question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (bi < ai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai. Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date. Input The first line contains a single positive integer n (1 ≤ n ≤ 5000) — the number of exams Valera will take. Each of the next n lines contains two positive space-separated integers ai and bi (1 ≤ bi < ai ≤ 109) — the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly. Output Print a single integer — the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date. Examples Input 3 5 2 3 1 4 2 Output 2 Input 3 6 1 5 2 4 3 Output 6 Note In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5. In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color x_{i} and the kit for away games of this team has color y_{i} (x_{i} ≠ y_{i}). In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n - 1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit. Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit. -----Input----- The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ 10^5; x_{i} ≠ y_{i}) — the color numbers for the home and away kits of the i-th team. -----Output----- For each team, print on a single line two space-separated integers — the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input. -----Examples----- Input 2 1 2 2 1 Output 2 0 2 0 Input 3 1 2 2 1 1 3 Output 3 1 4 0 2 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Прошло много лет, и на вечеринке снова встретились n друзей. С момента последней встречи техника шагнула далеко вперёд, появились фотоаппараты с автоспуском, и теперь не требуется, чтобы один из друзей стоял с фотоаппаратом, и, тем самым, оказывался не запечатлённым на снимке. Упрощенно процесс фотографирования можно описать следующим образом. На фотографии каждый из друзей занимает прямоугольник из пикселей: в стоячем положении i-й из них занимает прямоугольник ширины w_{i} пикселей и высоты h_{i} пикселей. Но также, при фотографировании каждый человек может лечь, и тогда он будет занимать прямоугольник ширины h_{i} пикселей и высоты w_{i} пикселей. Общая фотография будет иметь размеры W × H, где W — суммарная ширина всех прямоугольников-людей, а H — максимальная из высот. Друзья хотят определить, какую минимальную площадь может иметь общая фотография. Помогите им в этом. -----Входные данные----- В первой строке следует целое число n (1 ≤ n ≤ 1000) — количество друзей. В последующих n строках следуют по два целых числа w_{i}, h_{i} (1 ≤ w_{i}, h_{i} ≤ 1000), обозначающие размеры прямоугольника, соответствующего i-му из друзей. -----Выходные данные----- Выведите единственное целое число, равное минимальной возможной площади фотографии, вмещающей всех друзей. -----Примеры----- Входные данные 3 10 1 20 2 30 3 Выходные данные 180 Входные данные 3 3 1 2 2 4 3 Выходные данные 21 Входные данные 1 5 10 Выходные данные 50 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We want to find the numbers higher or equal than 1000 that the sum of every four consecutives digits cannot be higher than a certain given value. If the number is ``` num = d1d2d3d4d5d6 ```, and the maximum sum of 4 contiguous digits is ```maxSum```, then: ```python d1 + d2 + d3 + d4 <= maxSum d2 + d3 + d4 + d5 <= maxSum d3 + d4 + d5 + d6 <= maxSum ``` For that purpose, we need to create a function, ```max_sumDig()```, that receives ```nMax```, as the max value of the interval to study (the range (1000, nMax) ), and a certain value, ```maxSum```, the maximum sum that every four consecutive digits should be less or equal to. The function should output the following list with the data detailed bellow: ```[(1), (2), (3)]``` (1) - the amount of numbers that satisfy the constraint presented above (2) - the closest number to the mean of the results, if there are more than one, the smallest number should be chosen. (3) - the total sum of all the found numbers Let's see a case with all the details: ``` max_sumDig(2000, 3) -------> [11, 1110, 12555] (1) -There are 11 found numbers: 1000, 1001, 1002, 1010, 1011, 1020, 1100, 1101, 1110, 1200 and 2000 (2) - The mean of all the found numbers is: (1000 + 1001 + 1002 + 1010 + 1011 + 1020 + 1100 + 1101 + 1110 + 1200 + 2000) /11 = 1141.36363, so 1110 is the number that is closest to that mean value. (3) - 12555 is the sum of all the found numbers 1000 + 1001 + 1002 + 1010 + 1011 + 1020 + 1100 + 1101 + 1110 + 1200 + 2000 = 12555 Finally, let's see another cases ``` max_sumDig(2000, 4) -----> [21, 1120, 23665] max_sumDig(2000, 7) -----> [85, 1200, 99986] max_sumDig(3000, 7) -----> [141, 1600, 220756] ``` Happy coding!! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given n segments on a number line, numbered from 1 to n. The i-th segments covers all integer points from l_i to r_i and has a value w_i. You are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if there exists a selected segment that covers both of them. A subset is good if it's possible to reach point m starting from point 1 in arbitrary number of moves. The cost of the subset is the difference between the maximum and the minimum values of segments in it. Find the minimum cost of a good subset. In every test there exists at least one good subset. Input The first line contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5; 2 ≤ m ≤ 10^6) — the number of segments and the number of integer points. Each of the next n lines contains three integers l_i, r_i and w_i (1 ≤ l_i < r_i ≤ m; 1 ≤ w_i ≤ 10^6) — the description of the i-th segment. In every test there exists at least one good subset. Output Print a single integer — the minimum cost of a good subset. Examples Input 5 12 1 5 5 3 4 10 4 10 6 11 12 5 10 12 3 Output 3 Input 1 10 1 10 23 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place. You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either pa > pb, or pa = pb and ta < tb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places y + 1, y + 2, ..., y + x. The teams that performed worse than the teams from this group, get their places in the results table starting from the y + x + 1-th place. Your task is to count what number of teams from the given list shared the k-th place. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1 ≤ pi, ti ≤ 50) — the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. Output In the only line print the sought number of teams that got the k-th place in the final results' table. Examples Input 7 2 4 10 4 10 4 10 3 20 2 1 2 1 1 10 Output 3 Input 5 4 3 1 3 1 5 3 3 1 3 1 Output 4 Note The final results' table for the first sample is: * 1-3 places — 4 solved problems, the penalty time equals 10 * 4 place — 3 solved problems, the penalty time equals 20 * 5-6 places — 2 solved problems, the penalty time equals 1 * 7 place — 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams. The final table for the second sample is: * 1 place — 5 solved problems, the penalty time equals 3 * 2-5 places — 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. Input The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100). Output Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. Examples Input 3 4 1 7 -2 4 -1 1 -5 -3 Output NO Input 3 3 -1 7 -5 2 -4 2 -1 -3 Output YES Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given a string consisting of only numbers from 0 to 9, consider the operation of creating a new string from that string according to the following rules. Read the given string one character at a time from the left end. Go, if the same number a continues r, write the number r and the number a in this order without separating them with a space. Read to the right end of the given character string, and what is on the way to the end of the last writing Even if there are times of writing, all of them are counted as one operation. For the second and subsequent operations, the same operation is performed with the character string written out by the previous operation as the given character string. For example, "122244" If the character string "" is given, the character string obtained by one operation is "113224" and "44444444444" (11) because one 1, three 2, two 4s are given in order from the left end. In the case of 4), the obtained character string is “114”. Create a program that outputs a string obtained by performing the above operation n times on a given string of 100 characters or less, where n ≤ 20. The input data consists of two lines, the first line contains the number of operations n, and the second line contains the first character string. Input example --- Five 11 Output example 13112221 input The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5. output For each data set, the character string that has been operated the specified number of times is output on one line. Example Input 5 11 5 11 0 Output 13112221 13112221 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? Input The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. Output Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. Examples Input 5 1 2 4 3 3 Output 4 Input 8 2 3 4 4 2 1 3 1 Output 5 Note In the first test we can sort the children into four cars like this: * the third group (consisting of four children), * the fourth group (consisting of three children), * the fifth group (consisting of three children), * the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Suppose you have two points $p = (x_p, y_p)$ and $q = (x_q, y_q)$. Let's denote the Manhattan distance between them as $d(p, q) = |x_p - x_q| + |y_p - y_q|$. Let's say that three points $p$, $q$, $r$ form a bad triple if $d(p, r) = d(p, q) + d(q, r)$. Let's say that an array $b_1, b_2, \dots, b_m$ is good if it is impossible to choose three distinct indices $i$, $j$, $k$ such that the points $(b_i, i)$, $(b_j, j)$ and $(b_k, k)$ form a bad triple. You are given an array $a_1, a_2, \dots, a_n$. Calculate the number of good subarrays of $a$. A subarray of the array $a$ is the array $a_l, a_{l + 1}, \dots, a_r$ for some $1 \le l \le r \le n$. Note that, according to the definition, subarrays of length $1$ and $2$ are good. -----Input----- The first line contains one integer $t$ ($1 \le t \le 5000$) — the number of test cases. The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of array $a$. The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$). It's guaranteed that the sum of $n$ doesn't exceed $2 \cdot 10^5$. -----Output----- For each test case, print the number of good subarrays of array $a$. -----Examples----- Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 -----Note----- In the first test case, it can be proven that any subarray of $a$ is good. For example, subarray $[a_2, a_3, a_4]$ is good since it contains only three elements and: $d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3$ $<$ $d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7$; $d((a_2, 2), (a_3, 3))$ $<$ $d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3))$; $d((a_3, 3), (a_4, 4))$ $<$ $d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4))$; In the second test case, for example, subarray $[a_1, a_2, a_3, a_4]$ is not good, since it contains a bad triple $(a_1, 1)$, $(a_2, 2)$, $(a_4, 4)$: $d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6$; $d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4$; $d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2$; So, $d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4))$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Gag Segtree has $ N $ of "gags", each with a value of $ V_i $. Segtree decided to publish all the gags in any order. Here, the "joy" you get when you publish the $ i $ th gag to the $ j $ th is expressed as $ V_i --j $. Find the maximum sum of the "joy" you can get. input Input is given from standard input in the following format. $ N $ $ V_1 $ $ V_2 $ $ \ ldots $ $ V_N $ output Please output the maximum value of the sum of "joy". However, the value does not always fit in a 32-bit integer. Insert a line break at the end. Constraint * $ 1 \ leq N \ leq 10 ^ 5 $ * $ 1 \ leq V_i \ leq 10 ^ 5 $ * All inputs are integers. Input example 1 1 59549 Output example 1 59548 Input example 2 Five 2 1 8 5 7 Output example 2 8 Example Input 1 59549 Output 59548 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Your task is to write a program which reads a sequence of integers and prints mode values of the sequence. The mode value is the element which occurs most frequently. Input A sequence of integers ai (1 ≤ ai ≤ 100). The number of integers is less than or equals to 100. Output Print the mode values. If there are several mode values, print them in ascending order. Example Input 5 6 3 5 8 7 5 3 9 7 3 4 Output 3 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function `consonantCount`, `consonant_count` or `ConsonantCount` that takes a string of English-language text and returns the number of consonants in the string. Consonants are all letters used to write English excluding the vowels `a, e, i, o, u`. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. B: Ebi-chan and Integer Sequences- problem Ebi-chan likes sequences. I especially like arithmetic progressions. This time, I decided to create a sequence that meets the following conditions. * Arithmetic progression of length n * When the i-th element of the sequence is defined as s_i, all s_i (1 \ leq i \ leq n) are integers that satisfy 0 \ leq s_i \ leq m. How many sequences are there that satisfy the above conditions? However, the answer can be very large, so print the remainder after dividing by 10 ^ 9 + 7. Input format Input is given in one line. n m n represents the length of the sequence. Constraint * 1 \ leq n \ leq 10 ^ {15} * 0 \ leq m \ leq 10 ^ {15} Output format Divide the number of arithmetic progressions that satisfy the condition by 10 ^ 9 + 7 and output the remainder in one row. Input example 1 3 9 Output example 1 50 Input example 2 10000000000 10000000000 Output example 2 999999942 Note that the input does not fit in a 32-bit integer. Example Input 3 9 Output 50 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there. Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell. Help Vasya! Calculate the maximum total weight of mushrooms he can collect. -----Input----- The first line contains the number n (1 ≤ n ≤ 3·10^5) — the length of the glade. The second line contains n numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — the growth rate of mushrooms in the first row of the glade. The third line contains n numbers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^6) is the growth rate of mushrooms in the second row of the glade. -----Output----- Output one number — the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once. -----Examples----- Input 3 1 2 3 6 5 4 Output 70 Input 3 1 1000 10000 10 100 100000 Output 543210 -----Note----- In the first test case, the optimal route is as follows: [Image] Thus, the collected weight of mushrooms will be 0·1 + 1·2 + 2·3 + 3·4 + 4·5 + 5·6 = 70. In the second test case, the optimal route is as follows: [Image] Thus, the collected weight of mushrooms will be 0·1 + 1·10 + 2·100 + 3·1000 + 4·10000 + 5·100000 = 543210. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task An `amazon` (also known as a queen+knight compound) is an imaginary chess piece that can move like a `queen` or a `knight` (or, equivalently, like a `rook`, `bishop`, or `knight`). The diagram below shows all squares which the amazon attacks from e4 (circles represent knight-like moves while crosses correspond to queen-like moves). ![](https://codefightsuserpics.s3.amazonaws.com/tasks/amazonCheckmate/img/amazon.png?_tm=1473934566013) Recently you've come across a diagram with only three pieces left on the board: a `white amazon`, `white king` and `black king`. It's black's move. You don't have time to determine whether the game is over or not, but you'd like to figure it out in your head. Unfortunately, the diagram is smudged and you can't see the position of the `black king`, so it looks like you'll have to check them all. Given the positions of white pieces on a standard chessboard, determine the number of possible black king's positions such that: * It's a checkmate (i.e. black's king is under amazon's attack and it cannot make a valid move); * It's a check (i.e. black's king is under amazon's attack but it can reach a safe square in one move); * It's a stalemate (i.e. black's king is on a safe square but it cannot make a valid move); * Black's king is on a safe square and it can make a valid move. Note that two kings cannot be placed on two adjacent squares (including two diagonally adjacent ones). # Example For `king = "d3" and amazon = "e4"`, the output should be `[5, 21, 0, 29]`. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/amazonCheckmate/img/example1.png?_tm=1473934566299) `Red crosses` correspond to the `checkmate` positions, `orange pluses` refer to `checks` and `green circles` denote `safe squares`. For `king = "a1" and amazon = "g5"`, the output should be `[0, 29, 1, 29]`. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/amazonCheckmate/img/example2.png?_tm=1473934566670) `Stalemate` position is marked by a `blue square`. # Input - String `king` Position of white's king in chess notation. - String `amazon` Position of white's amazon in the same notation. Constraints: `amazon ≠ king.` # Output An array of four integers, each equal to the number of black's king positions corresponding to a specific situation. The integers should be presented in the same order as the situations were described, `i.e. 0 for checkmates, 1 for checks, etc`. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Roy and Biv have a set of n points on the infinite number line. Each point has one of 3 colors: red, green, or blue. Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects. They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly). However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue. Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected). Help them compute the minimum cost way to choose edges to satisfy the above constraints. -----Input----- The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points. The next n lines will contain two tokens p_{i} and c_{i} (p_{i} is an integer, 1 ≤ p_{i} ≤ 10^9, c_{i} is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order. -----Output----- Print a single integer, the minimum cost way to solve the problem. -----Examples----- Input 4 1 G 5 R 10 B 15 G Output 23 Input 4 1 G 2 R 3 B 10 G Output 12 -----Note----- In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Perhaps many have heard that the World Biathlon Championship has finished. Although our hero Valera was not present at this spectacular event himself and only watched it on TV, it excited him so much that he decided to enroll in a biathlon section. Of course, biathlon as any sport, proved very difficult in practice. It takes much time and effort. Workouts, workouts, and workouts, — that's what awaited Valera on his way to great achievements in biathlon. As for the workouts, you all probably know that every professional biathlete should ski fast and shoot precisely at the shooting range. Only in this case you can hope to be successful, because running and shooting are the two main components of biathlon. Valera has been diligent in his ski trainings, which is why he runs really fast, however, his shooting accuracy is nothing to write home about. On a biathlon base where Valera is preparing for the competition, there is a huge rifle range with n targets. Each target have shape of a circle, and the center of each circle is located on the Ox axis. At the last training session Valera made the total of m shots. To make monitoring of his own results easier for him, one rather well-known programmer (of course it is you) was commissioned to write a program that would reveal how many and which targets Valera hit. More specifically, for each target the program must print the number of the first successful shot (in the target), or "-1" if this was not hit. The target is considered hit if the shot is inside the circle or on its boundary. Valera is counting on you and perhaps, thanks to you he will one day win international competitions. Input The first line of the input file contains the integer n (1 ≤ n ≤ 104), which is the number of targets. The next n lines contain descriptions of the targets. Each target is a circle whose center is located on the Ox axis. Each circle is given by its coordinate of the center x ( - 2·104 ≤ x ≤ 2·104) and its radius r (1 ≤ r ≤ 1000). It is guaranteed that no two targets coincide, intersect or are nested into each other, but they can touch each other. The next line contains integer m (1 ≤ m ≤ 2·105), which is the number of shots. Next m lines contain descriptions of the shots, which are points on the plane, given by their coordinates x and y ( - 2·104 ≤ x, y ≤ 2·104). All the numbers in the input are integers. Targets and shots are numbered starting from one in the order of the input. Output Print on the first line a single number, the number of targets hit by Valera. Print on the second line for each of the targets the number of its first hit or "-1" (without quotes) if this number does not exist. Separate numbers with spaces. Examples Input 3 2 1 5 2 10 1 5 0 1 1 3 3 0 4 0 4 0 Output 2 3 3 -1 Input 3 3 2 7 1 11 2 4 2 1 6 0 6 4 11 2 Output 3 1 2 4 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke is going to open a contest named "AtCoder s Contest". Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters. Snuke has decided to abbreviate the name of the contest as "AxC". Here, x is the uppercase English letter at the beginning of s. Given the name of the contest, print the abbreviation of the name. -----Constraints----- - The length of s is between 1 and 100, inclusive. - The first character in s is an uppercase English letter. - The second and subsequent characters in s are lowercase English letters. -----Input----- The input is given from Standard Input in the following format: AtCoder s Contest -----Output----- Print the abbreviation of the name of the contest. -----Sample Input----- AtCoder Beginner Contest -----Sample Output----- ABC The contest in which you are participating now. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. 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----- 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----- 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. -----Examples----- Input 4 abab aabb Output 2 3 3 3 2 Input 1 a b Output -1 Input 8 babbaabb abababaa Output 3 2 6 1 3 7 8 -----Note----- In 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. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Simple enough this one - you will be given an array. The values in the array will either be numbers or strings, or a mix of both. You will not get an empty array, nor a sparse one. Your job is to return a single array that has first the numbers sorted in ascending order, followed by the strings sorted in alphabetic order. The values must maintain their original type. Note that numbers written as strings are strings and must be sorted with the other strings. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The new £5 notes have been recently released in the UK and they've certainly became a sensation! Even those of us who haven't been carrying any cash around for a while, having given in to the convenience of cards, suddenly like to have some of these in their purses and pockets. But how many of them could you get with what's left from your salary after paying all bills? The programme that you're about to write will count this for you! Given a salary and the array of bills, calculate your disposable income for a month and return it as a number of new £5 notes you can get with that amount. If the money you've got (or do not!) doesn't allow you to get any £5 notes return 0. £££ GOOD LUCK! £££ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1, p2, ..., pn. Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements. Input The single line of the input contains two space-separated positive integers n, k (1 ≤ k < n ≤ 105). Output Print n integers forming the permutation. If there are multiple answers, print any of them. Examples Input 3 2 Output 1 3 2 Input 3 1 Output 1 2 3 Input 5 2 Output 1 3 2 4 5 Note By |x| we denote the absolute value of number x. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Who's interested in football? Rayne Wooney has been one of the top players for his football club for the last few years. But unfortunately, he got injured during a game a few months back and has been out of play ever since. He's got proper treatment and is eager to go out and play for his team again. Before doing that, he has to prove to his fitness to the coach and manager of the team. Rayne has been playing practice matches for the past few days. He's played N practice matches in all. He wants to convince the coach and the manager that he's improved over time and that his injury no longer affects his game. To increase his chances of getting back into the team, he's decided to show them stats of any 2 of his practice games. The coach and manager will look into the goals scored in both the games and see how much he's improved. If the number of goals scored in the 2nd game(the game which took place later) is greater than that in 1st, then he has a chance of getting in. Tell Rayne what is the maximum improvement in terms of goal difference that he can show to maximize his chances of getting into the team. If he hasn't improved over time, he's not fit to play. Scoring equal number of goals in 2 matches will not be considered an improvement. Also, he will be declared unfit if he doesn't have enough matches to show an improvement. ------ Input: ------ The first line of the input contains a single integer T, the number of test cases. Each test case begins with a single integer N, the number of practice matches Rayne has played. The next line contains N integers. The ith integer, gi, on this line represents the number of goals Rayne scored in his ith practice match. The matches are given in chronological order i.e. j > i means match number j took place after match number i. ------ Output: ------ For each test case output a single line containing the maximum goal difference that Rayne can show to his coach and manager. If he's not fit yet, print "UNFIT". ------ Constraints: ------ 1≤T≤10 1≤N≤100000 0≤gi≤1000000 (Well, Rayne's a legend! You can expect him to score so many goals!) ----- Sample Input 1 ------ 3 6 3 7 1 4 2 4 5 5 4 3 2 1 5 4 3 2 2 3 ----- Sample Output 1 ------ 4 UNFIT 1 ----- explanation 1 ------ In the first test case, Rayne can choose the first and second game. Thus he gets a difference of 7-3=4 goals. Any other pair would give him a lower improvement. In the second test case, Rayne has not been improving in any match. Thus he's declared UNFIT. Note: Large input data. Use faster I/O methods. Prefer scanf,printf over cin/cout. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The only difference between easy and hard versions is constraints. Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them. Each day (during the morning) Ivan earns exactly one burle. There are $n$ types of microtransactions in the game. Each microtransaction costs $2$ burles usually and $1$ burle if it is on sale. Ivan has to order exactly $k_i$ microtransactions of the $i$-th type (he orders microtransactions during the evening). Ivan can order any (possibly zero) number of microtransactions of any types during any day (of course, if he has enough money to do it). If the microtransaction he wants to order is on sale then he can buy it for $1$ burle and otherwise he can buy it for $2$ burles. There are also $m$ special offers in the game shop. The $j$-th offer $(d_j, t_j)$ means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day. Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing. -----Input----- The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the number of types of microtransactions and the number of special offers in the game shop. The second line of the input contains $n$ integers $k_1, k_2, \dots, k_n$ ($0 \le k_i \le 2 \cdot 10^5$), where $k_i$ is the number of copies of microtransaction of the $i$-th type Ivan has to order. It is guaranteed that sum of all $k_i$ is not less than $1$ and not greater than $2 \cdot 10^5$. The next $m$ lines contain special offers. The $j$-th of these lines contains the $j$-th special offer. It is given as a pair of integers $(d_j, t_j)$ ($1 \le d_j \le 2 \cdot 10^5, 1 \le t_j \le n$) and means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day. -----Output----- Print one integer — the minimum day when Ivan can order all microtransactions he wants and actually start playing. -----Examples----- Input 5 6 1 2 0 2 0 2 4 3 3 1 5 1 2 1 5 2 3 Output 8 Input 5 3 4 2 1 3 2 3 5 4 2 2 5 Output 20 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mike has a sequence A = [a1, a2, ..., an] of length n. He considers the sequence B = [b1, b2, ..., bn] beautiful if the gcd of all its elements is bigger than 1, i.e. <image>. Mike wants to change his sequence in order to make it beautiful. In one move he can choose an index i (1 ≤ i < n), delete numbers ai, ai + 1 and put numbers ai - ai + 1, ai + ai + 1 in their place instead, in this order. He wants perform as few operations as possible. Find the minimal number of operations to make sequence A beautiful if it's possible, or tell him that it is impossible to do so. <image> is the biggest non-negative number d such that d divides bi for every i (1 ≤ i ≤ n). Input The first line contains a single integer n (2 ≤ n ≤ 100 000) — length of sequence A. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of sequence A. Output Output on the first line "YES" (without quotes) if it is possible to make sequence A beautiful by performing operations described above, and "NO" (without quotes) otherwise. If the answer was "YES", output the minimal number of moves needed to make sequence A beautiful. Examples Input 2 1 1 Output YES 1 Input 3 6 2 4 Output YES 0 Input 2 1 3 Output YES 1 Note In the first example you can simply make one move to obtain sequence [0, 2] with <image>. In the second example the gcd of the sequence is already greater than 1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Peter is a person with erratic sleep habits. He goes to sleep at twelve o'lock every midnight. He gets up just after one hour of sleep on some days; he may even sleep for twenty-three hours on other days. His sleeping duration changes in a cycle, where he always sleeps for only one hour on the first day of the cycle. Unfortunately, he has some job interviews this month. No doubt he wants to be in time for them. He can take anhydrous caffeine to reset his sleeping cycle to the beginning of the cycle anytime. Then he will wake up after one hour of sleep when he takes caffeine. But of course he wants to avoid taking caffeine as possible, since it may affect his health and accordingly his very important job interviews. Your task is to write a program that reports the minimum amount of caffeine required for Peter to attend all his interviews without being late, where the information about the cycle and the schedule of his interviews are given. The time for move to the place of each interview should be considered negligible. Input The input consists of multiple datasets. Each dataset is given in the following format: T t1 t2 ... tT N D1 M1 D2 M2 ... DN MN T is the length of the cycle (1 ≤ T ≤ 30); ti (for 1 ≤ i ≤ T ) is the amount of sleep on the i-th day of the cycle, given in hours (1 ≤ ti ≤ 23); N is the number of interviews (1 ≤ N ≤ 100); Dj (for 1 ≤ j ≤ N) is the day of the j-th interview (1 ≤ Dj ≤ 100); Mj (for 1 ≤ j ≤ N) is the hour when the j-th interview starts (1 ≤ Mj ≤ 23). The numbers in the input are all integers. t1 is always 1 as stated above. The day indicated by 1 is the first day in the cycle of Peter's sleep. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print the minimum number of times Peter needs to take anhydrous caffeine. Example Input 2 1 23 3 1 1 2 1 3 1 0 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all: * 'U': go up, (x, y) → (x, y+1); * 'D': go down, (x, y) → (x, y-1); * 'L': go left, (x, y) → (x-1, y); * 'R': go right, (x, y) → (x+1, y). The robot will do the operations in s from left to right, and repeat it infinite times. Help Fox Ciel to determine if after some steps the robot will located in (a, b). Input The first line contains two integers a and b, ( - 109 ≤ a, b ≤ 109). The second line contains a string s (1 ≤ |s| ≤ 100, s only contains characters 'U', 'D', 'L', 'R') — the command. Output Print "Yes" if the robot will be located at (a, b), and "No" otherwise. Examples Input 2 2 RU Output Yes Input 1 2 RU Output No Input -1 1000000000 LRRLU Output Yes Input 0 0 D Output Yes Note In the first and second test case, command string is "RU", so the robot will go right, then go up, then right, and then up and so on. The locations of its moves are (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2) → ... So it can reach (2, 2) but not (1, 2). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an expression of the form $a{+}b$, where $a$ and $b$ are integers from $0$ to $9$. You have to evaluate it and print the result. -----Input----- 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 an expression of the form $a{+}b$ ($0 \le a, b \le 9$, both $a$ and $b$ are integers). The integers are not separated from the $+$ sign. -----Output----- For each test case, print one integer — the result of the expression. -----Examples----- Input 4 4+2 0+0 3+7 8+9 Output 6 0 10 17 -----Note----- None Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis. Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point x_{i}. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task. Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression $\sum_{a \subseteq A, a \neq \varnothing} F(a)$. Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, $F(a) = \operatorname{max}_{i, j \in a}|x_{i} - x_{j}|$. Since the required sum can be quite large Noora asks to find it modulo 10^9 + 7. Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date. -----Input----- The first line contains one integer n (1 ≤ n ≤ 3·10^5) denoting the number of hacked computers. The second line contains n integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^9) denoting the coordinates of hacked computers. It is guaranteed that all x_{i} are distinct. -----Output----- Print a single integer — the required sum modulo 10^9 + 7. -----Examples----- Input 2 4 7 Output 3 Input 3 4 3 1 Output 9 -----Note----- There are three non-empty subsets in the first sample test:$\{4 \}$, $\{7 \}$ and $\{4,7 \}$. The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3. There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: $\{4,3 \}$, $\{4,1 \}$, $\{3,1 \}$, $\{4,3,1 \}$. In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A marine themed rival site to Codewars has started. Codwars is advertising their website all over the internet using subdomains to hide or obfuscate their domain to trick people into clicking on their site. Your task is to write a function that accepts a URL as a string and determines if it would result in an http request to codwars.com. Function should return true for all urls in the codwars.com domain. All other URLs should return false. The urls are all valid but may or may not contain http://, https:// at the beginning or subdirectories or querystrings at the end. For additional confusion, directories in can be named "codwars.com" in a url with the codewars.com domain and vise versa. Also, a querystring may contain codewars.com or codwars.com for any other domain - it should still return true or false based on the domain of the URL and not the domain in the querystring. Subdomains can also add confusion: for example `http://codwars.com.codewars.com` is a valid URL in the codewars.com domain in the same way that `http://mail.google.com` is a valid URL within google.com Urls will not necessarily have either codewars.com or codwars.com in them. The folks at Codwars aren't very good about remembering the contents of their paste buffers. All urls contain domains with a single TLD; you need not worry about domains like company.co.uk. ``` findCodwars("codwars.com"); // true findCodwars("https://subdomain.codwars.com/a/sub/directory?a=querystring"); // true findCodwars("codewars.com"); // false findCodwars("https://subdomain.codwars.codewars.com/a/sub/directory/codwars.com?a=querystring"); // false ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. [Image] Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a_1, a_2, ..., a_{k} such that $n = \prod_{i = 1}^{k} a_{i}$ in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that $\operatorname{gcd}(p, q) = 1$, where $gcd$ is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 10^9 + 7. Please note that we want $gcd$ of p and q to be 1, not $gcd$ of their remainders after dividing by 10^9 + 7. -----Input----- The first line of input contains a single integer k (1 ≤ k ≤ 10^5) — the number of elements in array Barney gave you. The second line contains k integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ 10^18) — the elements of the array. -----Output----- In the only line of output print a single string x / y where x is the remainder of dividing p by 10^9 + 7 and y is the remainder of dividing q by 10^9 + 7. -----Examples----- Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given string $s$ of length $n$ consisting of 0-s and 1-s. You build an infinite string $t$ as a concatenation of an infinite number of strings $s$, or $t = ssss \dots$ For example, if $s =$ 10010, then $t =$ 100101001010010... Calculate the number of prefixes of $t$ with balance equal to $x$. The balance of some string $q$ is equal to $cnt_{0, q} - cnt_{1, q}$, where $cnt_{0, q}$ is the number of occurrences of 0 in $q$, and $cnt_{1, q}$ is the number of occurrences of 1 in $q$. The number of such prefixes can be infinite; if it is so, you must say that. A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd". -----Input----- The first line contains the single integer $T$ ($1 \le T \le 100$) — the number of test cases. Next $2T$ lines contain descriptions of test cases — two lines per test case. The first line contains two integers $n$ and $x$ ($1 \le n \le 10^5$, $-10^9 \le x \le 10^9$) — the length of string $s$ and the desired balance, respectively. The second line contains the binary string $s$ ($|s| = n$, $s_i \in \{\text{0}, \text{1}\}$). It's guaranteed that the total sum of $n$ doesn't exceed $10^5$. -----Output----- Print $T$ integers — one per test case. For each test case print the number of prefixes or $-1$ if there is an infinite number of such prefixes. -----Example----- Input 4 6 10 010010 5 3 10101 1 0 0 2 0 01 Output 3 0 1 -1 -----Note----- In the first test case, there are 3 good prefixes of $t$: with length $28$, $30$ and $32$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Nauuo is a girl who loves writing comments. One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes. It's known that there were $x$ persons who would upvote, $y$ persons who would downvote, and there were also another $z$ persons who would vote, but you don't know whether they would upvote or downvote. Note that each of the $x+y+z$ people would vote exactly one time. There are three different results: if there are more people upvote than downvote, the result will be "+"; if there are more people downvote than upvote, the result will be "-"; otherwise the result will be "0". Because of the $z$ unknown persons, the result may be uncertain (i.e. there are more than one possible results). More formally, the result is uncertain if and only if there exist two different situations of how the $z$ persons vote, that the results are different in the two situations. Tell Nauuo the result or report that the result is uncertain. -----Input----- The only line contains three integers $x$, $y$, $z$ ($0\le x,y,z\le100$), corresponding to the number of persons who would upvote, downvote or unknown. -----Output----- If there is only one possible result, print the result : "+", "-" or "0". Otherwise, print "?" to report that the result is uncertain. -----Examples----- Input 3 7 0 Output - Input 2 0 1 Output + Input 1 1 0 Output 0 Input 0 0 1 Output ? -----Note----- In the first example, Nauuo would definitely get three upvotes and seven downvotes, so the only possible result is "-". In the second example, no matter the person unknown downvotes or upvotes, Nauuo would get more upvotes than downvotes. So the only possible result is "+". In the third example, Nauuo would definitely get one upvote and one downvote, so the only possible result is "0". In the fourth example, if the only one person upvoted, the result would be "+", otherwise, the result would be "-". There are two possible results, so the result is uncertain. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given two arrays, the purpose of this Kata is to check if these two arrays are the same. "The same" in this Kata means the two arrays contains arrays of 2 numbers which are same and not necessarily sorted the same way. i.e. [[2,5], [3,6]] is same as [[5,2], [3,6]] or [[6,3], [5,2]] or [[6,3], [2,5]] etc [[2,5], [3,6]] is NOT the same as [[2,3], [5,6]] Two empty arrays [] are the same [[2,5], [5,2]] is the same as [[2,5], [2,5]] but NOT the same as [[2,5]] [[2,5], [3,5], [6,2]] is the same as [[2,6], [5,3], [2,5]] or [[3,5], [6,2], [5,2]], etc An array can be empty or contain a minimun of one array of 2 integers and up to 100 array of 2 integers Note: 1. [[]] is not applicable because if the array of array are to contain anything, there have to be two numbers. 2. 100 randomly generated tests that can contains either "same" or "not same" arrays. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself. There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is p_{i}, possibly p_{i} = i; For each station i there exists exactly one station j such that p_{j} = i. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n). The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of p_{i} for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes. The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! -----Input----- The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations. The second line contains n integer numbers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the current structure of the subway. All these numbers are distinct. -----Output----- Print one number — the maximum possible value of convenience. -----Examples----- Input 3 2 1 3 Output 9 Input 5 1 5 4 3 2 Output 17 -----Note----- In the first example the mayor can change p_2 to 3 and p_3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3). In the second example the mayor can change p_2 to 4 and p_3 to 5. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Bessie is out grazing on the farm, which consists of $n$ fields connected by $m$ bidirectional roads. She is currently at field $1$, and will return to her home at field $n$ at the end of the day. The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has $k$ special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them. After the road is added, Bessie will return home on the shortest path from field $1$ to field $n$. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him! -----Input----- The first line contains integers $n$, $m$, and $k$ ($2 \le n \le 2 \cdot 10^5$, $n-1 \le m \le 2 \cdot 10^5$, $2 \le k \le n$) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains $k$ integers $a_1, a_2, \ldots, a_k$ ($1 \le a_i \le n$) — the special fields. All $a_i$ are distinct. The $i$-th of the following $m$ lines contains integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$), representing a bidirectional road between fields $x_i$ and $y_i$. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them. -----Output----- Output one integer, the maximum possible length of the shortest path from field $1$ to $n$ after Farmer John installs one road optimally. -----Examples----- Input 5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 Output 3 Input 5 4 2 2 4 1 2 2 3 3 4 4 5 Output 3 -----Note----- The graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields $3$ and $5$, and the resulting shortest path from $1$ to $5$ is length $3$. The graph for the second example is shown below. Farmer John must add a road between fields $2$ and $4$, and the resulting shortest path from $1$ to $5$ is length $3$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is a game that uses numbers called "Fizz Buzz". In this game, multiple players count the numbers one by one, starting with 1, and each player says only one number after the previous player. At that time, you must say "Fizz" if it is divisible by 3, "Buzz" if it is divisible by 5, and "FizzBuzz" if it is divisible by both. For example, the first 16 statements are as follows: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, ・ ・ ・ Taro decided to play "Fizz Buzz" with his friends. Taro and his colleagues decided the rules as follows. "The wrong person will drop out. The next person will start with the next number after the wrong number. That is, if you say 1, 2, 3, you made a mistake with 3, so you will start with 4." I play the game according to this rule, but because I am not used to the game, I sometimes do not notice that I made a mistake, and I cannot make a fair decision. So you decided to create a program that outputs the remaining people at the end of the set number of remarks so that Taro and his friends can enjoy this game. Create a program that inputs the number of players, the number of times spoken during the game, and each statement, and outputs the number of the remaining players at the end of the input in ascending order. However, the players are numbered from 1, and the order of speaking is also from the first player, and when the speaking is completed, the first player will speak again. If the player in turn has already dropped out, the next player will speak. Also, the program must ignore subsequent statements when the player is alone. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: m n s1 s2 :: sn The first line gives the number of players m (2 ≤ m ≤ 1000) and the number of remarks n (1 ≤ n ≤ 10000). The next n lines are given the i-th statement s1. si is an integer, Fizz, Buzz, or a string (up to 8 characters) that indicates FizzBuzz. The number of datasets does not exceed 50. Output For each input dataset, the number of the player remaining when the specified number of remarks is input is output in ascending order. Example Input 5 7 1 2 Fizz 4 Buzz 6 7 3 5 1 2 3 4 5 0 0 Output 2 3 4 5 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games. He came up with the following game. The player has a positive integer $n$. Initially the value of $n$ equals to $v$ and the player is able to do the following operation as many times as the player want (possibly zero): choose a positive integer $x$ that $x<n$ and $x$ is not a divisor of $n$, then subtract $x$ from $n$. The goal of the player is to minimize the value of $n$ in the end. Soon, Chouti found the game trivial. Can you also beat the game? -----Input----- The input contains only one integer in the first line: $v$ ($1 \le v \le 10^9$), the initial value of $n$. -----Output----- Output a single integer, the minimum value of $n$ the player can get. -----Examples----- Input 8 Output 1 Input 1 Output 1 -----Note----- In the first example, the player can choose $x=3$ in the first turn, then $n$ becomes $5$. He can then choose $x=4$ in the second turn to get $n=1$ as the result. There are other ways to get this minimum. However, for example, he cannot choose $x=2$ in the first turn because $2$ is a divisor of $8$. In the second example, since $n=1$ initially, the player can do nothing. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces. Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question. Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other. Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring. By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure. Input The input consists of multiple datasets. Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30. There is one line containing only 0 at the end of the input. Output Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1. Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day. Example Input 4 1 1 2 2 3 2 1 2 3 3 4 5 0 Output 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have N balls. The i-th ball has an integer A_i written on it. For each k=1, 2, ..., N, solve the following problem and print the answer. - Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal. -----Constraints----- - 3 \leq N \leq 2 \times 10^5 - 1 \leq A_i \leq N - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N A_1 A_2 ... A_N -----Output----- For each k=1,2,...,N, print a line containing the answer. -----Sample Input----- 5 1 1 2 1 2 -----Sample Output----- 2 2 3 2 3 Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2. From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal. Thus, the answer for k=1 is 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}. Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b): * \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j) Since the answer may be enormous, compute it modulo 998244353. Constraints * 1 \leq N \leq 200000 * 1 \leq A_i \leq 1000000 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_0\ A_1\ \cdots\ A_{N-1} Output Print the sum modulo 998244353. Examples Input 3 2 4 6 Output 22 Input 8 1 2 3 4 6 8 12 12 Output 313 Input 10 356822 296174 484500 710640 518322 888250 259161 609120 592348 713644 Output 353891724 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2). Input The first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-case Latin letters, and its length doesn't exceed 100. Output Output one number — length of the longest substring that can be met in the string at least twice. Examples Input abcd Output 0 Input ababa Output 3 Input zzz Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian as well. Given an array of N numbers, a pair of numbers is called good if difference between the two numbers is strictly less than D. Find out maximum possible sum of all good disjoint pairs that can be made from these numbers. Sum of X pairs is the sum of all 2*X numbers in the pairs. ------ Input ------ First line contains T, the number of test cases to follow. First line of each test case contains 2 space separated integers: N and D. Second line of each test case contains N space separated integers. ------ Output ------ For each test case, output the answer in a separate line. ------ Constraints ------ $1 ≤ T, N, D, Array Elements ≤ 10^{5}$ $1 ≤ Sum of N over all test cases ≤ 5*10^{5}$ ------ Note: ------ Pair (a,b) is disjoint with pair (c,d) if and only if indices of a, b, c and d in the array are distinct. ----- Sample Input 1 ------ 3 3 3 3 5 8 4 3 5 8 10 12 5 3 3 2 8 17 15 ----- Sample Output 1 ------ 8 22 37 ----- explanation 1 ------ Test Case 1: You can only take 1 pair out of 3 numbers. So pair(3,5) is only valid pair whose difference is 2. Test Case 3: You can take pairs(3,2) and (15,17) as the answer. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Implement a function which behaves like the 'uniq -c' command in UNIX. It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance together with the number of times a duplicate elements occurred in the original array. Example: ```python ['a','a','b','b','c','a','b','c'] --> [('a',2),('b',2),('c',1),('a',1),('b',1),('c',1)] ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!). The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one — to the 1-st and the 3-rd ones, the 3-rd one — only to the 2-nd one. The transitions are possible only between the adjacent sections. The spacecraft team consists of n aliens. Each of them is given a rank — an integer from 1 to n. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section a to section b only if it is senior in rank to all aliens who are in the segments a and b (besides, the segments a and b are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship. Alien A is senior in rank to alien B, if the number indicating rank A, is more than the corresponding number for B. At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task. Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo m. Input The first line contains two space-separated integers: n and m (1 ≤ n, m ≤ 109) — the number of aliens on the saucer and the number, modulo which you should print the answer, correspondingly. Output Print a single number — the answer to the problem modulo m. Examples Input 1 10 Output 2 Input 3 8 Output 2 Note In the first sample the only crew member moves from segment 3 to segment 2, and then from segment 2 to segment 1 without any problems. Thus, the whole moving will take two minutes. To briefly describe the movements in the second sample we will use value <image>, which would correspond to an alien with rank i moving from the segment in which it is at the moment, to the segment number j. Using these values, we will describe the movements between the segments in the second sample: <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>; In total: the aliens need 26 moves. The remainder after dividing 26 by 8 equals 2, so the answer to this test is 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task Your task is to sort the characters in a string according to the following rules: ``` - Rule1: English alphabets are arranged from A to Z, case insensitive. ie. "Type" --> "epTy" - Rule2: If the uppercase and lowercase of an English alphabet exist at the same time, they are arranged in the order of oringal input. ie. "BabA" --> "aABb" - Rule3: non English alphabet remain in their original position. ie. "By?e" --> "Be?y" ``` # Input/Output `[input]` string `s` A non empty string contains any characters(English alphabets or non English alphabets). `[output]` a string A sorted string according to the rules above. # Example For `s = "cba"`, the output should be `"abc"`. For `s = "Cba"`, the output should be `"abC"`. For `s = "cCBbAa"`, the output should be `"AaBbcC"`. For `s = "c b a"`, the output should be `"a b c"`. For `s = "-c--b--a-"`, the output should be `"-a--b--c-"`. For `s = "Codewars"`, the output should be `"aCdeorsw"`. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. All space-time unified dimension sugoroku tournament. You are representing the Earth in the 21st century in the tournament, which decides only one Sugoroku absolute champion out of more than 500 trillion participants. The challenge you are currently challenging is one-dimensional sugoroku with yourself as a frame. Starting from the start square at the end, roll a huge 6-sided die with 1 to 6 rolls one by one, and repeat the process by the number of rolls, a format you are familiar with. It's Sugoroku. If you stop at the goal square on the opposite end of the start square, you will reach the goal. Of course, the fewer times you roll the dice before you reach the goal, the better the result. There are squares with special effects, "○ square forward" and "○ square return", and if you stop there, you must advance or return by the specified number of squares. If the result of moving by the effect of the square stops at the effective square again, continue to move as instructed. However, this is a space-time sugoroku that cannot be captured with a straight line. Frighteningly, for example, "3 squares back" may be placed 3 squares ahead of "3 squares forward". If you stay in such a square and get stuck in an infinite loop due to the effect of the square, you have to keep going back and forth in the square forever. Fortunately, however, your body has an extraordinary "probability curve" that can turn the desired event into an entire event. With this ability, you can freely control the roll of the dice. Taking advantage of this advantage, what is the minimum number of times to roll the dice before reaching the goal when proceeding without falling into an infinite loop? Input N p1 p2 .. .. .. pN The integer N (3 ≤ N ≤ 100,000) is written on the first line of the input. This represents the number of Sugoroku squares. The squares are numbered from 1 to N. The starting square is number 1, then the number 2, 3, ..., N -1 in the order closer to the start, and the goal square is number N. If you roll the dice on the i-th square and get a j, move to the i + j-th square. However, if i + j exceeds N, it will not return by the extra number and will be considered as a goal. The following N lines contain the integer pi (-100,000 ≤ pi ≤ 100,000). The integer pi written on the 1 + i line represents the instruction written on the i-th cell. If pi> 0, it means "forward pi square", if pi <0, it means "go back -pi square", and if pi = 0, it has no effect on that square. p1 and pN are always 0. Due to the effect of the square, you will not be instructed to move before the start or after the goal. It should be assumed that the given sugoroku can reach the goal. Output Output the minimum number of dice rolls before reaching the goal. Examples Input 11 0 0 -2 0 -4 1 -1 2 0 0 0 Output 3 Input 12 0 0 7 0 2 0 0 3 -6 -2 1 0 Output 1 Input 8 0 4 -1 1 -2 -2 0 0 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task **_Given_** a **_Divisor and a Bound_** , *Find the largest integer N* , Such That , # Conditions : * **_N_** is *divisible by divisor* * **_N_** is *less than or equal to bound* * **_N_** is *greater than 0*. ___ # Notes * The **_parameters (divisor, bound)_** passed to the function are *only positive values* . * *It's guaranteed that* a **divisor is Found** . ___ # Input >> Output Examples ``` maxMultiple (2,7) ==> return (6) ``` ## Explanation: **_(6)_** is divisible by **_(2)_** , **_(6)_** is less than or equal to bound **_(7)_** , and **_(6)_** is > 0 . ___ ``` maxMultiple (10,50) ==> return (50) ``` ## Explanation: **_(50)_** *is divisible by* **_(10)_** , **_(50)_** is less than or equal to bound **_(50)_** , and **_(50)_** is > 0 .* ___ ``` maxMultiple (37,200) ==> return (185) ``` ## Explanation: **_(185)_** is divisible by **_(37)_** , **_(185)_** is less than or equal to bound **_(200)_** , and **_(185)_** is > 0 . ___ ___ ## [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [Bizarre Sorting-katas](https://www.codewars.com/collections/bizarre-sorting-katas) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou ~~~if:java Java's default return statement can be any `int`, a divisor **will** be found. ~~~ ~~~if:nasm ## NASM-specific notes The function declaration is `int max_multiple(int divisor, int bound)` where the first argument is the divisor and the second one is the bound. ~~~ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarp is flying in the airplane. Finally, it is his favorite time — the lunchtime. The BerAvia company stewardess is giving food consecutively to all the passengers from the 1-th one to the last one. Polycarp is sitting on seat m, that means, he will be the m-th person to get food. The flight menu has k dishes in total and when Polycarp boarded the flight, he had time to count the number of portions of each dish on board. Thus, he knows values a_1, a_2, ..., a_{k}, where a_{i} is the number of portions of the i-th dish. The stewardess has already given food to m - 1 passengers, gave Polycarp a polite smile and asked him what he would prefer. That's when Polycarp realized that they might have run out of some dishes by that moment. For some of the m - 1 passengers ahead of him, he noticed what dishes they were given. Besides, he's heard some strange mumbling from some of the m - 1 passengers ahead of him, similar to phrase 'I'm disappointed'. That happened when a passenger asked for some dish but the stewardess gave him a polite smile and said that they had run out of that dish. In that case the passenger needed to choose some other dish that was available. If Polycarp heard no more sounds from a passenger, that meant that the passenger chose his dish at the first try. Help Polycarp to find out for each dish: whether they could have run out of the dish by the moment Polyarp was served or that dish was definitely available. -----Input----- Each test in this problem consists of one or more input sets. First goes a string that contains a single integer t (1 ≤ t ≤ 100 000) — the number of input data sets in the test. Then the sets follow, each set is preceded by an empty line. The first line of each set of the input contains integers m, k (2 ≤ m ≤ 100 000, 1 ≤ k ≤ 100 000) — the number of Polycarp's seat and the number of dishes, respectively. The second line contains a sequence of k integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ 100 000), where a_{i} is the initial number of portions of the i-th dish. Then m - 1 lines follow, each line contains the description of Polycarp's observations about giving food to a passenger sitting in front of him: the j-th line contains a pair of integers t_{j}, r_{j} (0 ≤ t_{j} ≤ k, 0 ≤ r_{j} ≤ 1), where t_{j} is the number of the dish that was given to the j-th passenger (or 0, if Polycarp didn't notice what dish was given to the passenger), and r_{j} — a 1 or a 0, depending on whether the j-th passenger was or wasn't disappointed, respectively. We know that sum a_{i} equals at least m, that is,Polycarp will definitely get some dish, even if it is the last thing he wanted. It is guaranteed that the data is consistent. Sum m for all input sets doesn't exceed 100 000. Sum k for all input sets doesn't exceed 100 000. -----Output----- For each input set print the answer as a single line. Print a string of k letters "Y" or "N". Letter "Y" in position i should be printed if they could have run out of the i-th dish by the time the stewardess started serving Polycarp. -----Examples----- Input 2 3 4 2 3 2 1 1 0 0 0 5 5 1 2 1 3 1 3 0 0 0 2 1 4 0 Output YNNY YYYNY -----Note----- In the first input set depending on the choice of the second passenger the situation could develop in different ways: If he chose the first dish, then by the moment the stewardess reaches Polycarp, they will have run out of the first dish; If he chose the fourth dish, then by the moment the stewardess reaches Polycarp, they will have run out of the fourth dish; Otherwise, Polycarp will be able to choose from any of the four dishes. Thus, the answer is "YNNY". In the second input set there is, for example, the following possible scenario. First, the first passenger takes the only third dish, then the second passenger takes the second dish. Then, the third passenger asks for the third dish, but it is not available, so he makes disappointed muttering and ends up with the second dish. Then the fourth passenger takes the fourth dish, and Polycarp ends up with the choice between the first, fourth and fifth dish. Likewise, another possible scenario is when by the time the stewardess comes to Polycarp, they will have run out of either the first or the fifth dish (this can happen if one of these dishes is taken by the second passenger). It is easy to see that there is more than enough of the fourth dish, so Polycarp can always count on it. Thus, the answer is "YYYNY". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain. Initially, snowball is at height $h$ and it has weight $w$. Each second the following sequence of events happens: snowball's weights increases by $i$, where $i$ — is the current height of snowball, then snowball hits the stone (if it's present at the current height), then snowball moves one meter down. If the snowball reaches height zero, it stops. There are exactly two stones on the mountain. First stone has weight $u_1$ and is located at height $d_1$, the second one — $u_2$ and $d_2$ respectively. When the snowball hits either of two stones, it loses weight equal to the weight of that stone. If after this snowball has negative weight, then its weight becomes zero, but the snowball continues moving as before. [Image] Find the weight of the snowball when it stops moving, that is, it reaches height 0. -----Input----- First line contains two integers $w$ and $h$ — initial weight and height of the snowball ($0 \le w \le 100$; $1 \le h \le 100$). Second line contains two integers $u_1$ and $d_1$ — weight and height of the first stone ($0 \le u_1 \le 100$; $1 \le d_1 \le h$). Third line contains two integers $u_2$ and $d_2$ — weight and heigth of the second stone ($0 \le u_2 \le 100$; $1 \le d_2 \le h$; $d_1 \ne d_2$). Notice that stones always have different heights. -----Output----- Output a single integer — final weight of the snowball after it reaches height 0. -----Examples----- Input 4 3 1 1 1 2 Output 8 Input 4 3 9 2 0 1 Output 1 -----Note----- In the first example, initially a snowball of weight 4 is located at a height of 3, there are two stones of weight 1, at a height of 1 and 2, respectively. The following events occur sequentially: The weight of the snowball increases by 3 (current height), becomes equal to 7. The snowball moves one meter down, the current height becomes equal to 2. The weight of the snowball increases by 2 (current height), becomes equal to 9. The snowball hits the stone, its weight decreases by 1 (the weight of the stone), becomes equal to 8. The snowball moves one meter down, the current height becomes equal to 1. The weight of the snowball increases by 1 (current height), becomes equal to 9. The snowball hits the stone, its weight decreases by 1 (the weight of the stone), becomes equal to 8. The snowball moves one meter down, the current height becomes equal to 0. Thus, at the end the weight of the snowball is equal to 8. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a set of n points on the plane. A line containing the origin is called good, if projection of the given set to this line forms a symmetric multiset of points. Find the total number of good lines. Multiset is a set where equal elements are allowed. Multiset is called symmetric, if there is a point P on the plane such that the multiset is [centrally symmetric](https://en.wikipedia.org/wiki/Point_reflection) in respect of point P. Input The first line contains a single integer n (1 ≤ n ≤ 2000) — the number of points in the set. Each of the next n lines contains two integers xi and yi ( - 106 ≤ xi, yi ≤ 106) — the coordinates of the points. It is guaranteed that no two points coincide. Output If there are infinitely many good lines, print -1. Otherwise, print single integer — the number of good lines. Examples Input 3 1 2 2 1 3 3 Output 3 Input 2 4 3 1 2 Output -1 Note Picture to the first sample test: <image> In the second sample, any line containing the origin is good. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are a teacher at a cram school for elementary school pupils. One day, you showed your students how to calculate division of fraction in a class of mathematics. Your lesson was kind and fluent, and it seemed everything was going so well - except for one thing. After some experiences, a student Max got so curious about how precise he could compute the quotient. He tried many divisions asking you for a help, and finally found a case where the answer became an infinite fraction. He was fascinated with such a case, so he continued computing the answer. But it was clear for you the answer was an infinite fraction - no matter how many digits he computed, he wouldn’t reach the end. Since you have many other things to tell in today’s class, you can’t leave this as it is. So you decided to use a computer to calculate the answer in turn of him. Actually you succeeded to persuade him that he was going into a loop, so it was enough for him to know how long he could compute before entering a loop. Your task now is to write a program which computes where the recurring part starts and the length of the recurring part, for given dividend/divisor pairs. All computation should be done in decimal numbers. If the specified dividend/divisor pair gives a finite fraction, your program should treat the length of the recurring part as 0. Input The input consists of multiple datasets. Each line of the input describes a dataset. A dataset consists of two positive integers x and y, which specifies the dividend and the divisor, respectively. You may assume that 1 ≤ x < y ≤ 1,000,000. The last dataset is followed by a line containing two zeros. This line is not a part of datasets and should not be processed. Output For each dataset, your program should output a line containing two integers separated by exactly one blank character. The former describes the number of digits after the decimal point before the recurring part starts. And the latter describes the length of the recurring part. Example Input 1 3 1 6 3 5 2 200 25 99 0 0 Output 0 1 1 1 1 0 2 0 0 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered from 1 to N, and the item i weighs Wi grams. Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items. Chef does not want to burden his son. But he won't stop bothering him unless he is given a few items to carry. So Chef decides to give him some items. Obviously, Chef wants to give the kid less weight to carry. However, his son is a smart kid. To avoid being given the bare minimum weight to carry, he suggests that the items are split into two groups, and one group contains exactly K items. Then Chef will carry the heavier group, and his son will carry the other group. Help the Chef in deciding which items should the son take. Your task will be simple. Tell the Chef the maximum possible difference between the weight carried by him and the weight carried by the kid. -----Input:----- The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each test contains two space-separated integers N and K. The next line contains N space-separated integers W1, W2, ..., WN. -----Output:----- For each test case, output the maximum possible difference between the weights carried by both in grams. -----Constraints:----- - 1 ≤ T ≤ 100 - 1 ≤ K < N ≤ 100 - 1 ≤ Wi ≤ 100000 (105) -----Example:----- Input: 2 5 2 8 4 5 2 10 8 3 1 1 1 1 1 1 1 1 Output: 17 2 -----Explanation:----- Case #1: The optimal way is that Chef gives his son K=2 items with weights 2 and 4. Chef carries the rest of the items himself. Thus the difference is: (8+5+10) − (4+2) = 23 − 6 = 17. Case #2: Chef gives his son 3 items and he carries 5 items himself. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are 2N squares arranged from left to right. You are given a string of length 2N representing the color of each of the squares. The color of the i-th square from the left is black if the i-th character of S is `B`, and white if that character is `W`. You will perform the following operation exactly N times: choose two distinct squares, then invert the colors of these squares and the squares between them. Here, to invert the color of a square is to make it white if it is black, and vice versa. Throughout this process, you cannot choose the same square twice or more. That is, each square has to be chosen exactly once. Find the number of ways to make all the squares white at the end of the process, modulo 10^9+7. Two ways to make the squares white are considered different if and only if there exists i (1 \leq i \leq N) such that the pair of the squares chosen in the i-th operation is different. Constraints * 1 \leq N \leq 10^5 * |S| = 2N * Each character of S is `B` or `W`. Input Input is given from Standard Input in the following format: N S Output Print the number of ways to make all the squares white at the end of the process, modulo 10^9+7. If there are no such ways, print 0. Examples Input 2 BWWB Output 4 Input 4 BWBBWWWB Output 288 Input 5 WWWWWWWWWW Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given positive integers A and B. Find the K-th largest positive integer that divides both A and B. The input guarantees that there exists such a number. -----Constraints----- - All values in input are integers. - 1 \leq A, B \leq 100 - The K-th largest positive integer that divides both A and B exists. - K \geq 1 -----Input----- Input is given from Standard Input in the following format: A B K -----Output----- Print the K-th largest positive integer that divides both A and B. -----Sample Input----- 8 12 2 -----Sample Output----- 2 Three positive integers divides both 8 and 12: 1, 2 and 4. Among them, the second largest is 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. 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 $\operatorname{occ}(s^{\prime}, p)$ 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 $\operatorname{ans}(x)$ as maximum value of $\operatorname{occ}(s^{\prime}, p)$ over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know $\operatorname{ans}(x)$ for all x from 0 to |s| where |s| denotes the length of string s. -----Input----- 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----- Print |s| + 1 space-separated integers in a single line representing the $\operatorname{ans}(x)$ for all x from 0 to |s|. -----Examples----- Input aaaaa aa Output 2 2 1 1 0 0 Input axbaxxb ab Output 0 1 1 2 1 1 0 0 -----Note----- For 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", ""}. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In this Kata, you will be given a string and your task is to determine if that string can be a palindrome if we rotate one or more characters to the left. ```Haskell solve("4455") = true, because after 1 rotation, we get "5445" which is a palindrome solve("zazcbaabc") = true, because after 3 rotations, we get "abczazcba", a palindrome ``` More examples in test cases. Input will be strings of lowercase letters or numbers only. Good luck! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given $n$ segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. Your task is the following: for every $k \in [1..n]$, calculate the number of points with integer coordinates such that the number of segments that cover these points equals $k$. A segment with endpoints $l_i$ and $r_i$ covers point $x$ if and only if $l_i \le x \le r_i$. -----Input----- The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of segments. The next $n$ lines contain segments. The $i$-th line contains a pair of integers $l_i, r_i$ ($0 \le l_i \le r_i \le 10^{18}$) — the endpoints of the $i$-th segment. -----Output----- Print $n$ space separated integers $cnt_1, cnt_2, \dots, cnt_n$, where $cnt_i$ is equal to the number of points such that the number of segments that cover these points equals to $i$. -----Examples----- Input 3 0 3 1 3 3 8 Output 6 2 1 Input 3 1 3 2 4 5 7 Output 5 2 0 -----Note----- The picture describing the first example: [Image] Points with coordinates $[0, 4, 5, 6, 7, 8]$ are covered by one segment, points $[1, 2]$ are covered by two segments and point $[3]$ is covered by three segments. The picture describing the second example: [Image] Points $[1, 4, 5, 6, 7]$ are covered by one segment, points $[2, 3]$ are covered by two segments and there are no points covered by three segments. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Create an OR function, without use of the 'or' keyword, that takes an list of boolean values and runs OR against all of them. Assume there will be between 1 and 6 variables, and return None for an empty list. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke has four cookies with deliciousness A, B, C, and D. He will choose one or more from those cookies and eat them. Is it possible that the sum of the deliciousness of the eaten cookies is equal to that of the remaining cookies? -----Constraints----- - All values in input are integers. - 1 \leq A,B,C,D \leq 10^{8} -----Input----- Input is given from Standard Input in the following format: A B C D -----Output----- If it is possible that the sum of the deliciousness of the eaten cookies is equal to that of the remaining cookies, print Yes; otherwise, print No. -----Sample Input----- 1 3 2 4 -----Sample Output----- Yes - If he eats the cookies with deliciousness 1 and 4, the sum of the deliciousness of the eaten cookies will be equal to that of the remaining cookies. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him. <image> Thus, he came up with a puzzle to tell his mom his coordinates. His coordinates are the answer to the following problem. A string consisting only of parentheses ('(' and ')') is called a bracket sequence. Some bracket sequence are called correct bracket sequences. More formally: * Empty string is a correct bracket sequence. * if s is a correct bracket sequence, then (s) is also a correct bracket sequence. * if s and t are correct bracket sequences, then st (concatenation of s and t) is also a correct bracket sequence. A string consisting of parentheses and question marks ('?') is called pretty if and only if there's a way to replace each question mark with either '(' or ')' such that the resulting string is a non-empty correct bracket sequence. Will gave his mom a string s consisting of parentheses and question marks (using Morse code through the lights) and his coordinates are the number of pairs of integers (l, r) such that 1 ≤ l ≤ r ≤ |s| and the string slsl + 1... sr is pretty, where si is i-th character of s. Joyce doesn't know anything about bracket sequences, so she asked for your help. Input The first and only line of input contains string s, consisting only of characters '(', ')' and '?' (2 ≤ |s| ≤ 5000). Output Print the answer to Will's puzzle in the first and only line of output. Examples Input ((?)) Output 4 Input ??()?? Output 7 Note For the first sample testcase, the pretty substrings of s are: 1. "(?" which can be transformed to "()". 2. "?)" which can be transformed to "()". 3. "((?)" which can be transformed to "(())". 4. "(?))" which can be transformed to "(())". For the second sample testcase, the pretty substrings of s are: 1. "??" which can be transformed to "()". 2. "()". 3. "??()" which can be transformed to "()()". 4. "?()?" which can be transformed to "(())". 5. "??" which can be transformed to "()". 6. "()??" which can be transformed to "()()". 7. "??()??" which can be transformed to "()()()". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ilya plays a card game by the following rules. A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded. More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards. Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards? Input The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of cards Ilya has. Each of the next n lines contains two non-negative space-separated integers — ai and bi (0 ≤ ai, bi ≤ 104) — the numbers, written at the top and the bottom of the i-th card correspondingly. Output Print the single number — the maximum number of points you can score in one round by the described rules. Examples Input 2 1 0 2 0 Output 2 Input 3 1 0 2 0 0 2 Output 3 Note In the first sample none of two cards brings extra moves, so you should play the one that will bring more points. In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich. Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers $a$ and $b$ ($a < b$). After that, the student can apply any of the following operations any number of times: $a := a + 1$ (increase $a$ by $1$), $b := b + 1$ (increase $b$ by $1$), $a := a \ | \ b$ (replace $a$ with the bitwise OR of $a$ and $b$). To get full marks on the test, the student has to tell the teacher the minimum required number of operations to make $a$ and $b$ equal. Igor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make $a$ equal to $b$. -----Input----- 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 only line for each test case contains two integers $a$ and $b$ ($1 \le a < b \le 10^6$). It is guaranteed that the sum of $b$ over all test cases does not exceed $10^6$. -----Output----- For each test case print one integer — the minimum required number of operations to make $a$ and $b$ equal. -----Examples----- Input 5 1 3 5 8 2 5 3 19 56678 164422 Output 1 3 2 1 23329 -----Note----- In the first test case, it is optimal to apply the third operation. In the second test case, it is optimal to apply the first operation three times. In the third test case, it is optimal to apply the second operation and then the third operation. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Find the longest substring within a string that contains at most 2 unique characters. ``` substring("a") => "a" substring("aaa") => "aaa" substring("abacd") => "aba" substring("abacddcd") => "cddcd" substring("cefageaacceaccacca") => "accacca" ``` This function will take alphanumeric characters as input. In cases where there could be more than one correct answer, the first string occurrence should be used. For example, substring('abc') should return 'ab' instead of 'bc'. Although there are O(N^2) solutions to this problem, you should try to solve this problem in O(N) time. Tests may pass for O(N^2) solutions but, this is not guaranteed. This question is much harder than some of the other substring questions. It's easy to think that you have a solution and then get hung up on the implementation. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Problem There are n vertices that are not connected to any of the vertices. An undirected side is stretched between each vertex. Find out how many sides can be stretched when the diameter is set to d. The diameter represents the largest of the shortest distances between two vertices. Here, the shortest distance is the minimum value of the number of sides required to move between vertices. Multiple edges and self-loops are not allowed. Constraints * 2 ≤ n ≤ 109 * 1 ≤ d ≤ n−1 Input n d Two integers n and d are given on one line, separated by blanks. Output Output the maximum number of sides that can be stretched on one line. Examples Input 4 3 Output 3 Input 5 1 Output 10 Input 4 2 Output 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The only difference between easy and hard versions is the length of the string. You are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $s$ without changing order of remaining characters (in other words, it is guaranteed that $t$ is a subsequence of $s$). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from $s$ of maximum possible length such that after removing this substring $t$ will remain a subsequence of $s$. If you want to remove the substring $s[l;r]$ then the string $s$ will be transformed to $s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$ (where $|s|$ is the length of $s$). Your task is to find the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$. -----Input----- The first line of the input contains one string $s$ consisting of at least $1$ and at most $2 \cdot 10^5$ lowercase Latin letters. The second line of the input contains one string $t$ consisting of at least $1$ and at most $2 \cdot 10^5$ lowercase Latin letters. It is guaranteed that $t$ is a subsequence of $s$. -----Output----- Print one integer — the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$. -----Examples----- Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet. The Smart Beaver is going to bring some presents from ABBYY to the planets he will be visiting. The presents are packed in suitcases, x presents in each. The Beaver will take to the ship exactly a1 + ... + an suitcases. As the Beaver lands on the i-th planet, he takes ai suitcases and goes out. On the first day on the planet the Beaver takes a walk and gets to know the citizens. On the second and all subsequent days the Beaver gives presents to the citizens — each of the bi citizens gets one present per day. The Beaver leaves the planet in the evening of the day when the number of presents left is strictly less than the number of citizens (i.e. as soon as he won't be able to give away the proper number of presents the next day). He leaves the remaining presents at the hotel. The Beaver is going to spend exactly c days traveling. The time spent on flights between the planets is considered to be zero. In how many ways can one choose the positive integer x so that the planned voyage will take exactly c days? Input The first input line contains space-separated integers n and c — the number of planets that the Beaver is going to visit and the number of days he is going to spend traveling, correspondingly. The next n lines contain pairs of space-separated integers ai, bi (1 ≤ i ≤ n) — the number of suitcases he can bring to the i-th planet and the number of citizens of the i-th planet, correspondingly. The input limitations for getting 30 points are: * 1 ≤ n ≤ 100 * 1 ≤ ai ≤ 100 * 1 ≤ bi ≤ 100 * 1 ≤ c ≤ 100 The input limitations for getting 100 points are: * 1 ≤ n ≤ 104 * 0 ≤ ai ≤ 109 * 1 ≤ bi ≤ 109 * 1 ≤ c ≤ 109 Due to possible overflow, it is recommended to use the 64-bit arithmetic. In some solutions even the 64-bit arithmetic can overflow. So be careful in calculations! Output Print a single number k — the number of ways to choose x so as to travel for exactly c days. If there are infinitely many possible values of x, print -1. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Examples Input 2 5 1 5 2 4 Output 1 Note In the first example there is only one suitable value x = 5. Then the Beaver takes 1 suitcase with 5 presents to the first planet. Here he spends 2 days: he hangs around on the first day, and he gives away five presents on the second day. He takes 2 suitcases with 10 presents to the second planet. Here he spends 3 days — he gives away 4 presents on the second and the third days and leaves the remaining 2 presents at the hotel. In total, the Beaver spends 5 days traveling. For x = 4 or less the Beaver won't have enough presents for the second day on the first planet, so the voyage will end too soon. For x = 6 and more the Beaver will spend at least one more day on the second planet, and the voyage will take too long. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Create a program that outputs all leap years between the year a and year b. The leap year conditions are as follows. However, 0 <a ≤ b <3,000. If there is no leap year in the given period, output "NA". * The year is divisible by 4. * However, a year divisible by 100 is not a leap year. * However, a year divisible by 400 is a leap year. Input Given multiple datasets. The format of each dataset is as follows: a b Input ends when both a and b are 0. The number of datasets does not exceed 50. Output Print the year or NA for each dataset. Insert one blank line between the datasets. Example Input 2001 2010 2005 2005 2001 2010 0 0 Output 2004 2008 NA 2004 2008 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. 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 (x_1, y_1), an arbitrary corner of the table (x_2, y_2) and color all cells of the table (p, q), which meet both inequations: min(x_1, x_2) ≤ p ≤ max(x_1, x_2), min(y_1, y_2) ≤ q ≤ max(y_1, y_2). 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----- 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 a_{i}1, a_{i}2, ..., a_{im}. If a_{ij} equals zero, then cell (i, j) isn't good. Otherwise a_{ij} equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner. -----Output----- Print a single number — the minimum number of operations Simon needs to carry out his idea. -----Examples----- Input 3 3 0 0 0 0 1 0 0 0 0 Output 4 Input 4 3 0 0 0 0 0 1 1 0 0 0 0 0 Output 2 -----Note----- In the first sample, the sequence of operations can be like this: [Image] 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: [Image] 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). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have invented a time-machine which has taken you back to ancient Rome. Caeser is impressed with your programming skills and has appointed you to be the new information security officer. Caeser has ordered you to write a Caeser cipher to prevent Asterix and Obelix from reading his emails. A Caeser cipher shifts the letters in a message by the value dictated by the encryption key. Since Caeser's emails are very important, he wants all encryptions to have upper-case output, for example: If key = 3 "hello" -> KHOOR If key = 7 "hello" -> OLSSV Input will consist of the message to be encrypted and the encryption key. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1. One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on. The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1). Output In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi. Examples Input 10 2 1 3 1 4 2 5 1 6 2 7 5 8 6 9 8 10 5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 1 Output 2 4 7 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a string S consisting of digits between 1 and 9, inclusive. You can insert the letter + into some of the positions (possibly none) between two letters in this string. Here, + must not occur consecutively after insertion. All strings that can be obtained in this way can be evaluated as formulas. Evaluate all possible formulas, and print the sum of the results. -----Constraints----- - 1 \leq |S| \leq 10 - All letters in S are digits between 1 and 9, inclusive. -----Input----- The input is given from Standard Input in the following format: S -----Output----- Print the sum of the evaluated value over all possible formulas. -----Sample Input----- 125 -----Sample Output----- 176 There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated, - 125 - 1+25=26 - 12+5=17 - 1+2+5=8 Thus, the sum is 125+26+17+8=176. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have a set of $n$ discs, the $i$-th disc has radius $i$. Initially, these discs are split among $m$ towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top. You would like to assemble one tower containing all of those discs. To do so, you may choose two different towers $i$ and $j$ (each containing at least one disc), take several (possibly all) top discs from the tower $i$ and put them on top of the tower $j$ in the same order, as long as the top disc of tower $j$ is bigger than each of the discs you move. You may perform this operation any number of times. For example, if you have two towers containing discs $[6, 4, 2, 1]$ and $[8, 7, 5, 3]$ (in order from bottom to top), there are only two possible operations: move disc $1$ from the first tower to the second tower, so the towers are $[6, 4, 2]$ and $[8, 7, 5, 3, 1]$; move discs $[2, 1]$ from the first tower to the second tower, so the towers are $[6, 4]$ and $[8, 7, 5, 3, 2, 1]$. Let the difficulty of some set of towers be the minimum number of operations required to assemble one tower containing all of the discs. For example, the difficulty of the set of towers $[[3, 1], [2]]$ is $2$: you may move the disc $1$ to the second tower, and then move both discs from the second tower to the first tower. You are given $m - 1$ queries. Each query is denoted by two numbers $a_i$ and $b_i$, and means "merge the towers $a_i$ and $b_i$" (that is, take all discs from these two towers and assemble a new tower containing all of them in descending order of their radii from top to bottom). The resulting tower gets index $a_i$. For each $k \in [0, m - 1]$, calculate the difficulty of the set of towers after the first $k$ queries are performed. -----Input----- The first line of the input contains two integers $n$ and $m$ ($2 \le m \le n \le 2 \cdot 10^5$) — the number of discs and the number of towers, respectively. The second line contains $n$ integers $t_1$, $t_2$, ..., $t_n$ ($1 \le t_i \le m$), where $t_i$ is the index of the tower disc $i$ belongs to. Each value from $1$ to $m$ appears in this sequence at least once. Then $m - 1$ lines follow, denoting the queries. Each query is represented by two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le m$, $a_i \ne b_i$), meaning that, during the $i$-th query, the towers with indices $a_i$ and $b_i$ are merged ($a_i$ and $b_i$ are chosen in such a way that these towers exist before the $i$-th query). -----Output----- Print $m$ integers. The $k$-th integer ($0$-indexed) should be equal to the difficulty of the set of towers after the first $k$ queries are performed. -----Example----- Input 7 4 1 2 3 3 1 4 3 3 1 2 3 2 4 Output 5 4 2 0 -----Note----- The towers in the example are: before the queries: $[[5, 1], [2], [7, 4, 3], [6]]$; after the first query: $[[2], [7, 5, 4, 3, 1], [6]]$; after the second query: $[[7, 5, 4, 3, 2, 1], [6]]$; after the third query, there is only one tower: $[7, 6, 5, 4, 3, 2, 1]$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. G: Palindromic Subsequences problem Given a string S consisting only of lowercase letters, find out how many subsequences of this string S are not necessarily continuous and are palindromes. Here, a subsequence that is not necessarily continuous with S is an arbitrary selection of one or more characters | S | characters or less from the original character string S (the position of each character to be selected may be discontinuous), and they are used. Refers to a character string created by concatenating the characters in the original order. Note that an empty string is not allowed as a subsequence in this issue. Also, if the string X is a palindrome, it means that the original string X and the inverted X string X'are equal. Also note that even if the same palindrome is generated as a result of different subsequence arrangements, it will not be counted twice. For example, if S = `acpc`, both the subsequence consisting of only the second character and the subsequence consisting of only the fourth character are palindromes` c`, but this cannot be repeated multiple times, only once in total. I will count it. The answer can be very large, so print the remainder divided by 1,000,000,007. Input format S Constraint * 1 \ leq | S | \ leq 2,000 * S contains only lowercase letters Output format * Output the remainder of the answer divided by 1,000,000,007 on one line. Input example 1 acpc Output example 1 Five There are five types of subsequences of the string `acpc` that are not necessarily continuous and are palindromes:` a`, `c`,` cc`, `cpc`, and` p`. Note that we count the number of substring types. Input example 2 z Output example 2 1 The only subsequence that meets the condition is `z`. Note that an empty string is not allowed as a subsequence. Input example 3 madokamagica Output example 3 28 Example Input acpc Output 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have an N \times N square grid. We will paint each square in the grid either black or white. If we paint exactly A squares white, how many squares will be painted black? -----Constraints----- - 1 \leq N \leq 100 - 0 \leq A \leq N^2 -----Inputs----- Input is given from Standard Input in the following format: N A -----Outputs----- Print the number of squares that will be painted black. -----Sample Input----- 3 4 -----Sample Output----- 5 There are nine squares in a 3 \times 3 square grid. Four of them will be painted white, so the remaining five squares will be painted black. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers p_{i}, a_{i} and b_{i}, where p_{i} is the price of the i-th t-shirt, a_{i} is front color of the i-th t-shirt and b_{i} is back color of the i-th t-shirt. All values p_{i} are distinct, and values a_{i} and b_{i} are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color c_{j}. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. -----Input----- The first line contains single integer n (1 ≤ n ≤ 200 000) — the number of t-shirts. The following line contains sequence of integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 1 000 000 000), where p_{i} equals to the price of the i-th t-shirt. The following line contains sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 3), where a_{i} equals to the front color of the i-th t-shirt. The following line contains sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 3), where b_{i} equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≤ m ≤ 200 000) — the number of buyers. The following line contains sequence c_1, c_2, ..., c_{m} (1 ≤ c_{j} ≤ 3), where c_{j} equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. -----Output----- Print to the first line m integers — the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. -----Examples----- Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. *Inspired by the [Fold an Array](https://www.codewars.com/kata/fold-an-array) kata. This one is sort of similar but a little different.* --- ## Task You will receive an array as parameter that contains 1 or more integers and a number `n`. Here is a little visualization of the process: * Step 1: Split the array in two: ``` [1, 2, 5, 7, 2, 3, 5, 7, 8] / \ [1, 2, 5, 7] [2, 3, 5, 7, 8] ``` * Step 2: Put the arrays on top of each other: ``` [1, 2, 5, 7] [2, 3, 5, 7, 8] ``` * Step 3: Add them together: ``` [2, 4, 7, 12, 15] ``` Repeat the above steps `n` times or until there is only one number left, and then return the array. ## Example ``` Input: arr=[4, 2, 5, 3, 2, 5, 7], n=2 Round 1 ------- step 1: [4, 2, 5] [3, 2, 5, 7] step 2: [4, 2, 5] [3, 2, 5, 7] step 3: [3, 6, 7, 12] Round 2 ------- step 1: [3, 6] [7, 12] step 2: [3, 6] [7, 12] step 3: [10, 18] Result: [10, 18] ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A binary matrix is called good if every even length square sub-matrix has an odd number of ones. Given a binary matrix $a$ consisting of $n$ rows and $m$ columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all. All the terms above have their usual meanings — refer to the Notes section for their formal definitions. -----Input----- The first line of input contains two integers $n$ and $m$ ($1 \leq n \leq m \leq 10^6$ and $n\cdot m \leq 10^6$)  — the number of rows and columns in $a$, respectively. The following $n$ lines each contain $m$ characters, each of which is one of 0 and 1. If the $j$-th character on the $i$-th line is 1, then $a_{i,j} = 1$. Similarly, if the $j$-th character on the $i$-th line is 0, then $a_{i,j} = 0$. -----Output----- Output the minimum number of cells you need to change to make $a$ good, or output $-1$ if it's not possible at all. -----Examples----- Input 3 3 101 001 110 Output 2 Input 7 15 000100001010010 100111010110001 101101111100100 010000111111010 111010010100001 000011001111101 111111011010011 Output -1 -----Note----- In the first case, changing $a_{1,1}$ to $0$ and $a_{2,2}$ to $1$ is enough. You can verify that there is no way to make the matrix in the second case good. Some definitions — A binary matrix is one in which every element is either $1$ or $0$. A sub-matrix is described by $4$ parameters — $r_1$, $r_2$, $c_1$, and $c_2$; here, $1 \leq r_1 \leq r_2 \leq n$ and $1 \leq c_1 \leq c_2 \leq m$. This sub-matrix contains all elements $a_{i,j}$ that satisfy both $r_1 \leq i \leq r_2$ and $c_1 \leq j \leq c_2$. A sub-matrix is, further, called an even length square if $r_2-r_1 = c_2-c_1$ and $r_2-r_1+1$ is divisible by $2$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have two integers: A and B. Print the largest number among A + B, A - B, and A \times B. -----Constraints----- - All values in input are integers. - -100 \leq A,\ B \leq 100 -----Input----- Input is given from Standard Input in the following format: A B -----Output----- Print the largest number among A + B, A - B, and A \times B. -----Sample Input----- -13 3 -----Sample Output----- -10 The largest number among A + B = -10, A - B = -16, and A \times B = -39 is -10. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A tourist is visiting Byteland. The tourist knows English very well. The language of Byteland is rather different from English. To be exact it differs in following points: - Bytelandian alphabet has the same letters as English one, but possibly different in meaning. Like 'A' in Bytelandian may be 'M' in English. However this does not mean that 'M' in Bytelandian must be 'A' in English. More formally, Bytelindian alphabet is a permutation of English alphabet. It will be given to you and could be any possible permutation. Don't assume any other condition. - People of Byteland don't like to use invisible character for separating words. Hence instead of space (' ') they use underscore ('_'). Other punctuation symbols, like '?', '!' remain the same as in English. The tourist is carrying "The dummies guide to Bytelandian", for translation. The book is serving his purpose nicely. But he is addicted to sharing on BaceFook, and shares his numerous conversations in Byteland on it. The conversations are rather long, and it is quite tedious to translate for his English friends, so he asks you to help him by writing a program to do the same. -----Input----- The first line of the input contains an integer T, denoting the length of the conversation, and the string M, denoting the English translation of Bytelandian string "abcdefghijklmnopqrstuvwxyz". T and M are separated by exactly one space. Then T lines follow, each containing a Bytelandian sentence S which you should translate into English. See constraints for details. -----Output----- For each of the sentence in the input, output its English translation on a separate line. Replace each underscores ('_') with a space (' ') in the output. Each punctuation symbol (see below) should remain the same. Note that the uppercase letters in Bytelandian remain uppercase in English, and lowercase letters remain lowercase. See the example and its explanation for clarity. -----Constraints----- - 1 ≤ T ≤ 100 - M is a permutation of "abcdefghijklmnopqrstuvwxyz" - Each sentence is non-empty and contains at most 100 characters - Each sentence may contain only lowercase letters ('a'-'z'), uppercase letters ('A'-'Z'), underscores ('_') and punctuation symbols: dot ('.'), comma (','), exclamation ('!'), question-mark('?') -----Example----- Input: 5 qwertyuiopasdfghjklzxcvbnm Ph Pcssi Bpke_kdc_epclc_jcijsc_mihyo? Epcf_kdc_liswhyo_EIED_hy_Vimcvpcn_Zkdvp_siyo_viyecle. Ipp! Output: Hi Hello What are these people doing? They are solving TOTR in Codechef March long contest. Ohh! -----Explanation----- The string "qwertyuiopasdfghjklzxcvbnm" means that 'a' in Bytelandian is 'q' in English, 'b' in Bytelandian is 'w' in English, 'c' in Bytelandian is 'e' in English and so on. Thus to translate "Ph" (first sentence in example) to English: 1) We find that 'p' in Bytelandian means 'h' in English. So we replace 'P' with 'H'. 2) Then we see that 'h' in Bytelandian means 'i' in English. So we replace 'h' with 'i'. 3) Therefore, the translation is "Hi". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Introduction A grille cipher was a technique for encrypting a plaintext by writing it onto a sheet of paper through a pierced sheet (of paper or cardboard or similar). The earliest known description is due to the polymath Girolamo Cardano in 1550. His proposal was for a rectangular stencil allowing single letters, syllables, or words to be written, then later read, through its various apertures. The written fragments of the plaintext could be further disguised by filling the gaps between the fragments with anodyne words or letters. This variant is also an example of steganography, as are many of the grille ciphers. Wikipedia Link ![Tangiers1](https://upload.wikimedia.org/wikipedia/commons/8/8a/Tangiers1.png) ![Tangiers2](https://upload.wikimedia.org/wikipedia/commons/b/b9/Tangiers2.png) # Task Write a function that accepts two inputs: `message` and `code` and returns hidden message decrypted from `message` using the `code`. The `code` is a nonnegative integer and it decrypts in binary the `message`. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest". A palindrome is a string that reads the same forward or backward. The length of string B should be at most 10^4. It is guaranteed that there always exists such string. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 10^4. -----Input----- First line contains a string A (1 ≤ |A| ≤ 10^3) consisting of lowercase Latin letters, where |A| is a length of A. -----Output----- Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 10^4. If there are many possible B, print any of them. -----Examples----- Input aba Output aba Input ab Output aabaa -----Note----- In the first example, "aba" is a subsequence of "aba" which is a palindrome. In the second example, "ab" is a subsequence of "aabaa" which is a palindrome. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j (1 ≤ j ≤ n-2), that s_{j}s_{j+1}s_{j+2}="one" or s_{j}s_{j+1}s_{j+2}="two". For example: * Polycarp does not like strings "oneee", "ontwow", "twone" and "oneonetwo" (they all have at least one substring "one" or "two"), * Polycarp likes strings "oonnee", "twwwo" and "twnoe" (they have no substrings "one" and "two"). Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time. For example, if the string looks like s="onetwone", then if Polycarp selects two indices 3 and 6, then "onetwone" will be selected and the result is "ontwne". What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be? Input The first line of the input contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Next, the test cases are given. Each test case consists of one non-empty string s. Its length does not exceed 1.5⋅10^5. The string s consists only of lowercase Latin letters. It is guaranteed that the sum of lengths of all lines for all input data in the test does not exceed 1.5⋅10^6. Output Print an answer for each test case in the input in order of their appearance. The first line of each answer should contain r (0 ≤ r ≤ |s|) — the required minimum number of positions to be removed, where |s| is the length of the given line. The second line of each answer should contain r different integers — the indices themselves for removal in any order. Indices are numbered from left to right from 1 to the length of the string. If r=0, then the second line can be skipped (or you can print empty). If there are several answers, print any of them. Examples Input 4 onetwone testme oneoneone twotwo Output 2 6 3 0 3 4 1 7 2 1 4 Input 10 onetwonetwooneooonetwooo two one twooooo ttttwo ttwwoo ooone onnne oneeeee oneeeeeeetwooooo Output 6 18 11 12 1 6 21 1 1 1 3 1 2 1 6 0 1 4 0 1 1 2 1 11 Note In the first example, answers are: * "onetwone", * "testme" — Polycarp likes it, there is nothing to remove, * "oneoneone", * "twotwo". In the second example, answers are: * "onetwonetwooneooonetwooo", * "two", * "one", * "twooooo", * "ttttwo", * "ttwwoo" — Polycarp likes it, there is nothing to remove, * "ooone", * "onnne" — Polycarp likes it, there is nothing to remove, * "oneeeee", * "oneeeeeeetwooooo". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The postal system in the area where Masa lives has changed a bit. In this area, each post office is numbered consecutively from 1 to a different number, and mail delivered to a post office is intended from that post office via several post offices. Delivered to the post office. Mail "forwarding" is only done between specific post offices. However, the transfer is bidirectional between the post offices where the transfer is performed. If there are multiple routes for forwarding mail from a post office to the destination, use the route that minimizes the distance to the destination. Therefore, the forwarding destination will be the next post office on such a shortest path. If there are multiple routes with the shortest total distance, the postal office number that is the direct transfer destination is transferred to the younger one. <image> <image> By the way, the region is suffering from a serious labor shortage, and each post office has only one transfer person to transfer between post offices. They are doing their best to go back and forth. Of course, if the forwarding agent belonging to a post office has paid the mail when the mail arrives at that post office, the forwarding from that post office will be temporarily stopped. When they are at their post office, they depart immediately if there is mail that has not been forwarded from that post office, and return immediately after delivering it to the forwarding destination. When he returns from the destination post office, he will not carry the mail that will be forwarded to his post office, even if it is at that post office (the mail will be forwarded to that mail). It is the job of the post office transferman). If multiple mail items are collected at the time of forwarding, the mail that was delivered to the post office earliest is transferred first. Here, if there are multiple mail items that arrived at the same time, the mail is forwarded from the one with the youngest post office number that is the direct forwarding destination. If there is mail that has the same forwarding destination, it will also be forwarded together. Also, if the mail that should be forwarded to the same post office arrives at the same time as the forwarding agent's departure time, it will also be forwarded. It should be noted that they all take 1 time to travel a distance of 1. You will be given information about the transfer between post offices and a list of the times when the mail arrived at each post office. At this time, simulate the movement of the mail and report the time when each mail arrived at the destination post office. It can be assumed that all the times required during the simulation of the problem are in the range 0 or more and less than 231. Input The input consists of multiple datasets, and the end of the input is represented by a single line with only 0 0. The format of each dataset is as follows. The first line of the dataset is given the integers n (2 <= n <= 32) and m (1 <= m <= 496), separated by a single character space. n represents the total number of post offices and m represents the number of direct forwarding routes between post offices. There can never be more than one direct forwarding route between two post offices. On the next m line, three integers containing information on the direct transfer route between stations are written. The first and second are the postal numbers (1 or more and n or less) at both ends of the transfer route, and the last integer represents the distance between the two stations. The distance is greater than or equal to 1 and less than 10000. The next line contains the integer l (1 <= l <= 1000), which represents the number of mail items to process, followed by the l line, which contains the details of each piece of mail. Three integers are written at the beginning of each line. These are, in order, the sender's postal office number, the destination postal office number, and the time of arrival at the sender's postal office. At the end of the line, a string representing the label of the mail is written. This label must be between 1 and 50 characters in length and consists only of letters, numbers, hyphens ('-'), and underscores ('_'). Information on each of these mail items is written in chronological order of arrival at the post office of the sender. At the same time, the order is not specified. In addition, there is no mail with the same label, mail with the same origin and destination, or mail without a delivery route. Each number or string in the input line is separated by a single character space. Output Output l lines for each dataset. Each output follows the format below. For each mail, the time when the mail arrived is output on one line. On that line, first print the label of the mail, then with a one-character space, and finally print the time when the mail arrived at the destination post office. These are output in order of arrival time. If there are multiple mails arriving at the same time, the ASCII code of the label is output in ascending order. A blank line is inserted between the outputs corresponding to each dataset. Example Input 4 5 1 2 10 1 3 15 2 3 5 2 4 3 3 4 10 2 1 4 10 LoveLetter 2 3 20 Greetings 3 3 1 2 1 2 3 1 3 1 1 3 1 2 1 BusinessMailC 2 3 1 BusinessMailB 3 1 1 BusinessMailA 0 0 Output Greetings 25 LoveLetter 33 BusinessMailA 2 BusinessMailB 2 BusinessMailC 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have been speeding on a motorway and a police car had to stop you. The policeman is a funny guy that likes to play games. Before issuing penalty charge notice he gives you a choice to change your penalty. Your penalty charge is a combination of numbers like: speed of your car, speed limit in the area, speed of the police car chasing you, the number of police cars involved, etc. So, your task is to combine the given numbers and make the penalty charge to be as small as possible. For example, if you are given numbers ```[45, 30, 50, 1]``` your best choice is ```1304550``` Examples: ```Python ['45', '30', '50', '1'] => '1304550' ['100', '10', '1'] => '100101' ['32', '3'] => '323' ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Russian also. Chef likes shopping, and especially he likes to buy oranges. But right now he is short of money. He has only k rubles. There are n oranges. The i-th one costs cost_{i} rubles and has weight equal to weight_{i}. Chef wants to buy a set of oranges with the maximal possible weight. Please help him, and tell him this weight. ------ Input ------ The first line of the input contains an integer T denoting the number of test cases. The first line of each test case contains two numbers n and k. The following n lines contain two numbers cost_{i} and weight_{i} respectively. ------ Output ------ For each test case, output a single line containing maximal weight among all the affordable sets of oranges. ------ Constraints ------ $1 ≤ T ≤ 250 $ $1 ≤ n ≤ 10 $ $1 ≤ k ≤ 100000000 $ $1 ≤ weight_{i} ≤ 100000000 $ $1 ≤ cost_{i} ≤ 100000000 $ ------ Scoring ------ Subtask 1 (30 points): All the oranges' weights equals to 1. Subtask 2 (30 points): N = 5 Subtask 2 (40 points): See the constraints ----- Sample Input 1 ------ 2 1 3 2 2 3 4 2 1 2 2 3 5 ----- Sample Output 1 ------ 2 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≤ i ≤ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≤ i ≤ m) contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image> Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Having stayed home alone, Petya decided to watch forbidden films on the Net in secret. "What ungentlemanly behavior!" — you can say that, of course, but don't be too harsh on the kid. In his country films about the Martians and other extraterrestrial civilizations are forbidden. It was very unfair to Petya as he adored adventure stories that featured lasers and robots. Today Petya is watching a shocking blockbuster about the Martians called "R2:D2". What can "R2:D2" possibly mean? It might be the Martian time represented in the Martian numeral system. Petya knows that time on Mars is counted just like on the Earth (that is, there are 24 hours and each hour has 60 minutes). The time is written as "a:b", where the string a stands for the number of hours (from 0 to 23 inclusive), and string b stands for the number of minutes (from 0 to 59 inclusive). The only thing Petya doesn't know is in what numeral system the Martian time is written. Your task is to print the radixes of all numeral system which can contain the time "a:b". Input The first line contains a single string as "a:b" (without the quotes). There a is a non-empty string, consisting of numbers and uppercase Latin letters. String a shows the number of hours. String b is a non-empty string that consists of numbers and uppercase Latin letters. String b shows the number of minutes. The lengths of strings a and b are from 1 to 5 characters, inclusive. Please note that strings a and b can have leading zeroes that do not influence the result in any way (for example, string "008:1" in decimal notation denotes correctly written time). We consider characters 0, 1, ..., 9 as denoting the corresponding digits of the number's representation in some numeral system, and characters A, B, ..., Z correspond to numbers 10, 11, ..., 35. Output Print the radixes of the numeral systems that can represent the time "a:b" in the increasing order. Separate the numbers with spaces or line breaks. If there is no numeral system that can represent time "a:b", print the single integer 0. If there are infinitely many numeral systems that can represent the time "a:b", print the single integer -1. Note that on Mars any positional numeral systems with positive radix strictly larger than one are possible. Examples Input 11:20 Output 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Input 2A:13 Output 0 Input 000B:00001 Output -1 Note Let's consider the first sample. String "11:20" can be perceived, for example, as time 4:6, represented in the ternary numeral system or as time 17:32 in hexadecimal system. Let's consider the second sample test. String "2A:13" can't be perceived as correct time in any notation. For example, let's take the base-11 numeral notation. There the given string represents time 32:14 that isn't a correct time. Let's consider the third sample. String "000B:00001" can be perceived as a correct time in the infinite number of numeral systems. If you need an example, you can take any numeral system with radix no less than 12. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Pig Latin is an English language game where the goal is to hide the meaning of a word from people not aware of the rules. So, the goal of this kata is to wite a function that encodes a single word string to pig latin. The rules themselves are rather easy: 1) The word starts with a vowel(a,e,i,o,u) -> return the original string plus "way". 2) The word starts with a consonant -> move consonants from the beginning of the word to the end of the word until the first vowel, then return it plus "ay". 3) The result must be lowercase, regardless of the case of the input. If the input string has any non-alpha characters, the function must return None, null, Nothing (depending on the language). 4) The function must also handle simple random strings and not just English words. 5) The input string has no vowels -> return the original string plus "ay". For example, the word "spaghetti" becomes "aghettispay" because the first two letters ("sp") are consonants, so they are moved to the end of the string and "ay" is appended. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given $n$ rectangles on a plane with coordinates of their bottom left and upper right points. Some $(n-1)$ of the given $n$ rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary. Find any point with integer coordinates that belongs to at least $(n-1)$ given rectangles. -----Input----- The first line contains a single integer $n$ ($2 \le n \le 132\,674$) — the number of given rectangles. Each the next $n$ lines contains four integers $x_1$, $y_1$, $x_2$ and $y_2$ ($-10^9 \le x_1 < x_2 \le 10^9$, $-10^9 \le y_1 < y_2 \le 10^9$) — the coordinates of the bottom left and upper right corners of a rectangle. -----Output----- Print two integers $x$ and $y$ — the coordinates of any point that belongs to at least $(n-1)$ given rectangles. -----Examples----- Input 3 0 0 1 1 1 1 2 2 3 0 4 1 Output 1 1 Input 3 0 0 1 1 0 1 1 2 1 0 2 1 Output 1 1 Input 4 0 0 5 5 0 0 4 4 1 1 4 4 1 1 4 4 Output 1 1 Input 5 0 0 10 8 1 2 6 7 2 3 5 6 3 4 4 5 8 1 9 2 Output 3 4 -----Note----- The picture below shows the rectangles in the first and second samples. The possible answers are highlighted. [Image] The picture below shows the rectangles in the third and fourth samples. [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. problem During this time of winter in Japan, hot days continue in Australia in the Southern Hemisphere. IOI, who lives in Australia, decided to plan what clothes to wear based on the weather forecast for a certain D day. The maximum temperature on day i (1 ≤ i ≤ D) is predicted to be Ti degrees. IOI has N kinds of clothes, which are numbered from 1 to N. Clothes j (1 ≤ j ≤ N) are suitable for wearing on days when the maximum temperature is above Aj and below Bj. In addition, each clothes has an integer called "flashiness", and the flashiness of clothes j is Cj. For each of the D days, IOI chooses to wear one of the clothes suitable for wearing when the maximum temperature follows the weather forecast. You may choose the same clothes as many times as you like, or you may choose clothes that are never chosen in D days. IOI, who wanted to avoid wearing similar clothes in succession, decided to maximize the total absolute value of the difference in the flashiness of the clothes worn on consecutive days. That is, assuming that the clothes xi are selected on the i-day, we want to maximize the values ​​| Cx1 --Cx2 | + | Cx2 --Cx3 | +… + | CxD-1 --CxD |. Create a program to find this maximum value. input The input consists of 1 + D + N lines. On the first line, two integers D and N (2 ≤ D ≤ 200, 1 ≤ N ≤ 200) are written with a blank as a delimiter. D is the number of days to plan clothes and N is the number of clothes types IOI has. One integer Ti (0 ≤ Ti ≤ 60) is written in the i-th line (1 ≤ i ≤ D) of the following D lines. This means that the maximum temperature on day i is forecast to be Ti degrees. In the jth line (1 ≤ j ≤ N) of the following N lines, three integers Aj, Bj, Cj (0 ≤ Aj ≤ Bj ≤ 60, 0 ≤ Cj ≤ 100) are written. These indicate that clothing j is suitable for wearing on days when the maximum temperature is above Aj and below Bj, and the flashiness is Cj. It is guaranteed that there will be at least one piece of clothing suitable for wearing when the maximum temperature follows the weather forecast for every D day. output Output the total absolute value of the difference in the flashiness of clothes worn on consecutive days, that is, the maximum value of the values ​​| Cx1 --Cx2 | + | Cx2 --Cx3 | +… + | CxD-1 --CxD | in one line. .. Input / output example Input example 1 3 4 31 27 35 20 25 30 23 29 90 21 35 60 28 33 40 Output example 1 80 In the input / output example 1, the candidates for clothes on the first day are clothes 3 and 4, the candidates for clothes on the second day are clothes 2 and clothes 3, and the candidates for clothes on the third day are only clothes 3. is there. Choose clothes 4 on the first day, clothes 2 on the second day, and clothes 3 on the third day. That is, x1 = 4, x2 = 2, x3 = 3. At this time, the absolute value of the difference in the flashiness of the clothes on the first day and the second day is | 40 --90 | = 50, and the absolute value of the difference in the flashiness of the clothes on the second and third days is | 90-60 | = 30. The total is 80, which is the maximum value. Input example 2 5 2 26 28 32 29 34 30 35 0 25 30 100 Output example 2 300 In Example 2 of input / output, clothes 2 on the first day, clothes 2 on the second day, clothes 1 on the third day, clothes 2 on the fourth day, and clothes 1 on the fifth day. You have to choose. At this time, the required value is | 100 --100 | + | 100 --0 | + | 0 --100 | + | 100 --0 | = 300. The question text and the data used for the automatic referee are the question text and the test data for scoring, which are created and published by the Japan Committee for Information Olympics. Example Input 3 4 31 27 35 20 25 30 23 29 90 21 35 60 28 33 40 Output 80 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Chef and Roma are playing a game. Rules of the game are quite simple. Initially there are N piles of stones on the table. In each turn, a player can choose one pile and remove it from the table. Each player want to maximize the total number of stones removed by him. Chef takes the first turn. Please tell Chef the maximum number of stones he can remove assuming that both players play optimally. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the number of piles. The second line contains N space separated integers A1, A2, ..., AN denoting the number of stones in each pile. -----Output----- For each test case, output a single line containg the maximum number of stones that Chef can remove. -----Constraints----- - 1 ≤ Ai ≤ 109 - Subtask 1 (35 points): T = 10, 1 ≤ N ≤ 1000 - Subtask 2 (65 points): T = 10, 1 ≤ N ≤ 105 -----Example----- Input: 2 3 1 2 3 3 1 2 1 Output: 4 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Princess'Gamble Princess gambling English text is not available in this practice contest. One day, a brave princess in a poor country's tomboy broke the walls of her room, escaped from the castle, and entered the gambling hall where horse racing and other gambling were held. However, the princess who had never gambled was very defeated. The princess, who found this situation uninteresting, investigated how gambling was carried out. Then, in such gambling, it was found that the dividend was decided by a method called the parimutuel method. The parimutuel method is a calculation method used to determine dividends in gambling for races. In this method, all the stakes are pooled, a certain percentage is deducted, and then the amount proportional to the stakes is distributed to the winners. In the gambling that the princess is currently enthusiastic about, participants buy a 100 gold voting ticket to predict which player will win before the competition and receive a winning prize if the result of the competition matches the prediction. It's about getting the right. Gold is the currency unit of this country. Your job is to write a program that calculates the payout per voting ticket based on the competition information given as input. If the dividend amount calculated by the above method is not an integer, round it down to an integer. Input The input consists of multiple datasets. The number of data sets is 100 or less. After the last dataset, a line of "0 0 0" is given to mark the end of the input. Each data set has the following format. > N M P > X1 > ... > XN In the first line, N is the number of players to vote for, M is the number of the winning player, and P is an integer representing the deduction rate (percentage). Xi is the number of voting tickets voted for the i-th competitor. It may be assumed that 1 ≤ N ≤ 100, 1 ≤ M ≤ N, 0 ≤ P ≤ 100, 0 ≤ Xi ≤ 1000. Output For each dataset, output a line of integers indicating the payout amount per winning voting ticket. Output 0 if no one has won the bet. There must be no other characters on the output line. Sample Input 3 2 50 1 2 3 4 4 75 1 2 3 0 3 1 10 8 1 1 0 0 0 Output for the Sample Input 150 0 112 Example Input 3 2 50 1 2 3 4 4 75 1 2 3 0 3 1 10 8 1 1 0 0 0 Output 150 0 112 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city. Let's represent the city as an area of $n \times n$ square blocks. Yura needs to move from the block with coordinates $(s_x,s_y)$ to the block with coordinates $(f_x,f_y)$. In one minute Yura can move to any neighboring by side block; in other words, he can move in four directions. Also, there are $m$ instant-movement locations in the city. Their coordinates are known to you and Yura. Yura can move to an instant-movement location in no time if he is located in a block with the same coordinate $x$ or with the same coordinate $y$ as the location. Help Yura to find the smallest time needed to get home. -----Input----- The first line contains two integers $n$ and $m$ — the size of the city and the number of instant-movement locations ($1 \le n \le 10^9$, $0 \le m \le 10^5$). The next line contains four integers $s_x$ $s_y$ $f_x$ $f_y$ — the coordinates of Yura's initial position and the coordinates of his home ($ 1 \le s_x, s_y, f_x, f_y \le n$). Each of the next $m$ lines contains two integers $x_i$ $y_i$ — coordinates of the $i$-th instant-movement location ($1 \le x_i, y_i \le n$). -----Output----- In the only line print the minimum time required to get home. -----Examples----- Input 5 3 1 1 5 5 1 2 4 1 3 3 Output 5 Input 84 5 67 59 41 2 39 56 7 2 15 3 74 18 22 7 Output 42 -----Note----- In the first example Yura needs to reach $(5, 5)$ from $(1, 1)$. He can do that in $5$ minutes by first using the second instant-movement location (because its $y$ coordinate is equal to Yura's $y$ coordinate), and then walking $(4, 1) \to (4, 2) \to (4, 3) \to (5, 3) \to (5, 4) \to (5, 5)$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Dreamoon likes coloring cells very much. There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n. You are given an integer m and m integers l_1, l_2, …, l_m (1 ≤ l_i ≤ n) Dreamoon will perform m operations. In i-th operation, Dreamoon will choose a number p_i from range [1, n-l_i+1] (inclusive) and will paint all cells from p_i to p_i+l_i-1 (inclusive) in i-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation. Dreamoon hopes that after these m operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose p_i in each operation to satisfy all constraints. Input The first line contains two integers n,m (1 ≤ m ≤ n ≤ 100 000). The second line contains m integers l_1, l_2, …, l_m (1 ≤ l_i ≤ n). Output If it's impossible to perform m operations to satisfy all constraints, print "'-1" (without quotes). Otherwise, print m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n - l_i + 1), after these m operations, all colors should appear at least once and all cells should be colored. If there are several possible solutions, you can print any. Examples Input 5 3 3 2 2 Output 2 4 1 Input 10 1 1 Output -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is a_{i}. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in. For example, consider the case when the mother has 5 flowers, and their moods are equal to 1, - 2, 1, 3, - 4. Suppose the mother suggested subarrays (1, - 2), (3, - 4), (1, 3), (1, - 2, 1, 3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1·1 = 1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds ( - 2)·1 = - 2, because he is in one of chosen subarrays, the third flower adds 1·2 = 2, because he is in two of chosen subarrays, the fourth flower adds 3·2 = 6, because he is in two of chosen subarrays, the fifth flower adds ( - 4)·0 = 0, because he is in no chosen subarrays. Thus, in total 1 + ( - 2) + 2 + 6 + 0 = 7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this! Alyona can choose any number of the subarrays, even 0 or all suggested by her mother. -----Input----- The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moods — n integers a_1, a_2, ..., a_{n} ( - 100 ≤ a_{i} ≤ 100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) denoting the subarray a[l_{i}], a[l_{i} + 1], ..., a[r_{i}]. Each subarray can encounter more than once. -----Output----- Print single integer — the maximum possible value added to the Alyona's happiness. -----Examples----- Input 5 4 1 -2 1 3 -4 1 2 4 5 3 4 1 4 Output 7 Input 4 3 1 2 3 4 1 3 2 4 1 1 Output 16 Input 2 2 -1 -2 1 1 1 2 Output 0 -----Note----- The first example is the situation described in the statements. In the second example Alyona should choose all subarrays. The third example has answer 0 because Alyona can choose none of the subarrays. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Background My TV remote control has arrow buttons and an `OK` button. I can use these to move a "cursor" on a logical screen keyboard to type words... # Keyboard The screen "keyboard" layout looks like this #tvkb { width : 400px; border: 5px solid gray; border-collapse: collapse; } #tvkb td { color : orange; background-color : black; text-align : center; border: 3px solid gray; border-collapse: collapse; } abcde123 fghij456 klmno789 pqrst.@0 uvwxyz_/ aASP * `aA` is the SHIFT key. Pressing this key toggles alpha characters between UPPERCASE and lowercase * `SP` is the space character * The other blank keys in the bottom row have no function # Kata task How many button presses on my remote are required to type the given `words`? ## Hint This Kata is an extension of the earlier ones in this series. You should complete those first. ## Notes * The cursor always starts on the letter `a` (top left) * The alpha characters are initially lowercase (as shown above) * Remember to also press `OK` to "accept" each letter * Take the shortest route from one letter to the next * The cursor wraps, so as it moves off one edge it will reappear on the opposite edge * Although the blank keys have no function, you may navigate through them if you want to * Spaces may occur anywhere in the `words` string * Do not press the SHIFT key until you need to. For example, with the word `e.Z`, the SHIFT change happens **after** the `.` is pressed (not before) # Example words = `Code Wars` * C => `a`-`aA`-OK-`A`-`B`-`C`-OK = 6 * o => `C`-`B`-`A`-`aA`-OK-`u`-`v`-`w`-`x`-`y`-`t`-`o`-OK = 12 * d => `o`-`j`-`e`-`d`-OK = 4 * e => `d`-`e`-OK = 2 * space => `e`-`d`-`c`-`b`-`SP`-OK = 5 * W => `SP`-`aA`-OK-`SP`-`V`-`W`-OK = 6 * a => `W`-`V`-`U`-`aA`-OK-`a`-OK = 6 * r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6 * s => `r`-`s`-OK = 2 Answer = 6 + 12 + 4 + 2 + 5 + 6 + 6 + 6 + 2 = 49 *Good Luck! DM.* Series * TV Remote * TV Remote (shift and space) * TV Remote (wrap) * TV Remote (symbols) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mainak has an array $a_1, a_2, \ldots, a_n$ of $n$ positive integers. He will do the following operation to this array exactly once: Pick a subsegment of this array and cyclically rotate it by any amount. Formally, he can do the following exactly once: Pick two integers $l$ and $r$, such that $1 \le l \le r \le n$, and any positive integer $k$. Repeat this $k$ times: set $a_l=a_{l+1}, a_{l+1}=a_{l+2}, \ldots, a_{r-1}=a_r, a_r=a_l$ (all changes happen at the same time). Mainak wants to maximize the value of $(a_n - a_1)$ after exactly one such operation. Determine the maximum value of $(a_n - a_1)$ that he can obtain. -----Input----- Each test contains multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 50$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 2000$). The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 999$). It is guaranteed that the sum of $n$ over all test cases does not exceed $2000$. -----Output----- For each test case, output a single integer — the maximum value of $(a_n - a_1)$ that Mainak can obtain by doing the operation exactly once. -----Examples----- Input 5 6 1 3 9 11 5 7 1 20 3 9 99 999 4 2 1 8 1 3 2 1 5 Output 10 0 990 7 4 -----Note----- In the first test case, we can rotate the subarray from index $3$ to index $6$ by an amount of $2$ (i.e. choose $l = 3$, $r = 6$ and $k = 2$) to get the optimal array: $$[1, 3, \underline{9, 11, 5, 7}] \longrightarrow [1, 3, \underline{5, 7, 9, 11}]$$ So the answer is $a_n - a_1 = 11 - 1 = 10$. In the second testcase, it is optimal to rotate the subarray starting and ending at index $1$ and rotating it by an amount of $2$. In the fourth testcase, it is optimal to rotate the subarray starting from index $1$ to index $4$ and rotating it by an amount of $3$. So the answer is $8 - 1 = 7$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. 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 w_{i} 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 w_{i} · l energy units (w_{i} 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 Q_{l} energy units; Take the rightmost item with the right hand and spend w_{j} · r energy units (w_{j} 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 Q_{r} 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----- The first line contains five integers n, l, r, Q_{l}, Q_{r} (1 ≤ n ≤ 10^5; 1 ≤ l, r ≤ 100; 1 ≤ Q_{l}, Q_{r} ≤ 10^4). The second line contains n integers w_1, w_2, ..., w_{n} (1 ≤ w_{i} ≤ 100). -----Output----- In the single line print a single number — the answer to the problem. -----Examples----- Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 -----Note----- Consider 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. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.