question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin letters. String w has the length of |w|, its characters are numbered from 1 to |w|. First Petya should find all the occurrences of forbidden substrings in the w string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings "aBC" and "ABc" are considered equal. After that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position i should be replaced by any other one if for position i in string w there exist pair of indices l, r (1 ≀ l ≀ i ≀ r ≀ |w|) such that substring w[l ... r] is contained in the collection s1, s2, ..., sn, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring. Letter letter (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the letter occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically. Note that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them. Input The first line contains the only integer n (1 ≀ n ≀ 100) β€” the number of forbidden substrings in the collection. Next n lines contain these substrings. The next line contains string w. All those n + 1 lines are non-empty strings consisting of uppercase and lowercase Latin letters whose length does not exceed 100. The last line contains a lowercase letter letter. Output Output the only line β€” Petya's resulting string with the maximum number of letters letter. If there are several answers then output the one that comes first lexicographically. The lexicographical comparison is performed by the standard < operator in modern programming languages. The line a is lexicographically smaller than the line b, if a is a prefix of b, or there exists such an i (1 ≀ i ≀ |a|), that ai < bi, and for any j (1 ≀ j < i) aj = bj. |a| stands for the length of string a. Examples Input 3 bers ucky elu PetrLoveLuckyNumbers t Output PetrLovtTttttNumtttt Input 4 hello party abefglghjdhfgj IVan petrsmatchwin a Output petrsmatchwin Input 2 aCa cba abAcaba c Output abCacba 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 directed graph consisting of $n$ vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process $m$ queries with it. Each query is one of three types: "$+$ $u$ $v$ $c$" β€” add arc from $u$ to $v$ with label $c$. It's guaranteed that there is no arc $(u, v)$ in the graph at this moment; "$-$ $u$ $v$" β€” erase arc from $u$ to $v$. It's guaranteed that the graph contains arc $(u, v)$ at this moment; "$?$ $k$" β€” find the sequence of $k$ vertices $v_1, v_2, \dots, v_k$ such that there exist both routes $v_1 \to v_2 \to \dots \to v_k$ and $v_k \to v_{k - 1} \to \dots \to v_1$ and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times. -----Input----- The first line contains two integers $n$ and $m$ ($2 \le n \le 2 \cdot 10^5$; $1 \le m \le 2 \cdot 10^5$) β€” the number of vertices in the graph and the number of queries. The next $m$ lines contain queries β€” one per line. Each query is one of three types: "$+$ $u$ $v$ $c$" ($1 \le u, v \le n$; $u \neq v$; $c$ is a lowercase Latin letter); "$-$ $u$ $v$" ($1 \le u, v \le n$; $u \neq v$); "$?$ $k$" ($2 \le k \le 10^5$). It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type. -----Output----- For each query of the third type, print YES if there exist the sequence $v_1, v_2, \dots, v_k$ described above, or NO otherwise. -----Examples----- Input 3 11 + 1 2 a + 2 3 b + 3 2 a + 2 1 b ? 3 ? 2 - 2 1 - 3 2 + 2 1 c + 3 2 d ? 5 Output YES NO YES -----Note----- In the first query of the third type $k = 3$, we can, for example, choose a sequence $[1, 2, 3]$, since $1 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 3$ and $3 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 1$. In the second query of the third type $k = 2$, and we can't find sequence $p_1, p_2$ such that arcs $(p_1, p_2)$ and $(p_2, p_1)$ have the same characters. In the third query of the third type, we can, for example, choose a sequence $[1, 2, 3, 2, 1]$, where $1 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 3 \xrightarrow{\text{d}} 2 \xrightarrow{\text{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. n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≀ i ≀ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i and for all 1 ≀ j ≀ m the maximal number of sweets, which j-th girl received from some boy is equal to g_j. More formally, let a_{i,j} be the number of sweets which the i-th boy give to the j-th girl. Then b_i is equal exactly to the minimum among values a_{i,1}, a_{i,2}, …, a_{i,m} and g_j is equal exactly to the maximum among values b_{1,j}, b_{2,j}, …, b_{n,j}. You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of a_{i,j} for all (i,j) such that 1 ≀ i ≀ n and 1 ≀ j ≀ m. You are given the numbers b_1, …, b_n and g_1, …, g_m, determine this number. Input The first line contains two integers n and m, separated with space β€” the number of boys and girls, respectively (2 ≀ n, m ≀ 100 000). The second line contains n integers b_1, …, b_n, separated by spaces β€” b_i is equal to the minimal number of sweets, which i-th boy presented to some girl (0 ≀ b_i ≀ 10^8). The third line contains m integers g_1, …, g_m, separated by spaces β€” g_j is equal to the maximal number of sweets, which j-th girl received from some boy (0 ≀ g_j ≀ 10^8). Output If the described situation is impossible, print -1. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied. Examples Input 3 2 1 2 1 3 4 Output 12 Input 2 2 0 1 1 0 Output -1 Input 2 3 1 0 1 1 2 Output 4 Note In the first test, the minimal total number of sweets, which boys could have presented is equal to 12. This can be possible, for example, if the first boy presented 1 and 4 sweets, the second boy presented 3 and 2 sweets and the third boy presented 1 and 1 sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 12. In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied. In the third test, the minimal total number of sweets, which boys could have presented is equal to 4. This can be possible, for example, if the first boy presented 1, 1, 2 sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 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. Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β‰  ermit). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): * Clerihew (aabb); * Alternating (abab); * Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task. Input The first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5) β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on. Output Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes. Examples Input 1 1 day may sun fun Output aabb Input 1 1 day may gray way Output aaaa Input 2 1 a a a a a a e e Output aabb Input 2 1 day may sun fun test hill fest thrill Output NO Note In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO". 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. Story Jumbo Juice makes a fresh juice out of fruits of your choice.Jumbo Juice charges $5 for regular fruits and $7 for special ones. Regular fruits are Banana, Orange, Apple, Lemon and Grapes. Special ones are Avocado, Strawberry and Mango. Others fruits that are not listed are also available upon request. Those extra special fruits cost $9 per each. There is no limit on how many fruits she/he picks.The price of a cup of juice is the mean of price of chosen fruits. In case of decimal number (ex. $5.99), output should be the nearest integer (use the standard rounding function of your language of choice). Input The function will receive an array of strings, each with the name of a fruit. The recognition of names should be case insensitive. There is no case of an enmpty array input. Example ``` ['Mango', 'Banana', 'Avocado'] //the price of this juice bottle is (7+5+7)/3 = $6($6.333333...) ``` 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. Most of this problem is by the original author of [the harder kata](https://www.codewars.com/kata/556206664efbe6376700005c), I just made it simpler. I read a book recently, titled "Things to Make and Do in the Fourth Dimension" by comedian and mathematician Matt Parker ( [Youtube](https://www.youtube.com/user/standupmaths) ), and in the first chapter of the book Matt talks about problems he likes to solve in his head to take his mind off the fact that he is in his dentist's chair, we've all been there! The problem he talks about relates to polydivisible numbers, and I thought a kata should be written on the subject as it's quite interesting. (Well it's interesting to me, so there!) ### Polydivisib... huh what? So what are they? A polydivisible number is divisible in an unusual way. The first digit is cleanly divisible by `1`, the first two digits are cleanly divisible by `2`, the first three by `3`, and so on. ### Examples Let's take the number `1232` as an example. ``` 1 / 1 = 1 // Works 12 / 2 = 6 // Works 123 / 3 = 41 // Works 1232 / 4 = 308 // Works ``` `1232` is a polydivisible number. However, let's take the number `123220` and see what happens. ``` 1 /1 = 1 // Works 12 /2 = 6 // Works 123 /3 = 41 // Works 1232 /4 = 308 // Works 12322 /5 = 2464.4 // Doesn't work 123220 /6 = 220536.333... // Doesn't work ``` `123220` is not polydivisible. ### Your job: check if a number is polydivisible or not. Return `true` if it is, and `false` if it isn't. Note: All inputs will be valid numbers between `0` and `2^53-1 (9,007,199,254,740,991)` (inclusive). Note: All single digit numbers (including `0`) are trivially polydivisible. Note: Except for `0`, no numbers will start with `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. Berland Football Cup starts really soon! Commentators from all over the world come to the event. Organizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation. If $n$ is not divisible by $m$, it is impossible to distribute the boxes to the delegations at the moment. Organizers can build a new commentary box paying $a$ burles and demolish a commentary box paying $b$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes. What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$)? -----Input----- The only line contains four integer numbers $n$, $m$, $a$ and $b$ ($1 \le n, m \le 10^{12}$, $1 \le a, b \le 100$), where $n$ is the initial number of the commentary boxes, $m$ is the number of delegations to come, $a$ is the fee to build a box and $b$ is the fee to demolish a box. -----Output----- Output the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$). It is allowed that the final number of the boxes is equal to $0$. -----Examples----- Input 9 7 3 8 Output 15 Input 2 7 3 7 Output 14 Input 30 6 17 19 Output 0 -----Note----- In the first example organizers can build $5$ boxes to make the total of $14$ paying $3$ burles for the each of them. In the second example organizers can demolish $2$ boxes to make the total of $0$ paying $7$ burles for the each of them. In the third example organizers are already able to distribute all the boxes equally among the delegations, each one get $5$ boxes. 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. Spoonerize... with numbers... numberize?... numboonerize?... noonerize? ...anyway! If you don't yet know what a spoonerism is and haven't yet tried my spoonerism kata, please do [check it out](http://www.codewars.com/kata/spoonerize-me) first. You will create a function which takes an array of two positive integers, spoonerizes them, and returns the positive difference between them as a single number or ```0``` if the numbers are equal: ``` [123, 456] = 423 - 156 = 267 ``` Your code must test that all array items are numbers and return ```"invalid array"``` if it finds that either item is not a number. The provided array will always contain 2 elements. When the inputs are valid, they will always be integers, no floats will be passed. However, you must take into account that the numbers will be of varying magnitude, between and within test cases. 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. From the FAQ: What am I allowed to post as a comment for a problem? Do NOT post code. Do NOT post a comment asking why your solution is wrong. Do NOT post a comment asking if you can be given the test case your program fails on. Do NOT post a comment asking how your solution can be improved. Do NOT post a comment giving any hints or discussing approaches to the problem, or what type or speed of algorithm is required. ------ Problem Statement ------ Chef Doom has decided to bake a circular cake. He wants to place N colored cherries around the cake in a circular manner. As all great chefs do, Doom doesn't want any two adjacent cherries to have the same color. Chef has unlimited supply of cherries of K ≀ 10 different colors. Each color is denoted by the digit from the set {0, 1, ..., K – 1}. Different colors are denoted by different digits. Some of the cherries are already placed and the Chef wants you to place cherries in the remaining positions. He understands that there can be many such arrangements, so in the case when the answer is not unique he asks you to find the lexicographically smallest one. What does it mean? Let's numerate positions for the cherries by the numbers 1, 2, ..., N starting from one of the positions in a clockwise direction. Then the current (possibly partial) arrangement of the cherries can be represented by a string of N characters. For each position i of the arrangement if the cherry of the color C is placed at this position then the i^{th} character of the string is equal to the digit C. Otherwise, it is equal to the question mark ?. We identify the arrangement with the string that represents it. One arrangement is called lexicographically smaller than the other arrangement if at the first position where they differ the first one has smaller digit (we compare only complete arrangements so we don't care about relation between digits and the question mark). For example, the arrangement 1230123 is lexicographically smaller than 1231230 since they have first 3 equal characters but the 4^{th} character in the first arrangement is 0 and it is less than 1 which is the 4^{th} character of the second arrangement. Notes The cherries at the first and the last positions are adjacent to each other (recall that we have a circular cake). In the case N = 1 any arrangement is valid as long as the color used for the only cherry of this arrangement is less than K. Initial arrangement can be already invalid (see the case 3 in the example). Just to make all things clear. You will be given a usual string of digits and question marks. Don't be confused by circular stuff we have in this problem. You don't have to rotate the answer once you have replaced all question marks by the digits. Think of the output like the usual string for which each two consecutive digits must be different but having additional condition that the first and the last digits must be also different (of course if N > 1). Next, you don't have to use all colors. The only important condition is that this string should be lexicographically smaller than all other strings that can be obtained from the input string by replacement of question marks by digits and of course it must satisfy conditions on adjacent digits. One more thing, K here is not the length of the string but the number of allowed colors. Also we emphasize that the given string can have arbitrary number of question marks. So it can have zero number of question marks as well as completely consists of question marks but of course in general situation it can have both digits and question marks. OK. Let's try to formalize things in order to make all even more clear. You will be given an integer K and a string S=S[1]S[2]...S[N] where each S[i] is either the decimal digit less than K or the question mark. We are serious. In all tests string S can have only digits less than K. Don't ask about what to do if we have digit β‰₯ K. There are no such tests at all! We guarantee this! OK, let's continue. Your task is to replace each question mark by some digit strictly less than K. If there were no question marks in the string skip this step. Now if N=1 then your string is already valid. For N > 1 it must satisfy the following N conditions S[1] β‰  S[2], S[2] β‰  S[3], ..., S[N-1] β‰  S[N], S[N] β‰  S[1]. Among all such valid strings that can be obtained by replacement of question marks you should choose lexicographically smallest one. I hope now the problem is really clear. ------ Input ------ The first line of the input file contains an integer T, the number of test cases. T test cases follow. Each test case consists of exactly two lines. The first line contains an integer K, the number of available colors for cherries. The second line contains a string S that represents the current arrangement of the cherries in the cake. ------ Constraints ------ 1 ≀ T ≀ 1000 1 ≀ K ≀ 10 1 ≀ |S| ≀ 100, where |S| denotes the length of the string S Each character in S is either the digit from the set {0, 1, ..., K – 1} or the question mark ? ------ Output ------ For each test case output the lexicographically smallest valid arrangement of the cherries in the cake that can be obtained from the given arrangement by replacement of each question mark by some digit from 0 to K – 1. If it is impossible to place the cherries output NO (output is case sensitive). ----- Sample Input 1 ------ 7 1 ? 2 ?0 10 79259?087 2 ?? 3 0?1 4 ????? 3 012 ----- Sample Output 1 ------ 0 10 NO 01 021 01012 012 ----- explanation 1 ------ Case 2. The only possible replacement here is 10. Note that we output 10 since we can not rotate the answer to obtain 01 which is smaller. Case 3. Arrangement is impossible because cherries at the first and the last positions are already of the same color. Note that K = 10 but the string has length 9. It is normal. K and |S| don't have any connection. Case 4. There are two possible arrangements: 01 and 10. The answer is the first one since it is lexicographically smaller. Case 5. There are three possible ways to replace question mark by the digit: 001, 011 and 021. But the first and the second strings are not valid arrangements as in both of them there exists an adjacent pair of cherries having the same color. Hence the answer is the third string. Case 6. Note that here we do not use all colors. We just find the lexicographically smallest string that satisfies condition on adjacent digit. Case 7. The string is already valid arrangement of digits. Hence we simply print the same string to the output. 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. Daniel is watching a football team playing a game during their training session. They want to improve their passing skills during that session. The game involves $n$ players, making multiple passes towards each other. Unfortunately, since the balls were moving too fast, after the session Daniel is unable to know how many balls were involved during the game. The only thing he knows is the number of passes delivered by each player during all the session. Find the minimum possible amount of balls that were involved in the game. -----Input----- There are several test cases in the input data. The first line contains a single integer $t$ ($1 \leq t \leq 5 \cdot 10^4$) β€” the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $n$ ($2 \leq n \leq 10^5$) β€” the number of players. The second line of the test case contains a sequence of integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 10^9$), where $a_i$ is the number of passes delivered by the $i$-th player. It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$. -----Output----- For each test case print a single integer β€” the answer to the problem. -----Examples----- Input 4 4 2 3 3 2 3 1 5 2 2 0 0 4 1000000000 1000000000 1000000000 1000000000 Output 1 2 0 1 -----Note----- In the first test case, with the only ball, the game can go like this: $2 \rightarrow 1 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 2$. In the second test case, there is no possible way to play the game with only one ball. One possible way to play with two balls: $2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 1$. $2 \rightarrow 3 \rightarrow 2 \rightarrow 1$ In the third example, there were no passes, so $0$ balls are possible. 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. This is a story in a depopulated area. In this area, houses are sparsely built along a straight road called Country Road. Until now, there was no electricity in this area, but this time the government will give us some generators. You can install the generators wherever you like, but in order for electricity to be supplied to your home, you must be connected to one of the generators via an electric wire, which incurs a cost proportional to its length. As the only technical civil servant in the area, your job is to seek generator and wire placement that minimizes the total length of wires, provided that electricity is supplied to all homes. Is. Since the capacity of the generator is large enough, it is assumed that electricity can be supplied to as many houses as possible. Figure 2 shows the first data set of the sample input. To give the optimum placement for this problem, place the generators at the positions x = 20 and x = 80 as shown in the figure, and draw the wires at the positions shown in gray in the figure, respectively. Example of generator and wire placement (first dataset in input example). --- Figure 2: Example of generator and wire placement (first dataset in input example). Input The number of datasets t (0 <t ≀ 50) is given on the first line of the input. Subsequently, t datasets are given. Each dataset is given in two lines in the following format. n k x1 x2 ... xn n is the number of houses and k is the number of generators. x1, x2, ..., xn are one-dimensional coordinates that represent the position of the house, respectively. All of these values ​​are integers and satisfy 0 <n ≀ 100000, 0 <k ≀ 100000, 0 ≀ x1 <x2 <... <xn ≀ 1000000. In addition, 90% of the dataset satisfies 0 <n ≀ 100, 0 <k ≀ 100. Output For each dataset, output the minimum total required wire length in one line. Example Input 6 5 2 10 30 40 70 100 7 3 3 6 10 17 21 26 28 1 1 100 2 1 0 1000000 3 5 30 70 150 6 4 0 10 20 30 40 50 Output 60 13 0 1000000 0 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. Hakone Ekiden is one of the Japanese New Year's traditions. In Hakone Ekiden, 10 runners from each team aim for the goal while connecting the sashes at each relay station. In the TV broadcast, the ranking change from the previous relay station is displayed along with the passing order of each team at the relay station. So, look at it and tell us how many possible passage orders for each team at the previous relay station. The number of possible transit orders can be very large, so answer by the remainder divided by 1,000,000,007. Input The input is given in the form: > n > c1 > c2 > ... > cn > The number n (1 ≀ n ≀ 200) representing the number of teams is on the first line, and the ranking changes from the previous relay station in order from the first place on the following n lines. If it is'`U`', the ranking is up, if it is'`-`', the ranking is not changed) is written. Output Please output in one line by dividing the number of passages that could have been the previous relay station by 1,000,000,007. Examples Input 3 - U D Output 1 Input 5 U U - D D Output 5 Input 8 U D D D D D D D Output 1 Input 10 U D U D U D U D U D Output 608 Input 2 D U 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. For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}. Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i. Find the maximum possible value of M_1 + M_2 + \cdots + M_N. -----Constraints----- - N is an integer satisfying 1 \leq N \leq 10^9. -----Input----- Input is given from Standard Input in the following format: N -----Output----- Print the maximum possible value of M_1 + M_2 + \cdots + M_N. -----Sample Input----- 2 -----Sample Output----- 1 When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 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. Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not. One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n. Input The only line contains a positive integer n (1 ≀ n ≀ 109). This number doesn't have leading zeroes. Output Output the least super lucky number that is more than or equal to n. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4500 Output 4747 Input 47 Output 47 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. Let S(n) denote the sum of the digits in the decimal notation of n. For example, S(123) = 1 + 2 + 3 = 6. We will call an integer n a Snuke number when, for all positive integers m such that m > n, \frac{n}{S(n)} \leq \frac{m}{S(m)} holds. Given an integer K, list the K smallest Snuke numbers. -----Constraints----- - 1 \leq K - The K-th smallest Snuke number is not greater than 10^{15}. -----Input----- Input is given from Standard Input in the following format: K -----Output----- Print K lines. The i-th line should contain the i-th smallest Snuke number. -----Sample Input----- 10 -----Sample Output----- 1 2 3 4 5 6 7 8 9 19 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 tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k. For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. -----Input----- The first line of the input contains two integers n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ 5)Β β€” the number of vertices in the tree and the maximum allowed jump distance respectively. The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers a_{i} and b_{i} (1 ≀ a_{i}, b_{i} ≀ n)Β β€” the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. -----Output----- Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t. -----Examples----- Input 6 2 1 2 1 3 2 4 2 5 4 6 Output 20 Input 13 3 1 2 3 2 4 2 5 2 3 6 10 6 6 7 6 13 5 8 5 9 9 11 11 12 Output 114 Input 3 5 2 1 3 1 Output 3 -----Note----- In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). [Image] There are $\frac{n \cdot(n - 1)}{2} = 15$ pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5Β·2 + 10Β·1 = 20. In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3Β·1 = 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. You've just recently been hired to calculate scores for a Dart Board game! Scoring specifications: * 0 points - radius above 10 * 5 points - radius between 5 and 10 inclusive * 10 points - radius less than 5 **If all radii are less than 5, award 100 BONUS POINTS!** Write a function that accepts an array of radii (can be integers and/or floats), and returns a total score using the above specification. An empty array should return 0. ## Examples: 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. During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working. Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1). After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task. Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue. -----Input----- The first line contains integer n (2 ≀ n ≀ 2Β·10^5) β€” the number of students in the queue. Then n lines follow, i-th line contains the pair of integers a_{i}, b_{i} (0 ≀ a_{i}, b_{i} ≀ 10^6), where a_{i} is the ID number of a person in front of a student and b_{i} is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist. The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order. -----Output----- Print a sequence of n integers x_1, x_2, ..., x_{n} β€” the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one. -----Examples----- Input 4 92 31 0 7 31 0 7 141 Output 92 7 31 141 -----Note----- The picture illustrates the queue for the first sample. [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. You are given a permutation p of length n. Also you are given m foe pairs (a_{i}, b_{i}) (1 ≀ a_{i}, b_{i} ≀ n, a_{i} β‰  b_{i}). Your task is to count the number of different intervals (x, y) (1 ≀ x ≀ y ≀ n) that do not contain any foe pairs. So you shouldn't count intervals (x, y) that contain at least one foe pair in it (the positions and order of the values from the foe pair are not important). Consider some example: p = [1, 3, 2, 4] and foe pairs are {(3, 2), (4, 2)}. The interval (1, 3) is incorrect because it contains a foe pair (3, 2). The interval (1, 4) is also incorrect because it contains two foe pairs (3, 2) and (4, 2). But the interval (1, 2) is correct because it doesn't contain any foe pair. -----Input----- The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·10^5) β€” the length of the permutation p and the number of foe pairs. The second line contains n distinct integers p_{i} (1 ≀ p_{i} ≀ n) β€” the elements of the permutation p. Each of the next m lines contains two integers (a_{i}, b_{i}) (1 ≀ a_{i}, b_{i} ≀ n, a_{i} β‰  b_{i}) β€” the i-th foe pair. Note a foe pair can appear multiple times in the given list. -----Output----- Print the only integer c β€” the number of different intervals (x, y) that does not contain any foe pairs. Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type. -----Examples----- Input 4 2 1 3 2 4 3 2 2 4 Output 5 Input 9 5 9 7 2 3 1 4 6 5 8 1 6 4 5 2 7 7 2 2 7 Output 20 -----Note----- In the first example the intervals from the answer are (1, 1), (1, 2), (2, 2), (3, 3) and (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. You are given an array $a_1, a_2, \dots , a_n$. Array is good if for each pair of indexes $i < j$ the condition $j - a_j \ne i - a_i$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if $a = [1, 1, 3, 5]$, then shuffled arrays $[1, 3, 5, 1]$, $[3, 5, 1, 1]$ and $[5, 3, 1, 1]$ are good, but shuffled arrays $[3, 1, 5, 1]$, $[1, 1, 3, 5]$ and $[1, 1, 5, 3]$ aren't. It's guaranteed that it's always possible to shuffle an array to meet this condition. -----Input----- The first line contains one integer $t$ ($1 \le t \le 100$) β€” the number of test cases. The first line of each test case contains one integer $n$ ($1 \le n \le 100$) β€” the length of array $a$. The second line of each test case contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le 100$). -----Output----- For each test case print the shuffled version of the array $a$ which is good. -----Example----- Input 3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 Output 7 1 5 1 3 2 4 6 1 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. Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1 / x seconds for the first character and 1 / y seconds for the second one). The i-th monster dies after he receives a_{i} hits. Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit. -----Input----- The first line contains three integers n,x,y (1 ≀ n ≀ 10^5, 1 ≀ x, y ≀ 10^6) β€” the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly. Next n lines contain integers a_{i} (1 ≀ a_{i} ≀ 10^9)Β β€” the number of hits needed do destroy the i-th monster. -----Output----- Print n lines. In the i-th line print word "Vanya", if the last hit on the i-th monster was performed by Vanya, "Vova", if Vova performed the last hit, or "Both", if both boys performed it at the same time. -----Examples----- Input 4 3 2 1 2 3 4 Output Vanya Vova Vanya Both Input 2 1 1 1 2 Output Both Both -----Note----- In the first sample Vanya makes the first hit at time 1 / 3, Vova makes the second hit at time 1 / 2, Vanya makes the third hit at time 2 / 3, and both boys make the fourth and fifth hit simultaneously at the time 1. In the second sample Vanya and Vova make the first and second hit simultaneously at time 1. 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 well-known Fibonacci sequence $F_0, F_1, F_2,\ldots $ is defined as follows: $F_0 = 0, F_1 = 1$. For each $i \geq 2$: $F_i = F_{i - 1} + F_{i - 2}$. Given an increasing arithmetic sequence of positive integers with $n$ elements: $(a, a + d, a + 2\cdot d,\ldots, a + (n - 1)\cdot d)$. You need to find another increasing arithmetic sequence of positive integers with $n$ elements $(b, b + e, b + 2\cdot e,\ldots, b + (n - 1)\cdot e)$ such that: $0 < b, e < 2^{64}$, for all $0\leq i < n$, the decimal representation of $a + i \cdot d$ appears as substring in the last $18$ digits of the decimal representation of $F_{b + i \cdot e}$ (if this number has less than $18$ digits, then we consider all its digits). -----Input----- The first line contains three positive integers $n$, $a$, $d$ ($1 \leq n, a, d, a + (n - 1) \cdot d < 10^6$). -----Output----- If no such arithmetic sequence exists, print $-1$. Otherwise, print two integers $b$ and $e$, separated by space in a single line ($0 < b, e < 2^{64}$). If there are many answers, you can output any of them. -----Examples----- Input 3 1 1 Output 2 1 Input 5 1 2 Output 19 5 -----Note----- In the first test case, we can choose $(b, e) = (2, 1)$, because $F_2 = 1, F_3 = 2, F_4 = 3$. In the second test case, we can choose $(b, e) = (19, 5)$ because: $F_{19} = 4181$ contains $1$; $F_{24} = 46368$ contains $3$; $F_{29} = 514229$ contains $5$; $F_{34} = 5702887$ contains $7$; $F_{39} = 63245986$ contains $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. In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $s$ starting from the $l$-th character and ending with the $r$-th character as $s[l \dots r]$. The characters of each string are numbered from $1$. We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011. Binary string $a$ is considered reachable from binary string $b$ if there exists a sequence $s_1$, $s_2$, ..., $s_k$ such that $s_1 = a$, $s_k = b$, and for every $i \in [1, k - 1]$, $s_i$ can be transformed into $s_{i + 1}$ using exactly one operation. Note that $k$ can be equal to $1$, i. e., every string is reachable from itself. You are given a string $t$ and $q$ queries to it. Each query consists of three integers $l_1$, $l_2$ and $len$. To answer each query, you have to determine whether $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$. -----Input----- The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β€” the length of string $t$. The second line contains one string $t$ ($|t| = n$). Each character of $t$ is either 0 or 1. The third line contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) β€” the number of queries. Then $q$ lines follow, each line represents a query. The $i$-th line contains three integers $l_1$, $l_2$ and $len$ ($1 \le l_1, l_2 \le |t|$, $1 \le len \le |t| - \max(l_1, l_2) + 1$) for the $i$-th query. -----Output----- For each query, print either YES if $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$, or NO otherwise. You may print each letter in any register. -----Example----- Input 5 11011 3 1 3 3 1 4 2 1 2 3 Output Yes Yes No 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 colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells. Input The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105; 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe. Output Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe. Examples Input 6 3 ABBACC Output 2 ABCACA Input 3 2 BBB Output 1 BAB 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 category page displays a set number of products per page, with pagination at the bottom allowing the user to move from page to page. Given that you know the page you are on, how many products are in the category in total, and how many products are on any given page, how would you output a simple string showing which products you are viewing.. examples In a category of 30 products with 10 products per page, on page 1 you would see 'Showing 1 to 10 of 30 Products.' In a category of 26 products with 10 products per page, on page 3 you would see 'Showing 21 to 26 of 26 Products.' In a category of 8 products with 10 products per page, on page 1 you would see 'Showing 1 to 8 of 8 Products.' 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. # Description: Find the longest successive exclamation marks and question marks combination in the string. A successive exclamation marks and question marks combination must contains two part: a substring of "!" and a substring "?", they are adjacent. If more than one result are found, return the one which at left side; If no such a combination found, return `""`. # Examples ``` find("!!") === "" find("!??") === "!??" find("!?!!") === "?!!" find("!!???!????") === "!!???" find("!!???!?????") === "!?????" find("!????!!!?") === "????!!!" find("!?!!??!!!?") === "??!!!" ``` # Note Please don't post issue about difficulty or duplicate. Because: >[That's unfair on the kata creator. This is a valid kata and introduces new people to javascript some regex or loops, depending on how they tackle this problem. --matt c](https://www.codewars.com/kata/remove-exclamation-marks/discuss#57fabb625c9910c73000024e) 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 subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≀ k1 < k2 < ... < k|x| ≀ |s|). You've got two strings β€” s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1 ≀ i ≀ |s|), there is such subsequence x = sk1sk2... sk|x| of string s, that x = t and for some j (1 ≀ j ≀ |x|) kj = i. Input The first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2Β·105. Output Print "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise. Examples Input abab ab Output Yes Input abacaba aba Output No Input abc ba Output No Note In the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once. In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t. In the third sample there is no occurrence of string t in string s. 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. Nukes has an integer that can be represented as the bitwise OR of one or more integers between A and B (inclusive). How many possible candidates of the value of Nukes's integer there are? Constraints * 1 ≀ A ≀ B < 2^{60} * A and B are integers. Input The input is given from Standard Input in the following format: A B Output Print the number of possible candidates of the value of Nukes's integer. Examples Input 7 9 Output 4 Input 65 98 Output 63 Input 271828182845904523 314159265358979323 Output 68833183630578410 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 ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the king, whose name was Victorious Vasily Pupkin, was always called by the berlanders VVP. In Berland over its long history many dynasties of kings replaced each other, but they were all united by common traditions. Thus, according to one Berland traditions, to maintain stability in the country, the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor). Berlanders appreciate stability, so this tradition has never been broken. Also Berlanders like perfection, so another tradition requires that the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king). This tradition, of course, has also been always observed. The name of a dynasty is formed by very simple rules: we take all the short names of the kings in the order in which they ruled, and write them in one line. Thus, a dynasty of kings "ab" and "ba" is called "abba", and the dynasty, which had only the king "abca", is called "abca". Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland. Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B. Input The first line contains integer n (1 ≀ n ≀ 5Β·105) β€” the number of names in Vasya's list. Next n lines contain n abbreviated names, one per line. An abbreviated name is a non-empty sequence of lowercase Latin letters. Its length does not exceed 10 characters. Output Print a single number β€” length of the sought dynasty's name in letters. If Vasya's list is wrong and no dynasty can be found there, print a single number 0. Examples Input 3 abc ca cba Output 6 Input 4 vvp vvp dam vvp Output 0 Input 3 ab c def Output 1 Note In the first sample two dynasties can exist: the one called "abcca" (with the first and second kings) and the one called "abccba" (with the first and third kings). In the second sample there aren't acceptable dynasties. The only dynasty in the third sample consists of one king, his name is "c". 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 recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem. Let the queue to the cashier contain n people, at that each of them is characterized by a positive integer ai β€” that is the time needed to work with this customer. What is special about this very cashier is that it can serve two customers simultaneously. However, if two customers need ai and aj of time to be served, the time needed to work with both of them customers is equal to max(ai, aj). Please note that working with customers is an uninterruptable process, and therefore, if two people simultaneously come to the cashier, it means that they begin to be served simultaneously, and will both finish simultaneously (it is possible that one of them will have to wait). Vasya used in his algorithm an ingenious heuristic β€” as long as the queue has more than one person waiting, then some two people of the first three standing in front of the queue are sent simultaneously. If the queue has only one customer number i, then he goes to the cashier, and is served within ai of time. Note that the total number of phases of serving a customer will always be equal to ⌈n / 2βŒ‰. Vasya thinks that this method will help to cope with the queues we all hate. That's why he asked you to work out a program that will determine the minimum time during which the whole queue will be served using this algorithm. Input The first line of the input file contains a single number n (1 ≀ n ≀ 1000), which is the number of people in the sequence. The second line contains space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 106). The people are numbered starting from the cashier to the end of the queue. Output Print on the first line a single number β€” the minimum time needed to process all n people. Then on ⌈n / 2βŒ‰ lines print the order in which customers will be served. Each line (probably, except for the last one) must contain two numbers separated by a space β€” the numbers of customers who will be served at the current stage of processing. If n is odd, then the last line must contain a single number β€” the number of the last served customer in the queue. The customers are numbered starting from 1. Examples Input 4 1 2 3 4 Output 6 1 2 3 4 Input 5 2 4 3 1 4 Output 8 1 3 2 5 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. You've got a positive integer sequence a_1, a_2, ..., a_{n}. All numbers in the sequence are distinct. Let's fix the set of variables b_1, b_2, ..., b_{m}. Initially each variable b_{i} (1 ≀ i ≀ m) contains the value of zero. Consider the following sequence, consisting of n operations. The first operation is assigning the value of a_1 to some variable b_{x} (1 ≀ x ≀ m). Each of the following n - 1 operations is assigning to some variable b_{y} the value that is equal to the sum of values that are stored in the variables b_{i} and b_{j} (1 ≀ i, j, y ≀ m). At that, the value that is assigned on the t-th operation, must equal a_{t}. For each operation numbers y, i, j are chosen anew. Your task is to find the minimum number of variables m, such that those variables can help you perform the described sequence of operations. -----Input----- The first line contains integer n (1 ≀ n ≀ 23). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≀ a_{k} ≀ 10^9). It is guaranteed that all numbers in the sequence are distinct. -----Output----- In a single line print a single number β€” the minimum number of variables m, such that those variables can help you perform the described sequence of operations. If you cannot perform the sequence of operations at any m, print -1. -----Examples----- Input 5 1 2 3 6 8 Output 2 Input 3 3 6 5 Output -1 Input 6 2 4 8 6 10 18 Output 3 -----Note----- In the first sample, you can use two variables b_1 and b_2 to perform the following sequence of operations. b_1 := 1; b_2 := b_1 + b_1; b_1 := b_1 + b_2; b_1 := b_1 + b_1; b_1 := b_1 + b_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. Find the symmetric difference of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$. Constraints * $1 \leq n, m \leq 200,000$ * $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$ * $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$ Input The input is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ $m$ $b_0 \; b_1 \; ... \; b_{m-1}$ Elements in $A$ and $B$ are given in ascending order. There are no duplicate elements in each set. Output Print elements in the symmetric difference in ascending order. Print an element in a line. Example Input 7 1 2 3 4 5 6 7 4 2 4 6 8 Output 1 3 5 7 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. The surveyor starship Hakodate-maru is famous for her two fuel containers with unbounded capacities. They hold the same type of atomic fuel balls. There, however, is an inconvenience. The shapes of the fuel containers #1 and #2 are always cubic and regular tetrahedral respectively. Both of the fuel containers should be either empty or filled according to their shapes. Otherwise, the fuel balls become extremely unstable and may explode in the fuel containers. Thus, the number of fuel balls for the container #1 should be a cubic number (n3 for some n = 0, 1, 2, 3,... ) and that for the container #2 should be a tetrahedral number ( n(n + 1)(n + 2)/6 for some n = 0, 1, 2, 3,... ). Hakodate-maru is now at the star base Goryokaku preparing for the next mission to create a precise and detailed chart of stars and interstellar matters. Both of the fuel containers are now empty. Commander Parus of Goryokaku will soon send a message to Captain Future of Hakodate-maru on how many fuel balls Goryokaku can supply. Captain Future should quickly answer to Commander Parus on how many fuel balls she requests before her ship leaves Goryokaku. Of course, Captain Future and her omcers want as many fuel balls as possible. For example, consider the case Commander Parus offers 151200 fuel balls. If only the fuel container #1 were available (i.e. ifthe fuel container #2 were unavailable), at most 148877 fuel balls could be put into the fuel container since 148877 = 53 Γ— 53 Γ— 53 < 151200 < 54 Γ— 54 Γ— 54 . If only the fuel container #2 were available, at most 147440 fuel balls could be put into the fuel container since 147440 = 95 Γ— 96 Γ— 97/6 < 151200 < 96 Γ— 97 Γ— 98/6 . Using both of the fuel containers #1 and #2, 151200 fuel balls can be put into the fuel containers since 151200 = 39 Γ— 39 Γ— 39 + 81 Γ— 82 Γ— 83/6 . In this case, Captain Future's answer should be "151200". Commander Parus's offer cannot be greater than 151200 because of the capacity of the fuel storages of Goryokaku. Captain Future and her omcers know that well. You are a fuel engineer assigned to Hakodate-maru. Your duty today is to help Captain Future with calculating the number of fuel balls she should request. Input The input is a sequence of at most 1024 positive integers. Each line contains a single integer. The sequence is followed by a zero, which indicates the end of data and should not be treated as input. You may assume that none of the input integers is greater than 151200. Output The output is composed of lines, each containing a single integer. Each output integer should be the greatest integer that is the sum of a nonnegative cubic number and a nonnegative tetrahedral number and that is not greater than the corresponding input number. No other characters should appear in the output. Example Input 100 64 50 20 151200 0 Output 99 64 47 20 151200 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 ACM ICPC judges are very careful about not leaking their problems, and all communications are encrypted. However, one does sometimes make mistakes, like using too weak an encryption scheme. Here is an example of that. The encryption chosen was very simple: encrypt each chunk of the input by flipping some bits according to a shared key. To provide reasonable security, the size of both chunk and key is 32 bits. That is, suppose the input was a sequence of m 32-bit integers. N1 N2 N3 ... Nm After encoding with the key K it becomes the following sequence of m 32-bit integers. (N1 ∧ K) (N2 ∧ K) (N3 ∧ K) ... (Nm ∧ K) where (a ∧ b) is the bitwise exclusive or of a and b. Exclusive or is the logical operator which is 1 when only one of its operands is 1, and 0 otherwise. Here is its definition for 1-bit integers. 0 βŠ• 0 = 0 0 βŠ• 1 = 1 1 βŠ• 0 = 1 1 βŠ• 1 =0 As you can see, it is identical to addition modulo 2. For two 32-bit integers a and b, their bitwise exclusive or a ∧ b is defined as follows, using their binary representations, composed of 0's and 1's. a ∧ b = a31 ... a1a0 ∧ b31 ... b1b0 = c31 ... c1c0 where ci = ai βŠ• bi (i = 0, 1, ... , 31). For instance, using binary notation, 11010110 ∧ 01010101 = 10100011, or using hexadecimal, d6 ∧ 55 = a3. Since this kind of encryption is notoriously weak to statistical attacks, the message has to be compressed in advance, so that it has no statistical regularity. We suppose that N1 N2 ... Nm is already in compressed form. However, the trouble is that the compression algorithm itself introduces some form of regularity: after every 8 integers of compressed data, it inserts a checksum, the sum of these integers. That is, in the above input, N9 = βˆ‘8i=1 Ni = N1 + ... + N8, where additions are modulo 232. Luckily, you could intercept a communication between the judges. Maybe it contains a problem for the finals! As you are very clever, you have certainly seen that you can easily find the lowest bit of the key, denoted by K0. On the one hand, if K0 = 1, then after encoding, the lowest bit of βˆ‘8i=1 Ni ∧ K is unchanged, as K0 is added an even number of times, but the lowest bit of N9 ∧ K is changed, so they shall differ. On the other hand, if K0 = 0, then after encoding, the lowest bit of βˆ‘8i=1 Ni ∧ K shall still be identical to the lowest bit of N9 ∧ K, as they do not change. For instance, if the lowest bits after encoding are 1 1 1 1 1 1 1 1 1 then K0 must be 1, but if they are 1 1 1 1 1 1 1 0 1 then K0 must be 0. So far, so good. Can you do better? You should find the key used for encoding. Input The input starts with a line containing only a positive integer S, indicating the number of datasets in the input. S is no more than 1000. It is followed by S datasets. Each dataset is composed of nine 32-bit integers corresponding to the first nine chunks of a communication. They are written in hexadecimal notation, using digits β€˜0’ to β€˜9’ and lowercase letters β€˜a’ to β€˜f’, and with no leading zeros. They are separated by a space or a newline. Each dataset is ended by a newline. Output For each dataset you should output the key used for encoding. Each key shall appear alone on its line, and be written in hexadecimal notation, using digits β€˜0’ to β€˜9’ and lowercase letters β€˜a’ to β€˜f’, and with no leading zeros. Example Input 8 1 1 1 1 1 1 1 1 8 3 2 3 2 3 2 3 2 6 3 4 4 7 7 b a 2 2e e1 13 ce 28 ca 6 ab 46 a6d b08 49e2 6128 f27 8cf2 bc50 7380 7fe1 723b 4eba eb4 a352 fd14 6ac1 eed1 dd06 bb83 392bc ef593c08 847e522f 74c02b9c 26f3a4e1 e2720a01 6fe66007 7a4e96ad 6ee5cef6 3853cd88 60202fb8 757d6d66 9c3a9525 fbcd7983 82b9571c ddc54bab 853e52da 22047c88 e5524401 Output 0 2 6 1c6 4924afc7 ffff95c5 546991d 901c4a16 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 lives on an infinite two-dimensional plane. He is going on an N-day trip. At the beginning of Day 1, he is at home. His plan is described in a string S of length N. On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction: * North if the i-th letter of S is `N` * West if the i-th letter of S is `W` * South if the i-th letter of S is `S` * East if the i-th letter of S is `E` He has not decided each day's travel distance. Determine whether it is possible to set each day's travel distance so that he will be back at home at the end of Day N. Constraints * 1 ≦ | S | ≦ 1000 * S consists of the letters `N`, `W`, `S`, `E`. Input The input is given from Standard Input in the following format: S Output Print `Yes` if it is possible to set each day's travel distance so that he will be back at home at the end of Day N. Otherwise, print `No`. Examples Input SENW Output Yes Input NSNNSNSN Output Yes Input NNEW Output No Input W Output No 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 Little Elephant has got a problem β€” somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array. The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements. Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself. Input The first line contains a single integer n (2 ≀ n ≀ 105) β€” the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, β€” array a. Note that the elements of the array are not necessarily distinct numbers. Output In a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise. Examples Input 2 1 2 Output YES Input 3 3 2 1 Output YES Input 4 4 3 2 1 Output NO Note In the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES". In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES". In the third sample we can't sort the array in more than one swap operation, so the answer is "NO". 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. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1 ≀ x < n) such that dx = 4 and dx + 1 = 7, if x is odd, then to assign dx = dx + 1 = 4, otherwise to assign dx = dx + 1 = 7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all. You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations. Input The first line contains two integers n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ 109) β€” the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero. Output In the single line print the result without spaces β€” the number after the k operations are fulfilled. Examples Input 7 4 4727447 Output 4427477 Input 4 2 4478 Output 4478 Note In the first sample the number changes in the following sequence: 4727447 β†’ 4427447 β†’ 4427477 β†’ 4427447 β†’ 4427477. In the second sample: 4478 β†’ 4778 β†’ 4478. 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. Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm. .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# Note that the top left corner should be drawn by '#'. Constraints * 1 ≀ H ≀ 300 * 1 ≀ W ≀ 300 Input The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space. The input ends with two 0 (when both H and W are zero). Output For each dataset, print the chessboard made of '#' and '.'. Print a blank line after each dataset. Example Input 3 4 5 6 3 3 2 2 1 1 0 0 Output #.#. .#.# #.#. #.#.#. .#.#.# #.#.#. .#.#.# #.#.#. #.# .#. #.# #. .# # 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. So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 β‰₯ p_2 β‰₯ ... β‰₯ p_n. Help the jury distribute the gold, silver and bronze medals. Let their numbers be g, s and b, respectively. Here is a list of requirements from the rules, which all must be satisfied: * for each of the three types of medals, at least one medal must be awarded (that is, g>0, s>0 and b>0); * the number of gold medals must be strictly less than the number of silver and the number of bronze (that is, g<s and g<b, but there are no requirements between s and b); * each gold medalist must solve strictly more problems than any awarded with a silver medal; * each silver medalist must solve strictly more problems than any awarded a bronze medal; * each bronze medalist must solve strictly more problems than any participant not awarded a medal; * the total number of medalists g+s+b should not exceed half of all participants (for example, if n=21, then you can award a maximum of 10 participants, and if n=26, then you can award a maximum of 13 participants). The jury wants to reward with medals the total maximal number participants (i.e. to maximize g+s+b) so that all of the items listed above are fulfilled. Help the jury find such a way to award medals. Input The first line of the input contains an integer t (1 ≀ t ≀ 10000) β€” the number of test cases in the input. Then t test cases follow. The first line of a test case contains an integer n (1 ≀ n ≀ 4β‹…10^5) β€” the number of BeRC participants. The second line of a test case contains integers p_1, p_2, ..., p_n (0 ≀ p_i ≀ 10^6), where p_i is equal to the number of problems solved by the i-th participant from the final standings. The values p_i are sorted in non-increasing order, i.e. p_1 β‰₯ p_2 β‰₯ ... β‰₯ p_n. The sum of n over all test cases in the input does not exceed 4β‹…10^5. Output Print t lines, the j-th line should contain the answer to the j-th test case. The answer consists of three non-negative integers g, s, b. * Print g=s=b=0 if there is no way to reward participants with medals so that all requirements from the statement are satisfied at the same time. * Otherwise, print three positive numbers g, s, b β€” the possible number of gold, silver and bronze medals, respectively. The sum of g+s+b should be the maximum possible. If there are several answers, print any of them. Example Input 5 12 5 4 4 3 2 2 1 1 1 1 1 1 4 4 3 2 1 1 1000000 20 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 32 64 64 63 58 58 58 58 58 37 37 37 37 34 34 28 28 28 28 28 28 24 24 19 17 17 17 17 16 16 16 16 11 Output 1 2 3 0 0 0 0 0 0 2 5 3 2 6 6 Note In the first test case, it is possible to reward 1 gold, 2 silver and 3 bronze medals. In this case, the participant solved 5 tasks will be rewarded with the gold medal, participants solved 4 tasks will be rewarded with silver medals, participants solved 2 or 3 tasks will be rewarded with bronze medals. Participants solved exactly 1 task won't be rewarded. It's easy to see, that in this case, all conditions are satisfied and it is possible to reward participants in this way. It is impossible to give more than 6 medals because the number of medals should not exceed half of the number of participants. The answer 1, 3, 2 is also correct in this test case. In the second and third test cases, it is impossible to reward medals, because at least one medal of each type should be given, but the number of medals should not exceed half of the number of participants. 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's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups. The bus stop queue has n groups of people. The i-th group from the beginning has a_{i} people. Every 30 minutes an empty bus arrives at the bus stop, it can carry at most m people. Naturally, the people from the first group enter the bus first. Then go the people from the second group and so on. Note that the order of groups in the queue never changes. Moreover, if some group cannot fit all of its members into the current bus, it waits for the next bus together with other groups standing after it in the queue. Your task is to determine how many buses is needed to transport all n groups to the dacha countryside. -----Input----- The first line contains two integers n and m (1 ≀ n, m ≀ 100). The next line contains n integers: a_1, a_2, ..., a_{n} (1 ≀ a_{i} ≀ m). -----Output----- Print a single integer β€” the number of buses that is needed to transport all n groups to the dacha countryside. -----Examples----- Input 4 3 2 3 2 1 Output 3 Input 3 4 1 2 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. Read problems statements in Mandarin Chinese and Russian. Recently Chef bought a bunch of robot-waiters. And now he needs to know how much to pay for the electricity that robots use for their work. All waiters serve food from the kitchen (which is in the point (0, 0)) and carry it to some table (which is in some point (x, y)) in a shortest way. But this is a beta version of robots and they can only do the next moves: turn right and make a step forward or turn left and make a step forward. Initially they look in direction of X-axis. Your task is to calculate for each query the number of moves they’ll do to reach corresponding table. ------ Input ------ The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. For each test case there is a sing line containing two space-separated integers - x and y. ------ Output ------ For each test case, output a single line containing number of moves that robot will make to reach point (x, y) ------ Constraints ------ $1 ≀ T ≀ 10^{5}$ $-10^{9} ≀ x, y ≀ 10^{9}$ Β  ----- Sample Input 1 ------ 2 3 3 3 4 ----- Sample Output 1 ------ 6 7 ------ Explanation 0 ------ Example case 1. Sequence of moves would be LRLRLR 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 directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected. You should assign labels to all vertices in such a way that: Labels form a valid permutation of length n β€” an integer sequence such that each integer from 1 to n appears exactly once in it. If there exists an edge from vertex v to vertex u then label_{v} should be smaller than label_{u}. Permutation should be lexicographically smallest among all suitable. Find such sequence of labels to satisfy all the conditions. -----Input----- The first line contains two integer numbers n, m (2 ≀ n ≀ 10^5, 1 ≀ m ≀ 10^5). Next m lines contain two integer numbers v and u (1 ≀ v, u ≀ n, v β‰  u) β€” edges of the graph. Edges are directed, graph doesn't contain loops or multiple edges. -----Output----- Print n numbers β€” lexicographically smallest correct permutation of labels of vertices. -----Examples----- Input 3 3 1 2 1 3 3 2 Output 1 3 2 Input 4 5 3 1 4 1 2 3 3 4 2 4 Output 4 1 2 3 Input 5 4 3 1 2 1 2 3 4 5 Output 3 1 2 4 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. In this Kata, we define an arithmetic progression as a series of integers in which the differences between adjacent numbers are the same. You will be given an array of ints of `length > 2` and your task will be to convert it into an arithmetic progression by the following rule: ```Haskell For each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1 or it can be left unchanged. ``` Return the minimum number of changes needed to convert the array to an arithmetic progression. If not possible, return `-1`. ```Haskell For example: solve([1,1,3,5,6,5]) == 4 because [1,1,3,5,6,5] can be changed to [1,2,3,4,5,6] by making 4 changes. solve([2,1,2]) == 1 because it can be changed to [2,2,2] solve([1,2,3]) == 0 because it is already a progression, and no changes are needed. solve([1,1,10) == -1 because it's impossible. solve([5,6,5,3,1,1]) == 4. It becomes [6,5,4,3,2,1] ``` More examples in the test cases. 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. Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains a_{i} liters of paint of color i. Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 Γ— 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops. Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square. -----Input----- The first line of the input contains a single integer n (1 ≀ n ≀ 200 000)Β β€” the number of jars with colors Vika has. The second line of the input contains a sequence of integers a_1, a_2, ..., a_{n} (1 ≀ a_{i} ≀ 10^9), where a_{i} is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has. -----Output----- The only line of the output should contain a single integerΒ β€” the maximum number of squares that Vika can paint if she follows the rules described above. -----Examples----- Input 5 2 4 2 3 3 Output 12 Input 3 5 5 5 Output 15 Input 6 10 10 10 1 10 10 Output 11 -----Note----- In the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5. In the second sample Vika can start to paint using any color. In the third sample Vika should start painting using color number 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. Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns β€” from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (x_{k}, y_{k}). The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. [Image] Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made! -----Input----- The first line of the input contains fix integers n, m, x, y, z, p (1 ≀ n, m ≀ 10^9;Β 0 ≀ x, y, z ≀ 10^9;Β 1 ≀ p ≀ 10^5). Each of the following p lines contains two integers x_{k}, y_{k} (1 ≀ x_{k} ≀ n;Β 1 ≀ y_{k} ≀ m) β€” the initial coordinates of the k-th candy. Two candies can lie on the same cell. -----Output----- For each of the p candies, print on a single line its space-separated new coordinates. -----Examples----- Input 3 3 3 1 1 9 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 Output 1 3 1 2 1 1 2 3 2 2 2 1 3 3 3 2 3 1 -----Note----- Just for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix: QWER REWQ ASDF -> FDSA ZXCV VCXZ 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. Shohag has an integer sequence $a_1, a_2, \ldots, a_n$. He can perform the following operation any number of times (possibly, zero): Select any positive integer $k$ (it can be different in different operations). Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert $k$ into the sequence at this position. This way, the sequence $a$ changes, and the next operation is performed on this changed sequence. For example, if $a=[3,3,4]$ and he selects $k = 2$, then after the operation he can obtain one of the sequences $[\underline{2},3,3,4]$, $[3,\underline{2},3,4]$, $[3,3,\underline{2},4]$, or $[3,3,4,\underline{2}]$. Shohag wants this sequence to satisfy the following condition: for each $1 \le i \le |a|$, $a_i \le i$. Here, $|a|$ denotes the size of $a$. Help him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 200$) β€” the number of test cases. The first line of each test case contains a single integer $n$ ($1 \le n \le 100$) β€” the initial length of the sequence. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) β€” the elements of the sequence. -----Output----- For each test case, print a single integer β€” the minimum number of operations needed to perform to achieve the goal mentioned in the statement. -----Examples----- Input 4 3 1 3 4 5 1 2 5 7 4 1 1 3 69 6969 696969 Output 1 3 0 696966 -----Note----- In the first test case, we have to perform at least one operation, as $a_2=3>2$. We can perform the operation $[1, 3, 4] \rightarrow [1, \underline{2}, 3, 4]$ (the newly inserted element is underlined), now the condition is satisfied. In the second test case, Shohag can perform the following operations: $[1, 2, 5, 7, 4] \rightarrow [1, 2, \underline{3}, 5, 7, 4] \rightarrow [1, 2, 3, \underline{4}, 5, 7, 4] \rightarrow [1, 2, 3, 4, 5, \underline{3}, 7, 4]$. In the third test case, the sequence already satisfies the condition. 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 rectangle grid. That grid's size is n Γ— m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β€” a pair of integers (x, y) (0 ≀ x ≀ n, 0 ≀ y ≀ m). Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 ≀ x1 ≀ x ≀ x2 ≀ n, 0 ≀ y1 ≀ y ≀ y2 ≀ m, <image>. The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers. <image> If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one. Input The first line contains six integers n, m, x, y, a, b (1 ≀ n, m ≀ 109, 0 ≀ x ≀ n, 0 ≀ y ≀ m, 1 ≀ a ≀ n, 1 ≀ b ≀ m). Output Print four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2). Examples Input 9 9 5 5 2 1 Output 1 3 9 7 Input 100 100 52 50 46 56 Output 17 8 86 92 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 array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types. * `0 p x`: a_p \gets a_p + x * `1 l r`: Print \sum_{i = l}^{r - 1}{a_i}. Constraints * 1 \leq N, Q \leq 500,000 * 0 \leq a_i, x \leq 10^9 * 0 \leq p < N * 0 \leq l_i < r_i \leq N * All values in Input are integer. Input Input is given from Standard Input in the following format: N Q a_0 a_1 ... a_{N - 1} \textrm{Query}_0 \textrm{Query}_1 : \textrm{Query}_{Q - 1} Output For each query of the latter type, print the answer. Example Input 5 5 1 2 3 4 5 1 0 5 1 2 4 0 3 10 1 0 5 1 0 3 Output 15 7 25 6 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 recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence: `14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequence A007629 in the OEIS) Keith numbers were introduced by Mike Keith in 1987. They are computationally very challenging to find, with only about 100 known. Implement the code to check if the given number is a Keith number. Return the number number of iteration needed to confirm it; otherwise return `false`. **Note:** 1-digit numbers are **not** Keith numbers by definition ## Examples ``` n = 197 # --> [1, 9, 7] # calculation iteration 1 + 9 + 7 = 17 # 1 9 + 7 + 17 = 33 # 2 7 + 17 + 33 = 57 # 3 17 + 33 + 57 = 107 # 4 33 + 57 + 107 = 197 # 5 ``` As `197` is the same as the initial number, so it's a Keith number: return `5` Another example: ``` n = 196 # calculation iteration 1 + 9 + 6 = 16 # 1 ... ``` `196` is not a Keith number, so return `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. Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent. For each photo it is known which orientation is intended for it β€” horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo. Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos. Help Vasya find the maximum number of photos he is able to watch during T seconds. Input The first line of the input contains 4 integers n, a, b, T (1 ≀ n ≀ 5Β·105, 1 ≀ a, b ≀ 1000, 1 ≀ T ≀ 109) β€” the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo. Second line of the input contains a string of length n containing symbols 'w' and 'h'. If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation. If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation. Output Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds. Examples Input 4 2 3 10 wwhw Output 2 Input 5 2 4 13 hhwhh Output 4 Input 5 2 4 1000 hhwhh Output 5 Input 3 1 100 10 whw Output 0 Note In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds. Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. 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. One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one! Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture. In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses. The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n. Input The only line contains n (1 ≀ n ≀ 25) β€” the required sum of points. Output Print the numbers of ways to get the second card in the required way if the first card is the queen of spades. Examples Input 12 Output 4 Input 20 Output 15 Input 10 Output 0 Note In the first sample only four two's of different suits can earn the required sum of points. In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use. In the third sample there is no card, that would add a zero to the current ten points. 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 Statement Nathan O. Davis is a student at the department of integrated systems. Today's agenda in the class is audio signal processing. Nathan was given a lot of homework out. One of the homework was to write a program to process an audio signal. He copied the given audio signal to his USB memory and brought it back to his home. When he started his homework, he unfortunately dropped the USB memory to the floor. He checked the contents of the USB memory and found that the audio signal data got broken. There are several characteristics in the audio signal that he copied. * The audio signal is a sequence of $N$ samples. * Each sample in the audio signal is numbered from $1$ to $N$ and represented as an integer value. * Each value of the odd-numbered sample(s) is strictly smaller than the value(s) of its neighboring sample(s). * Each value of the even-numbered sample(s) is strictly larger than the value(s) of its neighboring sample(s). He got into a panic and asked you for a help. You tried to recover the audio signal from his USB memory but some samples of the audio signal are broken and could not be recovered. Fortunately, you found from the metadata that all the broken samples have the same integer value. Your task is to write a program, which takes the broken audio signal extracted from his USB memory as its input, to detect whether the audio signal can be recovered uniquely. Input The input consists of multiple datasets. The form of each dataset is described below. > $N$ > $a_{1}$ $a_{2}$ ... $a_{N}$ The first line of each dataset consists of an integer, $N (2 \le N \le 1{,}000)$. $N$ denotes the number of samples in the given audio signal. The second line of each dataset consists of $N$ values separated by spaces. The $i$-th value, $a_{i}$, is either a character `x` or an integer between $-10^9$ and $10^9$, inclusive. It represents the $i$-th sample of the broken audio signal. If $a_{i}$ is a character `x` , it denotes that $i$-th sample in the audio signal is broken. Otherwise it denotes the value of the $i$-th sample. The end of input is indicated by a single $0$. This is not included in the datasets. You may assume that the number of the datasets does not exceed $100$. Output For each dataset, output the value of the broken samples in one line if the original audio signal can be recovered uniquely. If there are multiple possible values, output `ambiguous`. If there are no possible values, output `none`. Sample Input 5 1 x 2 4 x 2 x x 2 1 2 2 2 1 2 1000000000 x 4 x 2 1 x 0 Output for the Sample Input 3 none ambiguous none ambiguous none Example Input 5 1 x 2 4 x 2 x x 2 1 2 2 2 1 2 1000000000 x 4 x 2 1 x 0 Output 3 none ambiguous none ambiguous 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. Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M. Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N): - There exists a non-negative integer p such that X= a_k \times (p+0.5). Find the number of semi-common multiples of A among the integers between 1 and M (inclusive). -----Constraints----- - 1 \leq N \leq 10^5 - 1 \leq M \leq 10^9 - 2 \leq a_i \leq 10^9 - a_i is an even number. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N M a_1 a_2 ... a_N -----Output----- Print the number of semi-common multiples of A among the integers between 1 and M (inclusive). -----Sample Input----- 2 50 6 10 -----Sample Output----- 2 - 15 = 6 \times 2.5 - 15 = 10 \times 1.5 - 45 = 6 \times 7.5 - 45 = 10 \times 4.5 Thus, 15 and 45 are semi-common multiples of A. There are no other semi-common multiples of A between 1 and 50, so the answer 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. Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food. Iahub asks Iahubina: can you build a rooted tree, such that * each internal node (a node with at least one son) has at least two sons; * node i has ci nodes in its subtree? Iahubina has to guess the tree. Being a smart girl, she realized that it's possible no tree can follow Iahub's restrictions. In this way, Iahub will eat all the food. You need to help Iahubina: determine if there's at least one tree following Iahub's restrictions. The required tree must contain n nodes. Input The first line of the input contains integer n (1 ≀ n ≀ 24). Next line contains n positive integers: the i-th number represents ci (1 ≀ ci ≀ n). Output Output on the first line "YES" (without quotes) if there exist at least one tree following Iahub's restrictions, otherwise output "NO" (without quotes). Examples Input 4 1 1 1 4 Output YES Input 5 1 1 5 2 1 Output NO 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 date (from 2004/1/1 to 2004/12/31) and prints the day of the date. Jan. 1, 2004, is Thursday. Note that 2004 is a leap year and we have Feb. 29. Input The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset consists of two integers m and d separated by a single space in a line. These integers respectively represent the month and the day. The number of datasets is less than or equal to 50. Output For each dataset, print the day (please see the following words) in a line. Monday Tuesday Wednesday Thursday Friday Saturday Sunday Example Input 1 1 2 29 0 0 Output Thursday Sunday 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. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem. Input The single line contains two integers l and r (1 ≀ l ≀ r ≀ 109) β€” the left and right interval limits. Output In the single line print the only number β€” the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 7 Output 33 Input 7 7 Output 7 Note In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33 In the second sample: next(7) = 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. A: Alphabet block Wakana Nakawa loves palindromes. Because my name is also a palindrome. Wakana got a set with some alphabet blocks. An alphabet block is a block in which one lowercase alphabet is written for each block, and you can create your favorite character string by changing the order of the blocks and combining them. Wakana is wondering if she can make a palindrome with this set. The following three types of operations are possible in the set of alphabet blocks, and the cost of each operation is 1. 1. Add one alphabet block (any letter is listed) 2. Change one alphabet block you have to another block (whatever the letters are listed) 3. Delete one alphabet block you currently have I want to make a set that can be rearranged into palindromes by operating the set of alphabet blocks several times. What is the minimum cost of such an operation? Let's think with Wakana-chan. Input The input consists of one line of the string S that points to the information in the first set of alphabet blocks. S consists of lowercase letters only and satisfies 1 \ leq | S | \ leq 10 ^ 3. Output Output the minimum cost for creating a palindrome. Don't forget the newline at the end. Sample Input 1 hcpc Sample Output 1 1 In this case, a palindrome can be created at a cost of 1, but multiple methods are possible. For example, if you add a block of'h', you can make a'hcpch', so you can make a palindrome at a cost of 1. Also, if you delete the block of'h', you can make'cpc', so you can make a palindrome with this method at cost 1. Sample Input 2 ritscamp Sample Output 2 Four Sample Input 3 nakawawakana Sample Output 3 0 If you can create a palindrome from scratch, the cost is zero. Example Input hcpc 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. ## The story you are about to hear is true Our cat, Balor, sadly died of cancer in 2015. While he was alive, the three neighborhood cats Lou, Mustache Cat, and Raoul all recognized our house and yard as Balor's territory, and would behave respectfully towards him and each other when they would visit. But after Balor died, gradually each of these three neighborhood cats began trying to claim his territory as their own, trying to drive the others away by growling, yowling, snarling, chasing, and even fighting, when one came too close to another, and no human was right there to distract or extract one of them before the situation could escalate. It is sad that these otherwise-affectionate animals, who had spent many afternoons peacefully sitting and/or lying near Balor and each other on our deck or around our yard, would turn on each other like that. However, sometimes, if they are far enough away from each other, especially on a warm day when all they really want to do is pick a spot in the sun and lie in it, they will ignore each other, and once again there will be a Peaceable Kingdom. ## Your Mission In this, the first and simplest of a planned trilogy of cat katas :-), all you have to do is determine whether the distances between any visiting cats are large enough to make for a peaceful afternoon, or whether there is about to be an altercation someone will need to deal with by carrying one of them into the house or squirting them with water or what have you. As input your function will receive a list of strings representing the yard as a grid, and an integer representing the minimum distance needed to prevent problems (considering the cats' current states of sleepiness). A point with no cat in it will be represented by a "-" dash. Lou, Mustache Cat, and Raoul will be represented by an upper case L, M, and R respectively. At any particular time all three cats may be in the yard, or maybe two, one, or even none. If the number of cats in the yard is one or none, or if the distances between all cats are at least the minimum distance, your function should return True/true/TRUE (depending on what language you're using), but if there are two or three cats, and the distance between at least two of them is smaller than the minimum distance, your function should return False/false/FALSE. ## Some examples (The yard will be larger in the random test cases, but a smaller yard is easier to see and fit into the instructions here.) In this first example, there is only one cat, so your function should return True. ``` ["------------", "------------", "-L----------", "------------", "------------", "------------"], 10 ``` In this second example, Mustache Cat is at the point yard[1][3] and Raoul is at the point yard[4][7] -- a distance of 5, so because the distance between these two points is smaller than the specified minimum distance of 6, there will be trouble, and your function should return False. ``` ["------------", "---M--------", "------------", "------------", "-------R----", "------------"], 6 ``` In this third example, Lou is at yard[0][11], Raoul is at yard[1][2], and Mustache Cat at yard[5][2]. The distance between Lou and Raoul is 9.05538513814, the distance between Raoul and Mustache Cat is 4, and the distance between Mustache Cat and Lou is 10.295630141 -- all greater than or equal to the specified minimum distance of 4, so the three cats will nap peacefully, and your function should return True. ``` ["-----------L", "--R---------", "------------", "------------", "------------", "--M---------"], 4 ``` Have fun! 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. Word $s$ of length $n$ is called $k$-complete if $s$ is a palindrome, i.e. $s_i=s_{n+1-i}$ for all $1 \le i \le n$; $s$ has a period of $k$, i.e. $s_i=s_{k+i}$ for all $1 \le i \le n-k$. For example, "abaaba" is a $3$-complete word, while "abccba" is not. Bob is given a word $s$ of length $n$ consisting of only lowercase Latin letters and an integer $k$, such that $n$ is divisible by $k$. He wants to convert $s$ to any $k$-complete word. To do this Bob can choose some $i$ ($1 \le i \le n$) and replace the letter at position $i$ with some other lowercase Latin letter. So now Bob wants to know the minimum number of letters he has to replace to convert $s$ to any $k$-complete word. Note that Bob can do zero changes if the word $s$ is already $k$-complete. You are required to answer $t$ test cases independently. -----Input----- The first line contains a single integer $t$ ($1 \le t\le 10^5$) β€” the number of test cases. The first line of each test case contains two integers $n$ and $k$ ($1 \le k < n \le 2 \cdot 10^5$, $n$ is divisible by $k$). The second line of each test case contains a word $s$ of length $n$. It is guaranteed that word $s$ only contains lowercase Latin letters. And it is guaranteed that the sum of $n$ over all test cases will not exceed $2 \cdot 10^5$. -----Output----- For each test case, output one integer, representing the minimum number of characters he has to replace to convert $s$ to any $k$-complete word. -----Example----- Input 4 6 2 abaaba 6 3 abaaba 36 9 hippopotomonstrosesquippedaliophobia 21 7 wudixiaoxingxingheclp Output 2 0 23 16 -----Note----- In the first test case, one optimal solution is aaaaaa. In the second test case, the given word itself is $k$-complete. 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, Russian and Vietnamese as well. There are N students living in the dormitory of Berland State University. Each of them sometimes wants to use the kitchen, so the head of the dormitory came up with a timetable for kitchen's usage in order to avoid the conflicts: The first student starts to use the kitchen at the time 0 and should finish the cooking not later than at the time A_{1}. The second student starts to use the kitchen at the time A_{1} and should finish the cooking not later than at the time A_{2}. And so on. The N-th student starts to use the kitchen at the time A_{N-1} and should finish the cooking not later than at the time A_{N} The holidays in Berland are approaching, so today each of these N students wants to cook some pancakes. The i-th student needs B_{i} units of time to cook. The students have understood that probably not all of them will be able to cook everything they want. How many students will be able to cook without violating the schedule? ------ Input Format ------ The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. \ Each test case contains 3 lines of input - The first line of each test case contains a single integer N denoting the number of students. - The second line contains N space-separated integers A1, A2, ..., AN denoting the moments of time by when the corresponding student should finish cooking. - The third line contains N space-separated integers B1, B2, ..., BN denoting the time required for each of the students to cook. ------ Output Format ------ For each test case, output a single line containing the number of students that will be able to finish the cooking. ------ Constraints ------ 1 ≀ T ≀ 10 \ 1 ≀ N ≀ 104 \ 0 A1 A2 AN 109 \ 1 ≀ Bi ≀ 109 ----- Sample Input 1 ------ 2 3 1 10 15 1 10 3 3 10 20 30 15 5 20 ----- Sample Output 1 ------ 2 1 ----- explanation 1 ------ Example case 1. The first student has 1 unit of time - the moment 0. It will be enough for her to cook. The second student has 9 units of time, but wants to cook for 10 units of time, and won't fit in time. The third student has 5 units of time and will fit in time, because needs to cook only for 3 units of time. Example case 2. Each of students has 10 units of time, but only the second one will be able to fit in time. 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 N children, numbered 1, 2, ..., N. Snuke has decided to distribute x sweets among them. He needs to give out all the x sweets, but some of the children may get zero sweets. For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets. Snuke is trying to maximize the number of happy children by optimally distributing the sweets. Find the maximum possible number of happy children. Constraints * All values in input are integers. * 2 \leq N \leq 100 * 1 \leq x \leq 10^9 * 1 \leq a_i \leq 10^9 Input Input is given from Standard Input in the following format: N x a_1 a_2 ... a_N Output Print the maximum possible number of happy children. Examples Input 3 70 20 30 10 Output 2 Input 3 10 20 30 10 Output 1 Input 4 1111 1 10 100 1000 Output 4 Input 2 10 20 20 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. Each day in Berland consists of $n$ hours. Polycarp likes time management. That's why he has a fixed schedule for each day β€” it is a sequence $a_1, a_2, \dots, a_n$ (each $a_i$ is either $0$ or $1$), where $a_i=0$ if Polycarp works during the $i$-th hour of the day and $a_i=1$ if Polycarp rests during the $i$-th hour of the day. Days go one after another endlessly and Polycarp uses the same schedule for each day. What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day. -----Input----- The first line contains $n$ ($1 \le n \le 2\cdot10^5$) β€” number of hours per day. The second line contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 1$), where $a_i=0$ if the $i$-th hour in a day is working and $a_i=1$ if the $i$-th hour is resting. It is guaranteed that $a_i=0$ for at least one $i$. -----Output----- Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day. -----Examples----- Input 5 1 0 1 0 1 Output 2 Input 6 0 1 0 1 1 0 Output 2 Input 7 1 0 1 1 1 0 1 Output 3 Input 3 0 0 0 Output 0 -----Note----- In the first example, the maximal rest starts in last hour and goes to the first hour of the next day. In the second example, Polycarp has maximal rest from the $4$-th to the $5$-th hour. In the third example, Polycarp has maximal rest from the $3$-rd to the $5$-th hour. In the fourth example, Polycarp has no rest at all. 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 permutation $a$ of size $n$ and you should perform $n$ operations on it. In the $i$-th operation, you can choose a non-empty suffix of $a$ and increase all of its elements by $i$. How can we perform the operations to minimize the number of inversions in the final array? Note that you can perform operations on the same suffix any number of times you want. A permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array. A suffix is several consecutive elements of an array that include the last element of the array. An inversion in an array $a$ is a pair of indices $(i, j)$ such that $i > j$ and $a_{i} < a_{j}$. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) β€” the size of the array. The second line contains $n$ distinct integers $a_{1}, a_{2}, \dots, a_{n}$ ($1 \le a_i \le n$), the initial permutation $a$. It's guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case, print $n$ integers $x_{1}, x_{2}, \ldots, x_{n}$ ($1 \le x_{i} \le n$ for each $1 \le i \le n$) indicating that the $i$-th operation must be applied to the suffix starting at index $x_{i}$. If there are multiple answers, print any of them. -----Examples----- Input 4 4 1 2 3 4 5 1 3 2 4 5 3 2 3 1 1 1 Output 1 1 1 1 1 4 3 2 1 1 3 3 1 -----Note----- In the first test case one of the optimal solutions is to increase the whole array on each operation (that is, choose the suffix starting at index $1$). The final array $[11, 12, 13, 14]$ contains $0$ inversions. In the second test case, $a$ will be equal to $[2, 4, 3, 5, 6]$, $[2, 4, 3, 7, 8]$, $[2, 4, 6, 10, 11]$, $[2, 8, 10, 14, 15]$ and $[7, 13, 15, 19, 20]$ after the first, second, third, fourth, and fifth operations, respectively. So the final array $a$ has zero inversions. 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 prime number is an integer that is greater than 1 and can only be divided by itself or 1. For example, 2 is a prime number because it is divisible only by 2 and 1, but 12 is not a prime number because it is divisible by 2, 3, 4, 6 in addition to 12 and 1. When you enter the integer n, write a program that outputs the largest prime number less than n and the smallest prime number greater than n. Input Given multiple datasets. Each dataset is given n (3 ≀ n ≀ 50,000) on one row. The number of datasets does not exceed 50. Output For each dataset, output the largest prime number less than n and the smallest prime number greater than n on one line, separated by a space. Example Input 19 3517 Output 17 23 3511 3527 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 must convert integers numbers from and to a negative-base binary system. Negative-base systems can accommodate all the same numbers as standard place-value systems, but both positive and negative numbers are represented without the use of a minus sign (or, in computer representation, a sign bit); this advantage is countered by an increased complexity of arithmetic operations. To help understand, the first eight digits (in decimal) of the Base(-2) system is: `[1, -2, 4, -8, 16, -32, 64, -128]` Example conversions: `Decimal, negabinary` ``` 6, '11010' -6, '1110' 4, '100' 18, '10110' -11, '110101' ``` 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 that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string. 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 chess position can be expressed as a string using the Forsyth–Edwards Notation (FEN). Your task is to write a parser that reads in a FEN-encoded string and returns a depiction of the board using the Unicode chess symbols (β™”,β™•,β™˜,etc.). The board should be drawn from the perspective of the active color (i.e. the side making the next move). Using the CodeWars dark theme is strongly recommended for this kata. Otherwise, the colors will appear to be inverted. The complete FEN format contains 6 fields separated by spaces, but we will only consider the first two fields: Piece placement and active color (side-to-move). The rules for these fields are as follows: The first field of the FEN describes piece placement. Each row ('rank') of the board is described one-by-one, starting with rank 8 (the far side of the board from White's perspective) and ending with rank 1 (White's home rank). Rows are separated by a forward slash ('/'). Within each row, the contents of the squares are listed starting with the "a-file" (White's left) and ending with the "h-file" (White's right). Each piece is identified by a single letter: pawn = P, knight = N, bishop = B, rook = R, queen = Q and king = K. White pieces are upper-case (PNBRQK), while black pieces are lowercase (pnbrqk). Empty squares are represented using the digits 1 through 8 to denote the number of consecutive empty squares. The piece placement field is followed by a single space, then a single character representing the color who has the next move ('w' for White and 'b' for Black). Four additional fields follow the active color, separated by spaces. These fields can be ignored. Using this encoding, the starting position is: ```rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``` Using the characters "οΌΏ" and "β–‡" to represent dark and light unoccupied spaces, respectively, the starting position using the Unicode pieces would be: β™–β™˜β™—β™•β™”β™—β™˜β™– β™™β™™β™™β™™β™™β™™β™™β™™ β–‡οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡οΌΏ οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡ β–‡οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡οΌΏ οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡ β™Ÿβ™Ÿβ™Ÿβ™Ÿβ™Ÿβ™Ÿβ™Ÿβ™Ÿ β™œβ™žβ™β™›β™šβ™β™žβ™œ After the move 1. Nf3, the FEN would be... ```rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R b KQkq - 1 1``` ...and because we draw the board from the perspective of the active color, the Unicode board would be: β™œοΌΏβ™β™›β™šβ™β™žβ™œ β™Ÿβ™Ÿβ™Ÿβ™Ÿβ™Ÿβ™Ÿβ™Ÿβ™Ÿ β–‡οΌΏβ™žοΌΏβ–‡οΌΏβ–‡οΌΏ οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡ β–‡οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡οΌΏ οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡οΌΏβ–‡ β™™β™™β™™β™™β™™β™™β™™β™™ β™–β™˜β™—β™•β™”β™—β™˜β™– Symbols *Again, note that these colors are inverted from the Unicode character names because most people seem to use the dark theme for CodeWars. Empty white square: β–‡ (2587) Empty black square: οΌΏ (FF3F) White king (K): β™š (265A) White queen (Q): β™› (265B) White rook (R): β™œ (265C) White bishop (B): ♝ (265D) White knight (N): β™ž (265E) White pawn (P): β™Ÿ (265F) Black king (k): β™” (2654) Black queen (q): β™• (2655) Black rook (r): β™– (2656) Black bishop (b): β™— (2657) Black knight (n): β™˜ (2658) Black pawn (p): β™™ (2659) NB: Empty squares must have the proper colors. The bottom-right and top-left squares on a chess board are white. 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 a 2 \times N grid. We will denote the square at the i-th row and j-th column (1 \leq i \leq 2, 1 \leq j \leq N) as (i, j). You are initially in the top-left square, (1, 1). You will travel to the bottom-right square, (2, N), by repeatedly moving right or down. The square (i, j) contains A_{i, j} candies. You will collect all the candies you visit during the travel. The top-left and bottom-right squares also contain candies, and you will also collect them. At most how many candies can you collect when you choose the best way to travel? -----Constraints----- - 1 \leq N \leq 100 - 1 \leq A_{i, j} \leq 100 (1 \leq i \leq 2, 1 \leq j \leq N) -----Input----- Input is given from Standard Input in the following format: N A_{1, 1} A_{1, 2} ... A_{1, N} A_{2, 1} A_{2, 2} ... A_{2, N} -----Output----- Print the maximum number of candies that can be collected. -----Sample Input----- 5 3 2 2 4 1 1 2 2 2 1 -----Sample Output----- 14 The number of collected candies will be maximized when you: - move right three times, then move down once, then move right once. 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. Joisino wants to evaluate the formula "A op B". Here, A and B are integers, and the binary operator op is either + or -. Your task is to evaluate the formula instead of her. -----Constraints----- - 1≦A,B≦10^9 - op is either + or -. -----Input----- The input is given from Standard Input in the following format: A op B -----Output----- Evaluate the formula and print the result. -----Sample Input----- 1 + 2 -----Sample Output----- 3 Since 1 + 2 = 3, the output should be 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. Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment. Find all integer solutions x (0 < x < 10^9) of the equation:x = bΒ·s(x)^{a} + c, where a, b, c are some predetermined constant values and function s(x) determines the sum of all digits in the decimal representation of number x. The teacher gives this problem to Dima for each lesson. He changes only the parameters of the equation: a, b, c. Dima got sick of getting bad marks and he asks you to help him solve this challenging problem. -----Input----- The first line contains three space-separated integers: a, b, c (1 ≀ a ≀ 5;Β 1 ≀ b ≀ 10000;Β  - 10000 ≀ c ≀ 10000). -----Output----- Print integer n β€” the number of the solutions that you've found. Next print n integers in the increasing order β€” the solutions of the given equation. Print only integer solutions that are larger than zero and strictly less than 10^9. -----Examples----- Input 3 2 8 Output 3 10 2008 13726 Input 1 2 -18 Output 0 Input 2 2 -1 Output 4 1 31 337 967 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 problem, you should process T testcases. For each testcase, you are given four integers N, M, A, B. Calculate \sum_{i = 0}^{N - 1} floor((A \times i + B) / M). Constraints * 1 \leq T \leq 100,000 * 1 \leq N, M \leq 10^9 * 0 \leq A, B < M Input Input is given from Standard Input in the following format: T N_0 M_0 A_0 B_0 N_1 M_1 A_1 B_1 : N_{T - 1} M_{T - 1} A_{T - 1} B_{T - 1} Output Print the answer for each testcase. Example Input 5 4 10 6 3 6 5 4 3 1 1 0 0 31415 92653 58979 32384 1000000000 1000000000 999999999 999999999 Output 3 13 0 314095480 499999999500000000 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 receive some random elements as a space-delimited string. Check if the elements are part of an ascending sequence of integers starting with 1, with an increment of 1 (e.g. 1, 2, 3, 4). Return: * `0` if the elements can form such a sequence, and no number is missing ("not broken", e.g. `"1 2 4 3"`) * `1` if there are any non-numeric elements in the input ("invalid", e.g. `"1 2 a"`) * `n` if the elements are part of such a sequence, but some numbers are missing, and `n` is the lowest of them ("broken", e.g. `"1 2 4"` or `"1 5"`) ## Examples ``` "1 2 3 4" ==> return 0, because the sequence is complete "1 2 4 3" ==> return 0, because the sequence is complete (order doesn't matter) "2 1 3 a" ==> return 1, because it contains a non numerical character "1 3 2 5" ==> return 4, because 4 is missing from the sequence "1 5" ==> return 2, because the sequence is missing 2, 3, 4 and 2 is the lowest ``` 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. Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split! Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space). The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXT SENTENCE ::= WORD SPACE SENTENCE | WORD END END ::= {'.', '?', '!'} WORD ::= LETTER | LETTER WORD LETTER ::= {'a'..'z', 'A'..'Z'} SPACE ::= ' ' SPACE stands for the symbol of a space. So, how many messages did Fangy send? Input The first line contains an integer n, which is the size of one message (2 ≀ n ≀ 255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty. Output On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes. Examples Input 25 Hello. I am a little walrus. Output 2 Input 2 How are you? Output Impossible Input 19 Hello! Do you like fish? Why? Output 3 Note Let's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?". 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. Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least a_{i} any pieces of information from the other computers. Doc can hack the computer only if he is right next to it. The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1. It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information. -----Input----- The first line contains number n (1 ≀ n ≀ 1000). The second line contains n non-negative integers a_1, a_2, ..., a_{n} (0 ≀ a_{i} < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information. -----Output----- Print a single number β€” the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information. -----Examples----- Input 3 0 2 0 Output 1 Input 5 4 2 3 0 1 Output 3 Input 7 0 3 1 0 5 2 6 Output 2 -----Note----- In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece. In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer. In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7. 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 Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n. A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≀ ai ≀ n), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length n. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules: * Before the beginning of the game Petya writes permutation 1, 2, ..., n on the blackboard. After that Petya makes exactly k moves, which are described below. * During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. 1. Let's assume that the board contains permutation p1, p2, ..., pn at the given moment. Then Petya removes the written permutation p from the board and writes another one instead: pq1, pq2, ..., pqn. In other words, Petya applies permutation q (which he has got from his mother) to permutation p. 2. All actions are similar to point 1, except that Petya writes permutation t on the board, such that: tqi = pi for all i from 1 to n. In other words, Petya applies a permutation that is inverse to q to permutation p. We know that after the k-th move the board contained Masha's permutation s1, s2, ..., sn. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the k-th move. Note that the game has exactly k moves, that is, throughout the game the coin was tossed exactly k times. Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding. Input The first line contains two integers n and k (1 ≀ n, k ≀ 100). The second line contains n space-separated integers q1, q2, ..., qn (1 ≀ qi ≀ n) β€” the permutation that Petya's got as a present. The third line contains Masha's permutation s, in the similar format. It is guaranteed that the given sequences q and s are correct permutations. Output If the situation that is described in the statement is possible, print "YES" (without the quotes), otherwise print "NO" (without the quotes). Examples Input 4 1 2 3 4 1 1 2 3 4 Output NO Input 4 1 4 3 1 2 3 4 2 1 Output YES Input 4 3 4 3 1 2 3 4 2 1 Output YES Input 4 2 4 3 1 2 2 1 4 3 Output YES Input 4 1 4 3 1 2 2 1 4 3 Output NO Note In the first sample Masha's permutation coincides with the permutation that was written on the board before the beginning of the game. Consequently, that violates the condition that Masha's permutation never occurred on the board before k moves were performed. In the second sample the described situation is possible, in case if after we toss a coin, we get tails. In the third sample the possible coin tossing sequence is: heads-tails-tails. In the fourth sample the possible coin tossing sequence is: heads-heads. 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 plate and you want to add some gilding to it. The plate is a rectangle that we split into $w\times h$ cells. There should be $k$ gilded rings, the first one should go along the edge of the plate, the second oneΒ β€” $2$ cells away from the edge and so on. Each ring has a width of $1$ cell. Formally, the $i$-th of these rings should consist of all bordering cells on the inner rectangle of size $(w - 4(i - 1))\times(h - 4(i - 1))$. [Image] The picture corresponds to the third example. Your task is to compute the number of cells to be gilded. -----Input----- The only line contains three integers $w$, $h$ and $k$ ($3 \le w, h \le 100$, $1 \le k \le \left\lfloor \frac{min(n, m) + 1}{4}\right\rfloor$, where $\lfloor x \rfloor$ denotes the number $x$ rounded down) β€” the number of rows, columns and the number of rings, respectively. -----Output----- Print a single positive integerΒ β€” the number of cells to be gilded. -----Examples----- Input 3 3 1 Output 8 Input 7 9 1 Output 28 Input 7 9 2 Output 40 -----Note----- The first example is shown on the picture below. [Image] The second example is shown on the picture below. [Image] The third example is shown in the problem description. 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 Pac-Man got lucky today! Due to minor performance issue all his enemies have frozen. Too bad Pac-Man is not brave enough to face them right now, so he doesn't want any enemy to see him. Given a gamefield of size `N` x `N`, Pac-Man's position(`PM`) and his enemies' positions(`enemies`), your task is to count the number of coins he can collect without being seen. An enemy can see a Pac-Man if they are standing on the same row or column. It is guaranteed that no enemy can see Pac-Man on the starting position. There is a coin on each empty square (i.e. where there is no Pac-Man or enemy). # Example For `N = 4, PM = [3, 0], enemies = [[1, 2]]`, the result should be `3`. ``` Let O represent coins, P - Pac-Man and E - enemy. OOOO OOEO OOOO POOO``` Pac-Man cannot cross row 1 and column 2. He can only collect coins from points `(2, 0), (2, 1) and (3, 1)`, like this: ``` x is the points that Pac-Man can collect the coins. OOOO OOEO xxOO PxOO ``` # Input/Output - `[input]` integer `N` The field size. - `[input]` integer array `PM` Pac-Man's position (pair of integers) - `[input]` 2D integer array `enemies` Enemies' positions (array of pairs) - `[output]` an integer Number of coins Pac-Man can collect. # More PacMan Katas - [Play PacMan: Devour all](https://www.codewars.com/kata/575c29d5fcee86cb8b000136) - [Play PacMan 2: The way home](https://www.codewars.com/kata/575ed46e23891f67d90000d8) 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. Let's denote correct match equation (we will denote it as CME) an equation $a + b = c$ there all integers $a$, $b$ and $c$ are greater than zero. For example, equations $2 + 2 = 4$ (||+||=||||) and $1 + 2 = 3$ (|+||=|||) are CME but equations $1 + 2 = 4$ (|+||=||||), $2 + 2 = 3$ (||+||=|||), and $0 + 1 = 1$ (+|=|) are not. Now, you have $n$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME! For example, if $n = 2$, you can buy two matches and assemble |+|=||, and if $n = 5$ you can buy one match and assemble ||+|=|||. [Image] Calculate the minimum number of matches which you have to buy for assembling CME. Note, that you have to answer $q$ independent queries. -----Input----- The first line contains one integer $q$ ($1 \le q \le 100$)Β β€” the number of queries. The only line of each query contains one integer $n$ ($2 \le n \le 10^9$)Β β€” the number of matches. -----Output----- For each test case print one integer in single lineΒ β€” the minimum number of matches which you have to buy for assembling CME. -----Example----- Input 4 2 5 8 11 Output 2 1 0 1 -----Note----- The first and second queries are explained in the statement. In the third query, you can assemble $1 + 3 = 4$ (|+|||=||||) without buying matches. In the fourth query, buy one match and assemble $2 + 4 = 6$ (||+||||=||||||). 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. This is the hard version of this problem. The only difference is the constraint on $k$ β€” the number of gifts in the offer. In this version: $2 \le k \le n$. Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very luckyΒ β€” today the offer "$k$ of goods for the price of one" is held in store. Using this offer, Vasya can buy exactly $k$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has. More formally, for each good, its price is determined by $a_i$Β β€” the number of coins it costs. Initially, Vasya has $p$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: Vasya can buy one good with the index $i$ if he currently has enough coins (i.e $p \ge a_i$). After buying this good, the number of Vasya's coins will decrease by $a_i$, (i.e it becomes $p := p - a_i$). Vasya can buy a good with the index $i$, and also choose exactly $k-1$ goods, the price of which does not exceed $a_i$, if he currently has enough coins (i.e $p \ge a_i$). Thus, he buys all these $k$ goods, and his number of coins decreases by $a_i$ (i.e it becomes $p := p - a_i$). Please note that each good can be bought no more than once. For example, if the store now has $n=5$ goods worth $a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$, respectively, $k=2$, and Vasya has $6$ coins, then he can buy $3$ goods. A good with the index $1$ will be bought by Vasya without using the offer and he will pay $2$ coins. Goods with the indices $2$ and $3$ Vasya will buy using the offer and he will pay $4$ coins. It can be proved that Vasya can not buy more goods with six coins. Help Vasya to find out the maximum number of goods he can buy. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$)Β β€” the number of test cases in the test. The next lines contain a description of $t$ test cases. The first line of each test case contains three integers $n, p, k$ ($2 \le n \le 2 \cdot 10^5$, $1 \le p \le 2\cdot10^9$, $2 \le k \le n$)Β β€” the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them. The second line of each test case contains $n$ integers $a_i$ ($1 \le a_i \le 10^4$)Β β€” the prices of goods. It is guaranteed that the sum of $n$ for all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case in a separate line print one integer $m$Β β€” the maximum number of goods that Vasya can buy. -----Example----- Input 8 5 6 2 2 4 3 5 7 5 11 2 2 4 3 5 7 3 2 3 4 2 6 5 2 3 10 1 3 9 2 2 10000 2 10000 10000 2 9999 2 10000 10000 4 6 4 3 2 3 2 5 5 3 1 2 2 1 2 Output 3 4 1 1 2 0 4 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. Determine whether a text T includes a pattern P. Your program should answer for given queries consisting of P_i. Constraints * 1 ≀ length of T ≀ 1000000 * 1 ≀ length of P_i ≀ 1000 * 1 ≀ Q ≀ 10000 * The input consists of alphabetical characters and digits Input In the first line, a text T is given. In the second line, an integer Q denoting the number of queries is given. In the following Q lines, the patterns P_i are given respectively. Output For each question, print 1 if the text includes P_i, or print 0 otherwise. Example Input aabaaa 4 aa ba bb xyz Output 1 1 0 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. Create a function that takes a string and returns that string with the first half lowercased and the last half uppercased. eg: foobar == fooBAR If it is an odd number then 'round' it up to find which letters to uppercase. See example below. sillycase("brian") // --^-- midpoint // bri first half (lower-cased) // AN second half (upper-cased) 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 three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times: - Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n. What is the largest possible sum of the integers written on the blackboard after K operations? -----Constraints----- - A, B and C are integers between 1 and 50 (inclusive). - K is an integer between 1 and 10 (inclusive). -----Input----- Input is given from Standard Input in the following format: A B C K -----Output----- Print the largest possible sum of the integers written on the blackboard after K operations by E869220. -----Sample Input----- 5 3 11 1 -----Sample Output----- 30 In this sample, 5, 3, 11 are initially written on the blackboard, and E869120 can perform the operation once. There are three choices: - Double 5: The integers written on the board after the operation are 10, 3, 11. - Double 3: The integers written on the board after the operation are 5, 6, 11. - Double 11: The integers written on the board after the operation are 5, 3, 22. If he chooses 3., the sum of the integers written on the board afterwards is 5 + 3 + 22 = 30, which is the largest among 1. through 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. Recently, chef Ciel often hears about lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Ciel decides to make Ciel numbers. As you know, Ciel likes the digit 8 very much. And then, Ciel likes the digits 5 and 3. So Ciel defines Ciel numbers as the positive integers k such that d(k, 8) β‰₯ d(k, 5) β‰₯ d(k, 3) and d(k, i) = 0 for all i = 0, 1, 2, 4, 6, 7, 9, where d(k, i) denotes the number of the digit i in the decimal representation of the integer k. For example, the first few Ciel numbers are 8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888, .... Ciel's restaurant has N menus. And Ciel want to know how many menus have Ciel numbers as their price. Your task is to find it. ------ Input ------ The first line contains an integer N. Then N lines follow. Each line has the name S_{i} of the menu and its price P_{i} separated by a single space. ------ Output ------ Print the number of menus whose prices are one of Ciel numbers. ------ Constraints ------ 1 ≀ N ≀ 1000 1 ≀ |S_{i}| ≀ 100, where |S_{i}| denotes the length of S_{i} Each letter of S_{i} is either an alphabetical letter or a digit or a single quotation mark or a space. 1 ≀ P_{i} < 1000000 (10^{6}) P_{i} contains no leading zeros. ------ Notes ------ Different operating systems have different ways of representing a newline; do not assume one particular way will be used. ----- Sample Input 1 ------ 6 milk 58 Ciel's Drink 80 The curry 2nd edition 888888 rice omelet 85855 unagi 1 The first and last letters can be a space 358 ----- Sample Output 1 ------ 3 ----- explanation 1 ------ 58 and 888888 and 358 are Ciel numbers. 80 and 85855 and 1 are not Ciel numbers. 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 Petya likes to play very much. And most of all he likes to play the following game: He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help. The sequence a is called non-decreasing if a1 ≀ a2 ≀ ... ≀ aN holds, where N is the length of the sequence. Input The first line of the input contains single integer N (1 ≀ N ≀ 5000) β€” the length of the initial sequence. The following N lines contain one integer each β€” elements of the sequence. These numbers do not exceed 109 by absolute value. Output Output one integer β€” minimum number of steps required to achieve the goal. Examples Input 5 3 2 -1 2 11 Output 4 Input 5 2 1 1 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. Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place: * A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars. * Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it. Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally. Input The first input line contains number n (1 ≀ n ≀ 5000) β€” amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0 ≀ x ≀ 2000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0 ≀ x ≀ 2000). Output Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time. Examples Input 7 win 10 win 5 win 3 sell 5 sell 3 win 10 sell 10 Output 1056 Input 3 win 5 sell 6 sell 4 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 taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well. However, the examination system is actually flawed, and if your grade is a multiple of 10, the system displays 0 as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade? -----Constraints----- - All input values are integers. - 1 ≀ N ≀ 100 - 1 ≀ s_i ≀ 100 -----Input----- Input is given from Standard Input in the following format: N s_1 s_2 : s_N -----Output----- Print the maximum value that can be displayed as your grade. -----Sample Input----- 3 5 10 15 -----Sample Output----- 25 Your grade will be 25 if the 10-point and 15-point questions are answered correctly and the 5-point question is not, and this grade will be displayed correctly. Your grade will become 30 if the 5-point question is also answered correctly, but this grade will be incorrectly displayed as 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 a set of all integers from $l$ to $r$ inclusive, $l < r$, $(r - l + 1) \le 3 \cdot 10^5$ and $(r - l)$ is always odd. You want to split these numbers into exactly $\frac{r - l + 1}{2}$ pairs in such a way that for each pair $(i, j)$ the greatest common divisor of $i$ and $j$ is equal to $1$. Each number should appear in exactly one of the pairs. Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them. -----Input----- The only line contains two integers $l$ and $r$ ($1 \le l < r \le 10^{18}$, $r - l + 1 \le 3 \cdot 10^5$, $(r - l)$ is odd). -----Output----- If any solution exists, print "YES" in the first line. Each of the next $\frac{r - l + 1}{2}$ lines should contain some pair of integers. GCD of numbers in each pair should be equal to $1$. All $(r - l + 1)$ numbers should be pairwise distinct and should have values from $l$ to $r$ inclusive. If there are multiple solutions, print any of them. If there exists no solution, print "NO". -----Example----- Input 1 8 Output YES 2 7 4 1 3 8 6 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. Complete the function that determines the score of a hand in the card game [Blackjack](https://en.wikipedia.org/wiki/Blackjack) (aka 21). The function receives an array of strings that represent each card in the hand (`"2"`, `"3",` ..., `"10"`, `"J"`, `"Q"`, `"K"` or `"A"`) and should return the score of the hand (integer). ~~~if:c Note: in C the function receives a character array with the card `10` represented by the character `T`. ~~~ ### Scoring rules: Number cards count as their face value (2 through 10). Jack, Queen and King count as 10. An Ace can be counted as either 1 or 11. Return the highest score of the cards that is less than or equal to 21. If there is no score less than or equal to 21 return the smallest score more than 21. ## Examples ``` ["A"] ==> 11 ["A", "J"] ==> 21 ["A", "10", "A"] ==> 12 ["5", "3", "7"] ==> 15 ["5", "4", "3", "2", "A", "K"] ==> 25 ``` 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 Little Elephant from the Zoo of Lviv likes listening to music. There are N songs, numbered from 1 to N, in his MP3-player. The song i is described by a pair of integers B_{i} and L_{i} - the band (represented as integer) that performed that song and the length of that song in seconds. The Little Elephant is going to listen all the songs exactly once in some order. The sweetness of the song is equal to the product of the length of that song and the number of different bands listened before (including the current playing song). Help the Little Elephant to find the order that maximizes the total sweetness of all N songs. Print that sweetness. ------ Input ------ The first line of the input contains single integer T, denoting the number of test cases. Then T test cases follow. The first line of each test case contains single integer N, denoting the number of the songs. The next N lines describe the songs in the MP3-player. The i-th line contains two space-sparated integers B_{i} and L_{i}. ------ Output ------ For each test, output the maximum total sweetness. ------ Constraints ------ $1 ≀ T ≀ 5$ $1 ≀ N ≀ 100000 (10^{5})$ $1 ≀ B_{i}, L_{i} ≀ 1000000000 (10^{9})$ ----- Sample Input 1 ------ 2 3 1 2 2 2 3 2 3 2 3 1 2 2 4 ----- Sample Output 1 ------ 12 16 ----- explanation 1 ------ In the first sample: if he listens the songs in given order, thenB1=1, L1=2: the sweetness = 2 * 1 = 2B2=2, L2=2: the sweetness = 2 * 2 = 4B3=3, L3=2: the sweetness = 2 * 3 = 6So the total sweetness is 12. In this case, you can check the total sweetness does not depend on the order of the songs. In the second sample: if he listens the songs in given order, thenB1=2, L1=3: the sweetness = 3 * 1 = 3B2=1, L2=2: the sweetness = 2 * 2 = 4B3=2, L3=4: the sweetness = 4 * 2 = 8So the total sweetness is 15. However, he listens the song 2 firstly, thenB2=1, L2=2: the sweetness = 2 * 1 = 2B1=2, L1=3: the sweetness = 3 * 2 = 6B3=2, L3=4: the sweetness = 4 * 2 = 8So the total sweetness is 16, and it is the maximum total sweetness. 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. Polycarpus is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array a for all indexes in the segment [l, r]. In other words, this function does the following: function rangeIncrement(l, r) for i := l .. r do a[i] = a[i] + 1 Polycarpus knows the state of the array a after a series of function calls. He wants to determine the minimum number of function calls that lead to such state. In addition, he wants to find what function calls are needed in this case. It is guaranteed that the required number of calls does not exceed 105. Before calls of function rangeIncrement(l, r) all array elements equal zero. Input The first input line contains a single integer n (1 ≀ n ≀ 105) β€” the length of the array a[1... n]. The second line contains its integer space-separated elements, a[1], a[2], ..., a[n] (0 ≀ a[i] ≀ 105) after some series of function calls rangeIncrement(l, r). It is guaranteed that at least one element of the array is positive. It is guaranteed that the answer contains no more than 105 calls of function rangeIncrement(l, r). Output Print on the first line t β€” the minimum number of calls of function rangeIncrement(l, r), that lead to the array from the input data. It is guaranteed that this number will turn out not more than 105. Then print t lines β€” the descriptions of function calls, one per line. Each line should contain two integers li, ri (1 ≀ li ≀ ri ≀ n) β€” the arguments of the i-th call rangeIncrement(l, r). Calls can be applied in any order. If there are multiple solutions, you are allowed to print any of them. Examples Input 6 1 2 1 1 4 1 Output 5 2 2 5 5 5 5 5 5 1 6 Input 5 1 0 1 0 1 Output 3 1 1 3 3 5 5 Note The first sample requires a call for the entire array, and four additional calls: * one for the segment [2,2] (i.e. the second element of the array), * three for the segment [5,5] (i.e. the fifth element of the array). 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 find the sum for the range `0 ... m` for all powers from `0 ... n. # Example For `m = 2, n = 3`, the result should be `20` `0^0+1^0+2^0 + 0^1+1^1+2^1 + 0^2+1^2+2^2 + 0^3+1^3+2^3 = 20` Note, that no output ever exceeds 2e9. # Input/Output - `[input]` integer m `0 <= m <= 50000` - `[input]` integer `n` `0 <= n <= 9` - `[output]` an integer(double in C#) The sum value. 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 invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a_1, a_2, ..., a_{n}. His teapot stores w milliliters of tea (w ≀ a_1 + a_2 + ... + a_{n}). Polycarp wants to pour tea in cups in such a way that: Every cup will contain tea for at least half of its volume Every cup will contain integer number of milliliters of tea All the tea from the teapot will be poured into cups All friends will be satisfied. Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but a_{i} > a_{j}. For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1. -----Input----- The first line contains two integer numbers n and w (1 ≀ n ≀ 100, $1 \leq w \leq \sum_{i = 1}^{n} a_{i}$). The second line contains n numbers a_1, a_2, ..., a_{n} (1 ≀ a_{i} ≀ 100). -----Output----- Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them. If it's impossible to pour all the tea and satisfy all conditions then output -1. -----Examples----- Input 2 10 8 7 Output 6 4 Input 4 4 1 1 1 1 Output 1 1 1 1 Input 3 10 9 8 10 Output -1 -----Note----- In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available. 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. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≀ n, m ≀ 500, 0 ≀ b ≀ 500; 1 ≀ mod ≀ 109 + 7) β€” the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 500) β€” the number of bugs per line for each programmer. Output Print a single integer β€” the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 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 an integer $n$. You have to calculate the number of binary (consisting of characters 0 and/or 1) strings $s$ meeting the following constraints. For every pair of integers $(i, j)$ such that $1 \le i \le j \le n$, an integer $a_{i,j}$ is given. It imposes the following constraint on the string $s_i s_{i+1} s_{i+2} \dots s_j$: if $a_{i,j} = 1$, all characters in $s_i s_{i+1} s_{i+2} \dots s_j$ should be the same; if $a_{i,j} = 2$, there should be at least two different characters in $s_i s_{i+1} s_{i+2} \dots s_j$; if $a_{i,j} = 0$, there are no additional constraints on the string $s_i s_{i+1} s_{i+2} \dots s_j$. Count the number of binary strings $s$ of length $n$ meeting the aforementioned constraints. Since the answer can be large, print it modulo $998244353$. -----Input----- The first line contains one integer $n$ ($2 \le n \le 100$). Then $n$ lines follow. The $i$-th of them contains $n-i+1$ integers $a_{i,i}, a_{i,i+1}, a_{i,i+2}, \dots, a_{i,n}$ ($0 \le a_{i,j} \le 2$). -----Output----- Print one integer β€” the number of strings meeting the constraints, taken modulo $998244353$. -----Examples----- Input 3 1 0 2 1 0 1 Output 6 Input 3 1 1 2 1 0 1 Output 2 Input 3 1 2 1 1 0 1 Output 0 Input 3 2 0 2 0 1 1 Output 0 -----Note----- In the first example, the strings meeting the constraints are 001, 010, 011, 100, 101, 110. In the second example, the strings meeting the constraints are 001, 110. 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. Some country is populated by wizards. They want to organize a demonstration. There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration. So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets. Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people. Input The first line contains three space-separated integers, n, x, y (1 ≀ n, x, y ≀ 104, x ≀ n) β€” the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly. Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n). Output Print a single integer β€” the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population). Examples Input 10 1 14 Output 1 Input 20 10 50 Output 0 Input 1000 352 146 Output 1108 Note In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone. In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones. 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 are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists. - Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s'). -----Notes----- - A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest. -----Constraints----- - 1 \leq |s| \leq 10^5 - 1 \leq |t| \leq 10^5 - s and t consists of lowercase English letters. -----Input----- Input is given from Standard Input in the following format: s t -----Output----- If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1. -----Sample Input----- contest son -----Sample Output----- 10 t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition. On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition. Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition 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. Write a program that will calculate the number of trailing zeros in a factorial of a given number. `N! = 1 * 2 * 3 * ... * N` Be careful `1000!` has 2568 digits... For more info, see: http://mathworld.wolfram.com/Factorial.html ## Examples ```python zeros(6) = 1 # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero zeros(12) = 2 # 12! = 479001600 --> 2 trailing zeros ``` *Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.* 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 educational reform Polycarp studies only two subjects at school, Safety Studies and PE (Physical Education). During the long months of the fourth term, he received n marks in them. When teachers wrote a mark in the journal, they didn't write in what subject the mark was for, they just wrote the mark. Now it's time to show the journal to his strict parents. Polycarp knows that recently at the Parent Meeting the parents were told that he received a Safety Studies marks and b PE marks (a + b = n). Now Polycarp wants to write a subject's name in front of each mark so that: * there are exactly a Safety Studies marks, * there are exactly b PE marks, * the total average score in both subjects is maximum. An average subject grade is the sum of all marks in it, divided by the number of them. Of course, the division is performed in real numbers without rounding up or down. Polycarp aims to maximize the x1 + x2, where x1 is the average score in the first subject (Safety Studies), and x2 is the average score in the second one (Physical Education). Input The first line contains an integer n (2 ≀ n ≀ 105), n is the number of marks in Polycarp's Journal. The second line contains two positive integers a, b (1 ≀ a, b ≀ n - 1, a + b = n). The third line contains a sequence of integers t1, t2, ..., tn (1 ≀ ti ≀ 5), they are Polycarp's marks. Output Print the sequence of integers f1, f2, ..., fn, where fi (1 ≀ fi ≀ 2) is the number of a subject to which the i-th mark should be attributed. If there are several possible solutions, then print such that the sequence f1, f2, ..., fn is the smallest lexicographically. The sequence p1, p2, ..., pn is lexicographically less than q1, q2, ..., qn if there exists such j (1 ≀ j ≀ n) that pi = qi for all 1 ≀ i < j, Π°nd pj < qj. Examples Input 5 3 2 4 4 5 4 4 Output 1 1 2 1 2 Input 4 2 2 3 5 4 5 Output 1 1 2 2 Input 6 1 5 4 4 4 5 4 4 Output 2 2 2 1 2 2 Note In the first sample the average score in the first subject is equal to 4, and in the second one β€” to 4.5. The total average score is 8.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. # Task Given an array `arr`, find the maximal value of `k` such `a[i] mod k` = `a[j] mod k` for all valid values of i and j. If it's impossible to find such number (there's an infinite number of `k`s), return `-1` instead. # Input/Output `[input]` integer array `arr` A non-empty array of positive integer. `2 <= arr.length <= 10` `1 <= arr[i] <= 100` `[output]` an integer The maximum value of `k` or `-1` if there is none. # Example For `arr = [1, 2, 3]`, the output should be `1`. `1` is the only k which satisfies the given conditions. For `arr = [1, 1, 1]`, the output should be `-1`. `1 % k = 1` for `any k > 1`, so it's impossible to find the maximum. For `arr = [5, 2, 8]`, the output should be `3`. `5 % 3 == 2 % 3 == 8 % 3 == 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. Claire is a man-eater. She's a real man-eater. She's going around with dozens of guys. She's dating all the time. And one day she found some conflicts in her date schedule. D'oh! So she needs to pick some dates and give the others up. The dates are set by hours like 13:00 to 15:00. She may have more than one date with a guy. For example, she can have dates with Adam from 10:00 to 12:00 and from 14:00 to 16:00 and with Bob from 12:00 to 13:00 and from 18:00 to 20:00. She can have these dates as long as there is no overlap of time. Time of traveling, time of make-up, trouble from love triangles, and the likes are not of her concern. Thus she can keep all the dates with Adam and Bob in the previous example. All dates are set between 6:00 and 22:00 on the same day. She wants to get the maximum amount of satisfaction in total. Each guy gives her some satisfaction if he has all scheduled dates. Let's say, for example, Adam's satisfaction is 100 and Bob's satisfaction is 200. Then, since she can make it with both guys, she can get 300 in total. Your task is to write a program to satisfy her demand. Then she could spend a few hours with you... if you really want. Input The input consists of a sequence of datasets. Each dataset has the following format: N Guy1 ... GuyN The first line of the input contains an integer N (1 ≀ N ≀ 100), the number of guys. Then there come the descriptions of guys. Each description is given in this format: M L S1 E1 ... SM EM The first line contains two integers Mi (1 ≀ Mi ≀ 16) and Li (1 ≀ Li ≀ 100,000,000), the number of dates set for the guy and the satisfaction she would get from him respectively. Then M lines follow. The i-th line contains two integers Si and Ei (6 ≀ Si < Ei ≀ 22), the starting and ending time of the i-th date. The end of input is indicated by N = 0. Output For each dataset, output in a line the maximum amount of satisfaction she can get. Example Input 2 2 100 10 12 14 16 2 200 12 13 18 20 4 1 100 6 22 1 1000 6 22 1 10000 6 22 1 100000 6 22 16 1 100000000 6 7 1 100000000 7 8 1 100000000 8 9 1 100000000 9 10 1 100000000 10 11 1 100000000 11 12 1 100000000 12 13 1 100000000 13 14 1 100000000 14 15 1 100000000 15 16 1 100000000 16 17 1 100000000 17 18 1 100000000 18 19 1 100000000 19 20 1 100000000 20 21 1 100000000 21 22 0 Output 300 100000 1600000000 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.