question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise. However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not. Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have. Input The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000). The following line contains a binary string of length n representing Kevin's results on the USAICO. Output Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring. Examples Input 8 10000011 Output 5 Input 2 01 Output 2 Note In the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'. In the second sample, Kevin can flip the entire string and still have the same score. 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. Karen has just arrived at school, and she has a math test today! <image> The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points. There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition. Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa. The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test. Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row? Since this number can be quite large, output only the non-negative remainder after dividing it by 109 + 7. Input The first line of input contains a single integer n (1 ≤ n ≤ 200000), the number of numbers written on the first row. The next line contains n integers. Specifically, the i-th one among these is ai (1 ≤ ai ≤ 109), the i-th number on the first row. Output Output a single integer on a line by itself, the number on the final row after performing the process above. Since this number can be quite large, print only the non-negative remainder after dividing it by 109 + 7. Examples Input 5 3 6 9 12 15 Output 36 Input 4 3 7 5 2 Output 1000000006 Note In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15. Karen performs the operations as follows: <image> The non-negative remainder after dividing the final number by 109 + 7 is still 36, so this is the correct output. In the second test case, the numbers written on the first row are 3, 7, 5 and 2. Karen performs the operations as follows: <image> The non-negative remainder after dividing the final number by 109 + 7 is 109 + 6, so this is the correct 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. Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset. Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes. Help Artem implement time travellers multiset. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers a_{i}, t_{i} and x_{i} (1 ≤ a_{i} ≤ 3, 1 ≤ t_{i}, x_{i} ≤ 10^9) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent. -----Output----- For each ask operation output the number of instances of integer being queried at the given moment of time. -----Examples----- Input 6 1 1 5 3 5 5 1 2 5 3 6 5 2 3 5 3 7 5 Output 1 2 1 Input 3 1 1 1 2 2 1 3 3 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. There are N holes in a two-dimensional plane. The coordinates of the i-th hole are (x_i,y_i). Let R=10^{10^{10^{10}}}. Ringo performs the following operation: * Randomly choose a point from the interior of a circle of radius R centered at the origin, and put Snuke there. Snuke will move to the hole with the smallest Euclidean distance from the point, and fall into that hole. If there are multiple such holes, the hole with the smallest index will be chosen. For every i (1 \leq i \leq N), find the probability that Snuke falls into the i-th hole. Here, the operation of randomly choosing a point from the interior of a circle of radius R is defined as follows: * Pick two real numbers x and y independently according to uniform distribution on [-R,R]. * If x^2+y^2\leq R^2, the point (x,y) is chosen. Otherwise, repeat picking the real numbers x,y until the condition is met. Constraints * 2 \leq N \leq 100 * |x_i|,|y_i| \leq 10^6(1\leq i\leq N) * All given points are pairwise distinct. * All input values are integers. Input Input is given from Standard Input in the following format: N x_1 y_1 : x_N y_N Output Print N real numbers. The i-th real number must represent the probability that Snuke falls into the i-th hole. The output will be judged correct when, for all output values, the absolute or relative error is at most 10^{-5}. Examples Input 2 0 0 1 1 Output 0.5 0.5 Input 5 0 0 2 8 4 5 2 6 3 10 Output 0.43160120892732328768 0.03480224363653196956 0.13880483535586193855 0.00000000000000000000 0.39479171208028279727 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. Takahashi has two positive integers A and B. It is known that A plus B equals N. Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10). Constraints * 2 ≤ N ≤ 10^5 * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B". Examples Input 15 Output 6 Input 100000 Output 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. Read problems statements in Mandarin Chinese and Russian as well. A version control system(VCS) is a repository of files, often the files for the source code of computer programs, with monitored access. Every change made to the source is tracked, along with who made the change, why they made it, and references to problems fixed, or enhancements introduced, by the change. Version control systems are essential for any form of distributed, collaborative development. Whether it is the history of a wiki page or large software development project, the ability to track each change as it was made, and to reverse changes when necessary can make all the difference between a well managed and controlled process and an uncontrolled ‘first come, first served’ system. It can also serve as a mechanism for due diligence for software projects. In this problem we'll consider a simplified model of a development project. Let's suppose, that there are N source files in the project. All the source files are distinct and numbered from 1 to N. A VCS, that is used for maintaining the project, contains two sequences of source files. The first sequence contains the source files, that are ignored by the VCS. If a source file is not in the first sequence, then it's considered to be unignored. The second sequence contains the source files, that are tracked by the VCS. If a source file is not in the second sequence, then it's considered to be untracked. A source file can either be or not be in any of these two sequences. Your task is to calculate two values: the number of source files of the project, that are both tracked and ignored, and the number of source files of the project, that are both untracked and unignored. ------ Input ------ The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of the test case description contains three integers N, M and K denoting the number of source files in the project, the number of ignored source files and the number of tracked source files. The second line contains M distinct integers denoting the sequence A of ignored source files. The sequence is strictly increasing. The third line contains K distinct integers denoting the sequence B of tracked source files. The sequence is strictly increasing. ------ Output ------ For each test case, output a single line containing two integers: the number of the source files, that are both tracked and ignored, and the number of the source files, that are both untracked and unignored. ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ M, K ≤ N ≤ 100$ $1 ≤ A_{1} < A_{2} < ... < A_{M} ≤ N$ $1 ≤ B_{1} < B_{2} < ... < B_{K} ≤ N$ ----- Sample Input 1 ------ 2 7 4 6 1 4 6 7 1 2 3 4 6 7 4 2 2 1 4 3 4 ----- Sample Output 1 ------ 4 1 1 1 ----- explanation 1 ------ In the first test case, the source files {1, 4, 6, 7} are both tracked and ignored, the source file {5} is both untracked and unignored. In the second test case, the source file {4} is both tracked and ignored, the source file {2} is both untracked and unignored. 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 huge decimal number consisting of $n$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1. You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem. You are also given two integers $0 \le y < x < n$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $10^y$ modulo $10^x$. In other words, the obtained number should have remainder $10^y$ when divided by $10^x$. -----Input----- The first line of the input contains three integers $n, x, y$ ($0 \le y < x < n \le 2 \cdot 10^5$) — the length of the number and the integers $x$ and $y$, respectively. The second line of the input contains one decimal number consisting of $n$ digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1. -----Output----- Print one integer — the minimum number of operations you should perform to obtain the number having remainder $10^y$ modulo $10^x$. In other words, the obtained number should have remainder $10^y$ when divided by $10^x$. -----Examples----- Input 11 5 2 11010100101 Output 1 Input 11 5 1 11010100101 Output 3 -----Note----- In the first example the number will be $11010100100$ after performing one operation. It has remainder $100$ modulo $100000$. In the second example the number will be $11010100010$ after performing three operations. It has remainder $10$ modulo $100000$. 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. Maya writes weekly articles to a well known magazine, but she is missing one word each time she is about to send the article to the editor. The article is not complete without this word. Maya has a friend, Dan, and he is very good with words, but he doesn't like to just give them away. He texts Maya a number and she needs to find out the hidden word. The words can contain only the letter: "a", "b", "d", "e", "i", "l", "m", "n", "o", and "t". Luckily, Maya has the key: "a" - 6 "b" - 1 "d" - 7 "e" - 4 "i" - 3 "l" - 2 "m" - 9 "n" - 8 "o" - 0 "t" - 5 You can help Maya by writing a function that will take a number between 100 and 999999 and return a string with the word. The input is always a number, contains only the numbers in the key. The output should be always a string with one word, all lowercase. Maya won't forget to thank you at the end of her article :) Write your solution by modifying this code: ```python def hidden(num): ``` Your solution should implemented in the function "hidden". The i 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. If you draw a few infinitely long straight lines on an infinitely wide plane, this plane will be divided into several areas. For example, if you draw a straight line, the plane will be divided into two areas. Even if you draw the same number of straight lines, the number of areas obtained will differ depending on how you draw. For example, if you draw two straight lines in parallel, you get three areas, and if you draw two straight lines perpendicular to each other, you get four areas. <image> Create a program that outputs the maximum number of regions that can be obtained by drawing n straight lines. Input Given multiple datasets. Each dataset is given n (1 ≤ n ≤ 10,000) on one row. Please process until the end of the input. The number of datasets does not exceed 50. Output For each dataset, output the maximum number of divisions on one line. Example Input 1 3 Output 2 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. Mr. E Ven only likes even length words. Please create a translator so that he doesn't have to hear those pesky odd length words. For some reason he also hates punctuation, he likes his sentences to flow. Your translator should take in a string and output it with all odd length words having an extra letter (the last letter in the word). It should also remove all punctuation (.,?!) as well as any underscores (_). "How did we end up here? We go?" translated becomes-> "Howw didd we endd up here We go" Write your solution by modifying this code: ```python def evenator(s): ``` Your solution should implemented in the function "evenator". The i 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. At 17:00, special agent Jack starts to escape from the enemy camp. There is a cliff in between the camp and the nearest safety zone. Jack has to climb the almost vertical cliff by stepping his feet on the blocks that cover the cliff. The cliff has slippery blocks where Jack has to spend time to take each step. He also has to bypass some blocks that are too loose to support his weight. Your mission is to write a program that calculates the minimum time to complete climbing. Figure D-1 shows an example of cliff data that you will receive. The cliff is covered with square blocks. Jack starts cliff climbing from the ground under the cliff, by stepping his left or right foot on one of the blocks marked with 'S' at the bottom row. The numbers on the blocks are the "slippery levels". It takes t time units for him to safely put his foot on a block marked with t, where 1 ≤ t ≤ 9. He cannot put his feet on blocks marked with 'X'. He completes the climbing when he puts either of his feet on one of the blocks marked with 'T' at the top row. <image> Figure D-1: Example of Cliff Data Jack's movement must meet the following constraints. After putting his left (or right) foot on a block, he can only move his right (or left, respectively) foot. His left foot position (lx, ly) and his right foot position (rx, ry) should satisfy lx < rx and | lx - rx | + | ly - ry | ≤ 3 . This implies that, given a position of his left foot in Figure D-2 (a), he has to place his right foot on one of the nine blocks marked with blue color. Similarly, given a position of his right foot in Figure D-2 (b), he has to place his left foot on one of the nine blocks marked with blue color. <image> Figure D-2: Possible Placements of Feet Input The input is a sequence of datasets. The end of the input is indicated by a line containing two zeros separated by a space. Each dataset is formatted as follows: > w h > s(1,1) ... s(1,w) > s(2,1) ... s(2,w) > ... > s(h,1) ... s(h,w) > The integers w and h are the width and the height of the matrix data of the cliff. You may assume 2 ≤ w ≤ 30 and 5 ≤ h ≤ 60. Each of the following h lines consists of w characters delimited by a space. The character s(y, x) represents the state of the block at position (x, y) as follows: * 'S': Jack can start cliff climbing from this block. * 'T': Jack finishes climbing when he reaches this block. * 'X': Jack cannot put his feet on this block. * '1' - '9' (= t): Jack has to spend t time units to put either of his feet on this block. You can assume that it takes no time to put a foot on a block marked with 'S' or 'T'. Output For each dataset, print a line only having a decimal integer indicating the minimum time required for the cliff climbing, when Jack can complete it. Otherwise, print a line only having "-1" for the dataset. Each line should not have any characters other than these numbers. Example Input 6 6 4 4 X X T T 4 7 8 2 X 7 3 X X X 1 8 1 2 X X X 6 1 1 2 4 4 7 S S 2 3 X X 2 10 T 1 1 X 1 X 1 X 1 1 1 X 1 X 1 1 1 X S S 2 10 T X 1 X 1 X 1 X 1 1 1 X 1 X 1 1 1 X S S 10 10 T T T T T T T T T T X 2 X X X X X 3 4 X 9 8 9 X X X 2 9 X 9 7 7 X 7 3 X X 8 9 X 8 9 9 9 6 3 X 5 X 5 8 9 9 9 6 X X 5 X 5 8 6 5 4 6 8 X 5 X 5 8 9 3 9 6 8 X 5 X 5 8 3 9 9 6 X X X 5 X S S S S S S S S S S 10 7 2 3 2 3 2 3 2 3 T T 1 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 4 3 2 3 2 3 2 3 2 3 5 3 2 3 1 3 2 3 2 3 5 2 2 3 2 4 2 3 2 3 5 S S 2 3 2 1 2 3 2 3 0 0 Output 12 5 -1 22 12 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This kata is from check py.checkio.org You are given an array with positive numbers and a number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first element has the index 0. Let's look at a few examples: * array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9; * array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1. Write your solution by modifying this code: ```python def index(array, n): ``` Your solution should implemented in the function "index". The i 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 official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 ≤ i ≤ n) region has a stable temperature of ti degrees in summer. This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is ti + k degrees. Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit. To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money. Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren. Input The first input line contains two integers n and m (1 ≤ n ≤ 105; 1 ≤ m ≤ 106) — the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1 ≤ ti, Ti, xi, costi ≤ 106). The numbers in the lines are separated by single spaces. Output Print the only integer — the minimum number of roubles the organizers will have to spend to transport all schoolchildren. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Examples Input 2 10 30 35 1 100 20 35 10 10 Output 120 Input 3 100 10 30 1000 1 5 10 1000 3 10 40 1000 100000 Output 200065 Note In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles. 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. Nezzar has $n$ balls, numbered with integers $1, 2, \ldots, n$. Numbers $a_1, a_2, \ldots, a_n$ are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that $a_i \leq a_{i+1}$ for all $1 \leq i < n$. Nezzar wants to color the balls using the minimum number of colors, such that the following holds. For any color, numbers on balls will form a strictly increasing sequence if he keeps balls with this chosen color and discards all other balls. Note that a sequence with the length at most $1$ is considered as a strictly increasing sequence. Please help Nezzar determine the minimum number of colors. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of testcases. The first line of each test case contains a single integer $n$ ($1 \le n \le 100$). The second line of each test case contains $n$ integers $a_1,a_2,\ldots,a_n$ ($1 \le a_i \le n$). It is guaranteed that $a_1 \leq a_2 \leq \ldots \leq a_n$. -----Output----- For each test case, output the minimum number of colors Nezzar can use. -----Examples----- Input 5 6 1 1 1 2 3 4 5 1 1 2 2 3 4 2 2 2 2 3 1 2 3 1 1 Output 3 2 4 1 1 -----Note----- Let's match each color with some numbers. Then: In the first test case, one optimal color assignment is $[1,2,3,3,2,1]$. In the second test case, one optimal color assignment is $[1,2,1,2,1]$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We, the researchers who discovered and investigated the ancient nation Iwashiro, finally discovered the temple in the center of Iwashiro. A lithograph dedicated to the god of Iwashiro was stored in the temple. On the lithograph, two strings were written, one for each sentence and one for the spell. In Iwashiro, how many times a spell appears in a sentence has an important meaning. However, it is considered that all the characters contained in the spell appear in order, and some of them appear in the sentence in a discrete manner once. For example, if the sentence is "abab" and the spell is "ab", then "ab" appears three times in "abab", including non-continuous ones (three ways: abab, abab, and abab). Create a program that prints how many times a spell appears in a sentence when it is given a sentence and a spell. Input The input is given in the following format. t b b The first line is given the string t that represents the text written on the lithograph. The second line is given the string b that represents the spell written on the lithograph. Both strings are composed of only lowercase letters and have a length of 1 or more and 1000 or less. Output Prints how many times a spell appears in a sentence on one line. However, the value to be output can be very large, so instead output the remainder divided by 1,000,000,007. Examples Input abab ab Output 3 Input aaaabaaaabaaaabaaaab aaaaa Output 4368 Input data structure 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 a string $s$ consisting of $n$ lowercase Latin letters. You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation. String $s = s_1 s_2 \dots s_n$ is lexicographically smaller than string $t = t_1 t_2 \dots t_m$ if $n < m$ and $s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$ or there exists a number $p$ such that $p \le min(n, m)$ and $s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$ and $s_p < t_p$. For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". -----Input----- The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the length of $s$. The second line of the input contains exactly $n$ lowercase Latin letters — the string $s$. -----Output----- Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $s$. -----Examples----- Input 3 aaa Output aa Input 5 abcda Output abca -----Note----- In the first example you can remove any character of $s$ to obtain the string "aa". In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". 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. Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are $n$ players arranged in a circle, so that for all $j$ such that $2 \leq j \leq n$, player $j - 1$ is to the left of the player $j$, and player $j$ is to the right of player $j - 1$. Additionally, player $n$ is to the left of player $1$, and player $1$ is to the right of player $n$. Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either $0$, $1$, or $2$ other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly $1$ other player, then they should logically attack that player in response. If instead a player is being attacked by $0$ or $2$ other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players. Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the $n$ players in the game to make them instead attack another player  — i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left. Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The descriptions of the test cases follows. The first line of each test case contains one integer $n$ ($3 \leq n \leq 2 \cdot 10^5$)  — the amount of players (and therefore beds) in this game of Bed Wars. The second line of each test case contains a string $s$ of length $n$. The $j$-th character of $s$ is equal to L if the $j$-th player is attacking the player to their left, and R if the $j$-th player is attacking the player to their right. It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case, output one integer: the minimum number of players Omkar needs to talk to to make it so that all players are acting logically according to Bed Wars strategy. It can be proven that it is always possible for Omkar to achieve this under the given constraints. -----Example----- Input 5 4 RLRL 6 LRRRRL 8 RLLRRRLL 12 LLLLRRLRRRLL 5 RRRRR Output 0 1 1 3 2 -----Note----- In the first test case, players $1$ and $2$ are attacking each other, and players $3$ and $4$ are attacking each other. Each player is being attacked by exactly $1$ other player, and each player is attacking the player that is attacking them, so all players are already being logical according to Bed Wars strategy and Omkar does not need to talk to any of them, making the answer $0$. In the second test case, not every player acts logically: for example, player $3$ is attacked only by player $2$, but doesn't attack him in response. Omkar can talk to player $3$ to convert the attack arrangement to LRLRRL, in which you can see that all players are being logical according to Bed Wars strategy, making the answer $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. Notice that the memory limit is non-standard. Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2n. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur's favorite correct bracket sequence just to spite him. All Arthur remembers about his favorite sequence is for each opening parenthesis ('(') the approximate distance to the corresponding closing one (')'). For the i-th opening bracket he remembers the segment [l_{i}, r_{i}], containing the distance to the corresponding closing bracket. Formally speaking, for the i-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment [l_{i}, r_{i}]. Help Arthur restore his favorite correct bracket sequence! -----Input----- The first line contains integer n (1 ≤ n ≤ 600), the number of opening brackets in Arthur's favorite correct bracket sequence. Next n lines contain numbers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} < 2n), representing the segment where lies the distance from the i-th opening bracket and the corresponding closing one. The descriptions of the segments are given in the order in which the opening brackets occur in Arthur's favorite sequence if we list them from left to right. -----Output----- If it is possible to restore the correct bracket sequence by the given data, print any possible choice. If Arthur got something wrong, and there are no sequences corresponding to the given information, print a single line "IMPOSSIBLE" (without the quotes). -----Examples----- Input 4 1 1 1 1 1 1 1 1 Output ()()()() Input 3 5 5 3 3 1 1 Output ((())) Input 3 5 5 3 3 2 2 Output IMPOSSIBLE Input 3 2 3 1 4 1 4 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. Wherever the destination is, whoever we meet, let's render this song together. On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage. On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups: Vertical: stands at (x_{i}, 0), moves in positive y direction (upwards); Horizontal: stands at (0, y_{i}), moves in positive x direction (rightwards). [Image] According to choreography, the i-th dancer should stand still for the first t_{i} milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time. When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on. [Image] Dancers stop when a border of the stage is reached. Find out every dancer's stopping position. -----Input----- The first line of input contains three space-separated positive integers n, w and h (1 ≤ n ≤ 100 000, 2 ≤ w, h ≤ 100 000) — the number of dancers and the width and height of the stage, respectively. The following n lines each describes a dancer: the i-th among them contains three space-separated integers g_{i}, p_{i}, and t_{i} (1 ≤ g_{i} ≤ 2, 1 ≤ p_{i} ≤ 99 999, 0 ≤ t_{i} ≤ 100 000), describing a dancer's group g_{i} (g_{i} = 1 — vertical, g_{i} = 2 — horizontal), position, and waiting time. If g_{i} = 1 then p_{i} = x_{i}; otherwise p_{i} = y_{i}. It's guaranteed that 1 ≤ x_{i} ≤ w - 1 and 1 ≤ y_{i} ≤ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time. -----Output----- Output n lines, the i-th of which contains two space-separated integers (x_{i}, y_{i}) — the stopping position of the i-th dancer in the input. -----Examples----- Input 8 10 8 1 1 10 1 4 13 1 7 1 1 8 2 2 2 0 2 5 14 2 6 0 2 6 1 Output 4 8 10 5 8 8 10 6 10 2 1 8 7 8 10 6 Input 3 2 3 1 1 2 2 1 1 1 1 5 Output 1 3 2 1 1 3 -----Note----- The first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure. [Image] In the second example, no dancers collide. 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 ask you to select some number of positive integers, and calculate the sum of them. It is allowed to select as many integers as you like, and as large integers as you wish. You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer. Your objective is to make the sum congruent to C modulo B. Determine whether this is possible. If the objective is achievable, print YES. Otherwise, print NO. -----Constraints----- - 1 ≤ A ≤ 100 - 1 ≤ B ≤ 100 - 0 ≤ C < B -----Input----- Input is given from Standard Input in the following format: A B C -----Output----- Print YES or NO. -----Sample Input----- 7 5 1 -----Sample Output----- YES For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 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. You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room. The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. [Image] The picture illustrates the first example. You have given k pairs of locations (t_{a}, f_{a}), (t_{b}, f_{b}): floor f_{a} of tower t_{a} and floor f_{b} of tower t_{b}. For each pair you need to determine the minimum walking time between these locations. -----Input----- The first line of the input contains following integers: n: the number of towers in the building (1 ≤ n ≤ 10^8), h: the number of floors in each tower (1 ≤ h ≤ 10^8), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h), k: total number of queries (1 ≤ k ≤ 10^4). Next k lines contain description of the queries. Each description consists of four integers t_{a}, f_{a}, t_{b}, f_{b} (1 ≤ t_{a}, t_{b} ≤ n, 1 ≤ f_{a}, f_{b} ≤ h). This corresponds to a query to find the minimum travel time between f_{a}-th floor of the t_{a}-th tower and f_{b}-th floor of the t_{b}-th tower. -----Output----- For each query print a single integer: the minimum walking time between the locations in minutes. -----Example----- Input 3 6 2 3 3 1 2 1 3 1 4 3 4 1 2 2 3 Output 1 4 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left. On this grid, there is a piece, which is initially placed at square (s_r,s_c). Takahashi and Aoki will play a game, where each player has a string of length N. Takahashi's string is S, and Aoki's string is T. S and T both consist of four kinds of letters: `L`, `R`, `U` and `D`. The game consists of N steps. The i-th step proceeds as follows: * First, Takahashi performs a move. He either moves the piece in the direction of S_i, or does not move the piece. * Second, Aoki performs a move. He either moves the piece in the direction of T_i, or does not move the piece. Here, to move the piece in the direction of `L`, `R`, `U` and `D`, is to move the piece from square (r,c) to square (r,c-1), (r,c+1), (r-1,c) and (r+1,c), respectively. If the destination square does not exist, the piece is removed from the grid, and the game ends, even if less than N steps are done. Takahashi wants to remove the piece from the grid in one of the N steps. Aoki, on the other hand, wants to finish the N steps with the piece remaining on the grid. Determine if the piece will remain on the grid at the end of the game when both players play optimally. Constraints * 2 \leq H,W \leq 2 \times 10^5 * 2 \leq N \leq 2 \times 10^5 * 1 \leq s_r \leq H * 1 \leq s_c \leq W * |S|=|T|=N * S and T consists of the four kinds of letters `L`, `R`, `U` and `D`. Input Input is given from Standard Input in the following format: H W N s_r s_c S T Output If the piece will remain on the grid at the end of the game, print `YES`; otherwise, print `NO`. Examples Input 2 3 3 2 2 RRL LUD Output YES Input 4 3 5 2 2 UDRRR LLDUD Output NO Input 5 6 11 2 1 RLDRRUDDLRL URRDRLLDLRD 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. For an array $b$ of length $m$ we define the function $f$ as $ f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} $ where $\oplus$ is bitwise exclusive OR. For example, $f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$ You are given an array $a$ and a few queries. Each query is represented as two integers $l$ and $r$. The answer is the maximum value of $f$ on all continuous subsegments of the array $a_l, a_{l+1}, \ldots, a_r$. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 5000$) — the length of $a$. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2^{30}-1$) — the elements of the array. The third line contains a single integer $q$ ($1 \le q \le 100\,000$) — the number of queries. Each of the next $q$ lines contains a query represented as two integers $l$, $r$ ($1 \le l \le r \le n$). -----Output----- Print $q$ lines — the answers for the queries. -----Examples----- Input 3 8 4 1 2 2 3 1 2 Output 5 12 Input 6 1 2 4 8 16 32 4 1 6 2 5 3 4 1 2 Output 60 30 12 3 -----Note----- In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment. In second sample, optimal segment for first query are $[3,6]$, for second query — $[2,5]$, for third — $[3,4]$, for fourth — $[1,2]$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. At Akabeko Elementary School, all the students participate in a slightly unusual jogging. Students run their own lap courses at their own pace. After going around each of your courses, you will be returned to elementary school. How many laps do they all meet at the same time in elementary school after they all start elementary school at the same time? Enter the number of students n, the distance d (km) per lap of each student's course, and the running speed v (km / hour) of each student. To do this, create a program that outputs how many laps each student has made. Please note that each student will not run more than 231-1 laps. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: n d1 v1 d2 v2 :: dn vn The first line gives the number of students n (2 ≤ n ≤ 10). The next n lines give the distance di (1 ≤ di ≤ 10000) and the running speed vi (1 ≤ vi ≤ 10000) for one lap of the course of the i-th student. The number of datasets does not exceed 2000. Output Outputs the number of laps for each student for each input dataset. Please output the number of laps of each student on one line according to the order of input. Example Input 2 4 3 5 4 5 789 289 166 46 9 4 617 252 972 303 2 8 5 32 20 0 Output 15 16 1598397732 1209243492 1939462992 1782294192 1360317793 1 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Now I have a card with n numbers on it. Consider arranging some or all of these appropriately to make numbers. Find the number obtained by adding all the numbers created at this time. For example, if you have 1 and 2, you will get 4 numbers 1, 2, 12, 21 so the total number is 36. Even if the same numbers are produced as a result of arranging them, if they are arranged differently, they are added separately. For example, if you have a card called 1 and a card called 11, there are two ways to arrange them so that they are 111, but add them as different ones. There are no leading zero cards among the cards, and we do not accept numbers that lead to zero reading. Output the answer divided by 1,000,000,007. Input The input is given in the form: > n > a1 > a2 > ... > an > The first line contains n (1 ≤ n ≤ 200), which represents the number of cards, and the next n lines contain the number ai (0 ≤ ai <10000) on each card. Also, the same number is never written on multiple cards. Output Output the sum of all the numbers you can make divided by 1,000,000,007 on one line. Examples Input 2 1 2 Output 36 Input 2 1 11 Output 234 Input 4 0 4 7 8 Output 135299 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 **bouncy number** is a positive integer whose digits neither increase nor decrease. For example, `1235` is an increasing number, `5321` is a decreasing number, and `2351` is a bouncy number. By definition, all numbers under `100` are non-bouncy, and `101` is the first bouncy number. To complete this kata, you must write a function that takes a number and determines if it is bouncy. Input numbers will always be positive integers, but it never hurts to throw in some error handling : ) For clarification, the bouncy numbers between `100` and `125` are: `101, 102, 103, 104, 105, 106, 107, 108, 109, 120, and 121`. Write your solution by modifying this code: ```python def is_bouncy(number): ``` Your solution should implemented in the function "is_bouncy". The i 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. Assume that you started to store items in progressively expanding square location, like this for the first 9 numbers: ``` 05 04 03 06 01 02 07 08 09 ``` And like this for the expanding to include up to the first 25 numbers: ``` 17 16 15 14 13 18 05 04 03 12 19 06 01 02 11 20 07 08 09 10 21 22 23 24 25 ``` You might easily notice that the first - and innermost - layer containes only one number (`01`), the second one - immediately around it - contains 8 numbers (number in the `02-09` range) and so on. Your task is to create a function that given a number `n` simply returns the number of layers required to store up to `n` (included). ```python layers(1) == 1 layers(5) == 2 layers(25) == 3 layers(30) == 4 layers(50) == 5 ``` **Fair warning:** you will always and only get positive integers, but be ready for bigger numbers in the tests! If you had fun with this, also try some follow up kata: [progressive spiral number branch](https://www.codewars.com/kata/progressive-spiral-number-branch/) and [progressive spiral number distance](https://www.codewars.com/kata/progressive-spiral-number-distance/). *[Base idea taken from [here](http://adventofcode.com/2017/day/3)]* Write your solution by modifying this code: ```python def layers(n): ``` Your solution should implemented in the function "layers". The i 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. Taking into consideration the [3.5 edition rules](http://www.dandwiki.com/wiki/SRD:Ability_Scores#Table:_Ability_Modifiers_and_Bonus_Spells), your goal is to build a function that takes an ability score (worry not about validation: it is always going to be a non negative integer), will return: * attribute modifier, as indicated on the table of the above link; * maximum spell level for the spells you can cast (-1 for no spells at all) with that score; * the eventual extra spells you might get (as an array/list, with elements representing extra spells for 1st, 2nd,... spell level in order; empty array for no extra spells). The result needs to be an object (associative array in PHP), as shown in the examples: ```python char_attribute(0) == {"modifier": 0, "maximum_spell_level": -1, "extra_spells": []} char_attribute(1) == {"modifier": -5, "maximum_spell_level": -1, "extra_spells": []} char_attribute(5) == {"modifier": -3, "maximum_spell_level": -1, "extra_spells": []} char_attribute(10) == {"modifier": 0, "maximum_spell_level": 0, "extra_spells": []} char_attribute(20) == {"modifier": +5, "maximum_spell_level": 9, "extra_spells": [2,1,1,1,1]} ``` *Note: I didn't explain things in detail and just pointed out to the table on purpose, as my goal is also to train the pattern recognition skills of whoever is going to take this challenges, so do not complain about a summary description. Thanks :)* In the same series: * [D&D Character generator #1: attribute modifiers and spells](https://www.codewars.com/kata/d-and-d-character-generator-number-1-attribute-modifiers-and-spells/) * [D&D Character generator #2: psion power points](https://www.codewars.com/kata/d-and-d-character-generator-number-2-psion-power-points/) * [D&D Character generator #3: carrying capacity](https://www.codewars.com/kata/d-and-d-character-generator-number-3-carrying-capacity/) Write your solution by modifying this code: ```python def char_attribute(score): ``` Your solution should implemented in the function "char_attribute". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function named `first_non_repeating_letter` that takes a string input, and returns the first character that is not repeated anywhere in the string. For example, if given the input `'stress'`, the function should return `'t'`, since the letter *t* only occurs once in the string, and occurs first in the string. As an added challenge, upper- and lowercase letters are considered the **same character**, but the function should return the correct case for the initial letter. For example, the input `'sTreSS'` should return `'T'`. If a string contains *all repeating characters*, it should return an empty string (`""`) or `None` -- see sample tests. Write your solution by modifying this code: ```python def first_non_repeating_letter(string): ``` Your solution should implemented in the function "first_non_repeating_letter". The i 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 got a robot which is situated on an infinite Cartesian plane, initially in the cell $(0, 0)$. Robot can perform the following four kinds of operations: U — move from $(x, y)$ to $(x, y + 1)$; D — move from $(x, y)$ to $(x, y - 1)$; L — move from $(x, y)$ to $(x - 1, y)$; R — move from $(x, y)$ to $(x + 1, y)$. Vasya also has got a sequence of $n$ operations. Vasya wants to modify this sequence so after performing it the robot will end up in $(x, y)$. Vasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: $maxID - minID + 1$, where $maxID$ is the maximum index of a changed operation, and $minID$ is the minimum index of a changed operation. For example, if Vasya changes RRRRRRR to RLRRLRL, then the operations with indices $2$, $5$ and $7$ are changed, so the length of changed subsegment is $7 - 2 + 1 = 6$. Another example: if Vasya changes DDDD to DDRD, then the length of changed subsegment is $1$. If there are no changes, then the length of changed subsegment is $0$. Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them. Help Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from $(0, 0)$ to $(x, y)$, or tell him that it's impossible. -----Input----- The first line contains one integer number $n~(1 \le n \le 2 \cdot 10^5)$ — the number of operations. The second line contains the sequence of operations — a string of $n$ characters. Each character is either U, D, L or R. The third line contains two integers $x, y~(-10^9 \le x, y \le 10^9)$ — the coordinates of the cell where the robot should end its path. -----Output----- Print one integer — the minimum possible length of subsegment that can be changed so the resulting sequence of operations moves the robot from $(0, 0)$ to $(x, y)$. If this change is impossible, print $-1$. -----Examples----- Input 5 RURUU -2 3 Output 3 Input 4 RULR 1 1 Output 0 Input 3 UUU 100 100 Output -1 -----Note----- In the first example the sequence can be changed to LULUU. So the length of the changed subsegment is $3 - 1 + 1 = 3$. In the second example the given sequence already leads the robot to $(x, y)$, so the length of the changed subsegment is $0$. In the third example the robot can't end his path in the cell $(x, y)$. 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 some country live wizards. They love playing with numbers. The blackboard has two numbers written on it — a and b. The order of the numbers is not important. Let's consider a ≤ b for the sake of definiteness. The players can cast one of the two spells in turns: * Replace b with b - ak. Number k can be chosen by the player, considering the limitations that k > 0 and b - ak ≥ 0. Number k is chosen independently each time an active player casts a spell. * Replace b with b mod a. If a > b, similar moves are possible. If at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses. To perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second. Input The first line contains a single integer t — the number of input data sets (1 ≤ t ≤ 104). Each of the next t lines contains two integers a, b (0 ≤ a, b ≤ 1018). The numbers are separated by a space. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator. Output For any of the t input sets print "First" (without the quotes) if the player who moves first wins. Print "Second" (without the quotes) if the player who moves second wins. Print the answers to different data sets on different lines in the order in which they are given in the input. Examples Input 4 10 21 31 10 0 1 10 30 Output First Second Second First Note In the first sample, the first player should go to (11,10). Then, after a single move of the second player to (1,10), he will take 10 modulo 1 and win. In the second sample the first player has two moves to (1,10) and (21,10). After both moves the second player can win. In the third sample, the first player has no moves. In the fourth sample, the first player wins in one move, taking 30 modulo 10. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given a hash of letters and the number of times they occur, recreate all of the possible anagram combinations that could be created using all of the letters, sorted alphabetically. The inputs will never include numbers, spaces or any special characters, only lowercase letters a-z. E.g. get_words({2=>["a"], 1=>["b", "c"]}) => ["aabc", "aacb", "abac", "abca", "acab", "acba", "baac", "baca", "bcaa", "caab", "caba", "cbaa"] Write your solution by modifying this code: ```python def get_words(hash_of_letters): ``` Your solution should implemented in the function "get_words". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}. Snuke, an employee, would like to play with this sequence. Specifically, he would like to repeat the following operation as many times as possible: For every i satisfying 1 \leq i \leq N, perform one of the following: "divide a_i by 2" and "multiply a_i by 3". Here, choosing "multiply a_i by 3" for every i is not allowed, and the value of a_i after the operation must be an integer. At most how many operations can be performed? -----Constraints----- - N is an integer between 1 and 10 \ 000 (inclusive). - a_i is an integer between 1 and 1 \ 000 \ 000 \ 000 (inclusive). -----Input----- Input is given from Standard Input in the following format: N a_1 a_2 a_3 ... a_N -----Output----- Print the maximum number of operations that Snuke can perform. -----Sample Input----- 3 5 2 4 -----Sample Output----- 3 The sequence is initially {5, 2, 4}. Three operations can be performed as follows: - First, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {15, 6, 2}. - Next, multiply a_1 by 3, divide a_2 by 2 and multiply a_3 by 3. The sequence is now {45, 3, 6}. - Finally, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {135, 9, 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. For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n. For example, 4-rounding of 375 is 375·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375. Write a program that will perform the k-rounding of n. -----Input----- The only line contains two integers n and k (1 ≤ n ≤ 10^9, 0 ≤ k ≤ 8). -----Output----- Print the k-rounding of n. -----Examples----- Input 375 4 Output 30000 Input 10000 1 Output 10000 Input 38101 0 Output 38101 Input 123456789 8 Output 12345678900000000 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 the string s of length n and the numbers p, q. Split the string s to pieces of length p and q. For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo". Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test). -----Input----- The first line contains three positive integers n, p, q (1 ≤ p, q ≤ n ≤ 100). The second line contains the string s consists of lowercase and uppercase latin letters and digits. -----Output----- If it's impossible to split the string s to the strings of length p and q print the only number "-1". Otherwise in the first line print integer k — the number of strings in partition of s. Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s — from left to right. If there are several solutions print any of them. -----Examples----- Input 5 2 3 Hello Output 2 He llo Input 10 9 5 Codeforces Output 2 Codef orces Input 6 4 5 Privet Output -1 Input 8 1 1 abacabac Output 8 a b a c a b a 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. In this problem you have to solve a simple classification task: given an image, determine whether it depicts a Fourier doodle. You are given a set of 50 images with ids 1 through 50. You are also given a text file labels.txt containing the labels for images with ids 1 through 20, which comprise the learning data set. You have to output the classification results for images with ids 21 through 50 in the same format. Input [Download the images and the training labels](http://tc-alchemy.progopedia.com/fourier-doodles.zip) Each line of the file labels.txt contains a single integer 0 or 1. Line i (1-based) contains the label of the image {i}.png. Label 1 means that the image depicts a Fourier doodle, label 0 - that it does not. Output Output 30 lines, one line per image 21 through 50. Line i (1-based) should contain the classification result for the image {i + 20}.png. 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. Vus the Cossack holds a programming competition, in which $n$ people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly $m$ pens and $k$ notebooks. Determine whether the Cossack can reward all participants, giving each of them at least one pen and at least one notebook. -----Input----- The first line contains three integers $n$, $m$, and $k$ ($1 \leq n, m, k \leq 100$) — the number of participants, the number of pens, and the number of notebooks respectively. -----Output----- Print "Yes" if it possible to reward all the participants. Otherwise, print "No". You can print each letter in any case (upper or lower). -----Examples----- Input 5 8 6 Output Yes Input 3 9 3 Output Yes Input 8 5 20 Output No -----Note----- In the first example, there are $5$ participants. The Cossack has $8$ pens and $6$ notebooks. Therefore, he has enough pens and notebooks. In the second example, there are $3$ participants. The Cossack has $9$ pens and $3$ notebooks. He has more than enough pens but only the minimum needed number of notebooks. In the third example, there are $8$ participants but only $5$ pens. Since the Cossack does not have enough pens, 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. A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring. You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes). A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string. The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap. String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ. Input The first line contains integer n (1 ≤ n ≤ 105) — the number of strings in the set. Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct. The total length of the strings doesn't exceed 105. Output Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print "NO" (without quotes) if there are no good strings. Examples Input 4 mail ai lru cf Output cfmailru Input 3 kek preceq cheburek Output NO Note One can show that in the first sample only two good strings with minimum length exist: "cfmailru" and "mailrucf". The first string is lexicographically minimum. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function which outputs the positions of matching bracket pairs. The output should be a dictionary with keys the positions of the open brackets '(' and values the corresponding positions of the closing brackets ')'. For example: input = "(first)and(second)" should return {0:6, 10:17} If brackets cannot be paired or if the order is invalid (e.g. ')(') return False. In this kata we care only about the positions of round brackets '()', other types of brackets should be ignored. Write your solution by modifying this code: ```python def bracket_pairs(string): ``` Your solution should implemented in the function "bracket_pairs". The i 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. Addition of Big Integers Given two integers $A$ and $B$, compute the sum, $A + B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the sum in a line. Constraints * $-1 \times 10^{100000} \leq A, B \leq 10^{100000}$ Sample Input 1 5 8 Sample Output 1 13 Sample Input 2 100 25 Sample Output 2 125 Sample Input 3 -1 1 Sample Output 3 0 Sample Input 4 12 -3 Sample Output 4 9 Example Input 5 8 Output 13 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. Diamond Miner is a game that is similar to Gold Miner, but there are $n$ miners instead of $1$ in this game. The mining area can be described as a plane. The $n$ miners can be regarded as $n$ points on the y-axis. There are $n$ diamond mines in the mining area. We can regard them as $n$ points on the x-axis. For some reason, no miners or diamond mines can be at the origin (point $(0, 0)$). Every miner should mine exactly one diamond mine. Every miner has a hook, which can be used to mine a diamond mine. If a miner at the point $(a,b)$ uses his hook to mine a diamond mine at the point $(c,d)$, he will spend $\sqrt{(a-c)^2+(b-d)^2}$ energy to mine it (the distance between these points). The miners can't move or help each other. The object of this game is to minimize the sum of the energy that miners spend. Can you find this minimum? -----Input----- The input consists of multiple test cases. The first line contains a single integer $t$ ($1\le t\le 10$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) — the number of miners and mines. Each of the next $2n$ lines contains two space-separated integers $x$ ($-10^8 \le x \le 10^8$) and $y$ ($-10^8 \le y \le 10^8$), which represent the point $(x,y)$ to describe a miner's or a diamond mine's position. Either $x = 0$, meaning there is a miner at the point $(0, y)$, or $y = 0$, meaning there is a diamond mine at the point $(x, 0)$. There can be multiple miners or diamond mines at the same point. It is guaranteed that no point is at the origin. It is guaranteed that the number of points on the x-axis is equal to $n$ and the number of points on the y-axis is equal to $n$. It's guaranteed that the sum of $n$ for all test cases does not exceed $10^5$. -----Output----- For each test case, print a single real number — the minimal sum of energy that should be spent. Your answer is considered correct if its absolute or relative error does not exceed $10^{-9}$. Formally, let your answer be $a$, and the jury's answer be $b$. Your answer is accepted if and only if $\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-9}$. -----Examples----- Input 3 2 0 1 1 0 0 -1 -2 0 4 1 0 3 0 -5 0 6 0 0 3 0 1 0 2 0 4 5 3 0 0 4 0 -3 4 0 2 0 1 0 -3 0 0 -10 0 -2 0 -10 Output 3.650281539872885 18.061819283610362 32.052255376143336 -----Note----- In the first test case, the miners are at $(0,1)$ and $(0,-1)$, while the diamond mines are at $(1,0)$ and $(-2,0)$. If you arrange the miners to get the diamond mines in the way, shown in the picture, you can get the sum of the energy $\sqrt2 + \sqrt5$. 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. Kate has a set $S$ of $n$ integers $\{1, \dots, n\} $. She thinks that imperfection of a subset $M \subseteq S$ is equal to the maximum of $gcd(a, b)$ over all pairs $(a, b)$ such that both $a$ and $b$ are in $M$ and $a \neq b$. Kate is a very neat girl and for each $k \in \{2, \dots, n\}$ she wants to find a subset that has the smallest imperfection among all subsets in $S$ of size $k$. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size $k$, will name it $I_k$. Please, help Kate to find $I_2$, $I_3$, ..., $I_n$. -----Input----- The first and only line in the input consists of only one integer $n$ ($2\le n \le 5 \cdot 10^5$)  — the size of the given set $S$. -----Output----- Output contains only one line that includes $n - 1$ integers: $I_2$, $I_3$, ..., $I_n$. -----Examples----- Input 2 Output 1 Input 3 Output 1 1 -----Note----- First sample: answer is 1, because $gcd(1, 2) = 1$. Second sample: there are subsets of $S$ with sizes $2, 3$ with imperfection equal to 1. For example, $\{2,3\}$ and $\{1, 2, 3\}$. 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 string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not. You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically. -----Input----- The only line contains string s (1 ≤ |s| ≤ 2·10^5) consisting of only lowercase Latin letters. -----Output----- Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes. -----Examples----- Input aabc Output abba Input aabcd Output abcba 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 might have heard about our new goodie distribution program aka the "Laddu Accrual System". This problem is designed to give you a glimpse of its rules. You can read the page once before attempting the problem if you wish, nonetheless we will be providing all the information needed here itself. Laddu Accrual System is our new goodie distribution program. In this program, we will be distributing Laddus in place of goodies for your winnings and various other activities (described below), that you perform on our system. Once you collect enough number of Laddus, you can then redeem them to get yourself anything from a wide range of CodeChef goodies. Let us know about various activities and amount of laddus you get corresponding to them. - Contest Win (CodeChef’s Long, Cook-Off, LTIME, or any contest hosted with us) : 300 + Bonus (Bonus = 20 - contest rank). Note that if your rank is > 20, then you won't get any bonus. - Top Contributor on Discuss : 300 - Bug Finder : 50 - 1000 (depending on the bug severity). It may also fetch you a CodeChef internship! - Contest Hosting : 50 You can do a checkout for redeeming laddus once a month. The minimum laddus redeemable at Check Out are 200 for Indians and 400 for the rest of the world. You are given history of various activities of a user. The user has not redeemed any of the its laddus accrued.. Now the user just wants to redeem as less amount of laddus he/she can, so that the laddus can last for as long as possible. Find out for how many maximum number of months he can redeem the laddus. -----Input----- - The first line of input contains a single integer T denoting number of test cases - For each test case: - First line contains an integer followed by a string denoting activities, origin respectively, where activities denotes number of activities of the user, origin denotes whether the user is Indian or the rest of the world. origin can be "INDIAN" or "NON_INDIAN". - For each of the next activities lines, each line contains an activity. An activity can be of four types as defined above. - Contest Win : Input will be of form of CONTEST_WON rank, where rank denotes the rank of the user. - Top Contributor : Input will be of form of TOP_CONTRIBUTOR. - Bug Finder : Input will be of form of BUG_FOUND severity, where severity denotes the severity of the bug. - Contest Hosting : Input will be of form of CONTEST_HOSTED. -----Output----- - For each test case, find out the maximum number of months for which the user can redeem the laddus accrued. -----Constraints----- - 1 ≤ T, activities ≤ 100 - 1 ≤ rank ≤ 5000 - 50 ≤ severity ≤ 1000 -----Subtasks----- There is only a single subtask with 100 points. -----Example----- Input: 2 4 INDIAN CONTEST_WON 1 TOP_CONTRIBUTOR BUG_FOUND 100 CONTEST_HOSTED 4 NON_INDIAN CONTEST_WON 1 TOP_CONTRIBUTOR BUG_FOUND 100 CONTEST_HOSTED Output: 3 1 -----Explanation----- In the first example, - For winning contest with rank 1, user gets 300 + 20 - 1 = 319 laddus. - For top contributor, user gets 300 laddus. - For finding a bug with severity of 100, user gets 100 laddus. - For hosting a contest, user gets 50 laddus. So, overall user gets 319 + 300 + 100 + 50 = 769 laddus. Now, the user is an Indian user, he can redeem only 200 laddus per month. So, for first three months, he will redeem 200 * 3 = 600 laddus. The remaining 169 laddus, he can not redeem as he requires at least 200 laddues in a month to redeem. So, answer is 3. In the second example, user is a non-Indian user, he can redeem 400 laddues per month. So, in the first month, he will redeem 400 laddus. The remaining 369 laddus, he can not redeem as he requires at least 400 laddues in a month to redeem. So, answer is 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 only difference between easy and hard versions are constraints on $n$ and $k$. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $0$). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive $n$ messages, the $i$-th message will be received from the friend with ID $id_i$ ($1 \le id_i \le 10^9$). If you receive a message from $id_i$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with $id_i$ on the screen): Firstly, if the number of conversations displayed on the screen is $k$, the last conversation (which has the position $k$) is removed from the screen. Now the number of conversations on the screen is guaranteed to be less than $k$ and the conversation with the friend $id_i$ is not displayed on the screen. The conversation with the friend $id_i$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $n$ messages. -----Input----- The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 200)$ — the number of messages and the number of conversations your smartphone can show. The second line of the input contains $n$ integers $id_1, id_2, \dots, id_n$ ($1 \le id_i \le 10^9$), where $id_i$ is the ID of the friend which sends you the $i$-th message. -----Output----- In the first line of the output print one integer $m$ ($1 \le m \le min(n, k)$) — the number of conversations shown after receiving all $n$ messages. In the second line print $m$ integers $ids_1, ids_2, \dots, ids_m$, where $ids_i$ should be equal to the ID of the friend corresponding to the conversation displayed on the position $i$ after receiving all $n$ messages. -----Examples----- Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 -----Note----- In the first example the list of conversations will change in the following way (in order from the first to last message): $[]$; $[1]$; $[2, 1]$; $[3, 2]$; $[3, 2]$; $[1, 3]$; $[1, 3]$; $[2, 1]$. In the second example the list of conversations will change in the following way: $[]$; $[2]$; $[3, 2]$; $[3, 2]$; $[1, 3, 2]$; and then the list will not change till the end. 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. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. 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 sequence $a_1, a_2, \dots, a_n$ consisting of $n$ integers. You may perform the following operation on this sequence: choose any element and either increase or decrease it by one. Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than $k$ times. -----Input----- The first line contains two integers $n$ and $k$ $(2 \le n \le 10^{5}, 1 \le k \le 10^{14})$ — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^{9})$. -----Output----- Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than $k$ times. -----Examples----- Input 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 -----Note----- In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes $[3, 3, 5, 5]$, and the difference between maximum and minimum is $2$. You still can perform one operation after that, but it's useless since you can't make the answer less than $2$. In the second example all elements are already equal, so you may get $0$ as the answer even without applying any operations. 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 is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully. A string is a bHTML table, if it satisfies the grammar: TABLE ::= <table>ROWS</table> ROWS ::= ROW | ROW ROWS ROW ::= <tr>CELLS</tr> CELLS ::= CELL | CELL CELLS CELL ::= <td></td> | <td>TABLE</td> Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : "table", "tr", "td", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables. As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular. Input For convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation s of the specified table. String s corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string s. Output Print the sizes of all the tables in the non-decreasing order. Examples Input &lt;table&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; Output 1 Input &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;table&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;/ td &gt;&lt;/tr&gt;&lt;tr &gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; Output 1 4 Input &lt;table&gt;&lt;tr&gt;&lt;td&gt; &lt;table&gt;&lt;tr&gt;&lt;td&gt; &lt;table&gt;&lt;tr&gt;&lt;td&gt; &lt;table&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; Output 1 1 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. In this simple exercise, you will build a program that takes a value, `integer `, and returns a list of its multiples up to another value, `limit `. If `limit` is a multiple of ```integer```, it should be included as well. There will only ever be positive integers passed into the function, not consisting of 0. The limit will always be higher than the base. For example, if the parameters passed are `(2, 6)`, the function should return `[2, 4, 6]` as 2, 4, and 6 are the multiples of 2 up to 6. If you can, try writing it in only one line of code. Write your solution by modifying this code: ```python def find_multiples(integer, limit): ``` Your solution should implemented in the function "find_multiples". The i 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 day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same. Input The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found. Output Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1. Examples Input 3 2 3 1 1 Output 1 Input 3 1 3 1 1 Output -1 Note In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one. In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1. 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. Mr. A, who will graduate next spring, decided to move when he got a job. The company that finds a job has offices in several towns, and the offices that go to work differ depending on the day. So Mr. A decided to live in a town where he had a short time to go to any office. So you decided to find the most convenient town to live in to help Mr. A. <image> Towns are numbered starting with 0 and there is a road between towns. Commuting time is fixed for each road. If Mr. A lives in a town, the commuting time to the office in his town is 0. At this time, consider the total commuting time to all towns. For example, if the layout of towns and roads is as shown in the figure above and Mr. A lives in town 1, the commuting time to each town will be Town 0 to 80 0 to town 1 Up to town 2 20 Up to town 3 70 Town 4 to 90 And the sum is 260. Enter the number of roads and information on all roads, calculate the total commuting time when living in each town, and output the number of the town that minimizes it and the total commuting time at that time. Create a program. However, if there are multiple towns with the smallest total commuting time, please output the number of the smallest town and the total commuting time at that time. The total number of towns is 10 or less, the total number of roads is 45 or less, all roads can move in both directions, and commuting time does not change depending on the direction. We also assume that there are routes from any town to all other towns. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: n a1 b1 c1 a2 b2 c2 :: an bn cn The number of roads n (1 ≤ n ≤ 45) is given on the first line. The following n lines give information on the i-th way. ai, bi (0 ≤ ai, bi ≤ 9) is the number of the town to which the i-th road connects, and ci (0 ≤ ci ≤ 100) is the commute time for that road. Output For each data set, the town number that minimizes the total commuting time and the total commuting time at that time are output on one line separated by blanks. Example Input 6 0 1 80 1 2 20 0 2 60 2 3 50 3 4 60 1 4 90 2 0 1 1 1 2 1 0 Output 2 240 1 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. B: Dansunau www --Dance Now!- story Last lab life! Daigakuin! !! Dosanko Snow has won 9th place in the event "Master Idol World", which can be said to be the outpost of the biggest competition "Lab Life" where master idols compete. The sharp dance is ridiculed as "9th place dance", and the whole body's deciding pose is also ridiculed as "9th place stance", which causes deep emotional wounds. In the upcoming Lab Life Preliminary Qualifying, we can never take 9th place ... Dosanko Snow, who renewed his determination, refined his special skill "self-control" and headed for the battlefield. .. problem A tournament "Lab Life" will be held in which N groups of units compete. In this tournament, the three divisions of Smile Pure Cool will be played separately, and the overall ranking will be decided in descending order of the total points scored in each game. The ranking of the smile category is determined in descending order of the smile value of each unit. Similarly, in the pure / cool category, the ranking is determined in descending order of pure / cool value. The score setting according to the ranking is common to all divisions, and the unit ranked i in a division gets r_i points in that division. Here, if there are a plurality of units having the same value as the unit with the rank i, they are regarded as the same rate i rank, and the points r_i are equally obtained. More specifically, when k units are in the same ratio i position, k units get equal points r_i, and no unit gets points from r_ {i + 1} to r_ {i + k-1}. Also, the next largest unit (s) gets the score r_ {i + k}. As a specific example, consider a case where there are five units with smile values ​​of 1, 3, 2, 3, and 2, and 10, 8, 6, 4, and 2 points are obtained in descending order of rank. At this time, the 2nd and 4th units will get 10 points, the 3rd and 5th units will get 6 points, and the 1st unit will get 2 points. Unit Dosanko Snow, who participates in the Lab Life Preliminary Qualifying, thinks that "Lab Life is not a play", so he entered the tournament first and became the first unit. However, when we obtained information on the smile value, pure value, and cool value (hereinafter referred to as 3 values) of all N groups participating in the tournament, we found that their overall ranking was (equal rate) 9th. Dosanko Snow can raise any one of the three values ​​by the special skill "Self Control", but if you raise it too much, you will get tired and it will affect the main battle, so you want to make the rise value as small as possible. Dosanko Snow wants to get out of 9th place anyway, so when you raise any one of the 3 values ​​by self-control so that it will be 8th or higher at the same rate, find the minimum value that needs to be raised. Input format The input is given in the following format. N r_1 ... r_N s_1 p_1 c_1 ... s_N p_N c_N The first line is given the integer N, which represents the number of units, in one line. The second line that follows is given N integers separated by blanks. The i (1 \ leq i \ leq N) th integer represents the score r_i that can be obtained when the ranking is i in each division. Of the following Nth line, the jth line is given three integers s_j, p_j, c_j. These represent the smile value s_j, pure value p_j, and cool value c_j of the jth unit, respectively. Dosanko Snow is the first unit. Constraint * 9 \ leq N \ leq 100 * 100 \ geq r_1> ...> r_N \ geq 1 * 1 \ leq s_j, p_j, c_j \ leq 100 (1 \ leq j \ leq N) * Before self-control, Dosanko Snow was 9th (sometimes 9th, but never more than 8th) Output format By increasing any of the three values ​​by x by self-control, output the minimum x that makes Dosanko Snow 8th or higher at the same rate on one line. However, if self-control does not raise the ranking no matter how much you raise it, output "Saiko". Input example 1 9 9 8 7 6 5 4 3 2 1 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 Output example 1 2 For example, if you raise the smile value by 2 by self-control, the rankings in each division of Dosanko Snow will be 7th, 9th, and 9th, respectively, and you will get 3 + 1 + 1 = 5 points. On the other hand, the ranking of the second unit in each division is 9th, 8th, and 8th, respectively, and 1 + 2 + 2 = 5 points are obtained. Since the other units get 6 points or more, these two units will be ranked 8th at the same rate, satisfying the conditions. Input example 2 9 9 8 7 6 5 4 3 2 1 1 1 1 2 6 9 6 9 2 9 2 6 3 5 8 5 8 3 8 3 5 4 7 4 7 4 7 Output example 2 Saiko No matter how much you raise the value, Dosanko Snow can only get up to 11 points, but other units can always get 14 points or more, so Dosanko Snow is immovable in 9th place. Example Input 9 9 8 7 6 5 4 3 2 1 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. problem Five students, Taro, Jiro, Saburo, Shiro, and Hanako, participated in the JOI High School class. In this class, a final exam was conducted. All five people took the final exam. For students with a final exam score of 40 or higher, the final exam score was used as is. All students with a final exam score of less than 40 received supplementary lessons and scored 40 points. Create a program that calculates the average score of the five students' grades given the final exam scores of the five students. Example Input 10 65 100 30 95 Output 68 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 which computes the greatest common divisor (GCD) and the least common multiple (LCM) of given a and b. Constraints * 0 < a, b ≤ 2,000,000,000 * LCM(a, b) ≤ 2,000,000,000 * The number of data sets ≤ 50 Input Input consists of several data sets. Each data set contains a and b separated by a single space in a line. The input terminates with EOF. Output For each data set, print GCD and LCM separated by a single space in a line. Example Input 8 6 50000000 30000000 Output 2 24 10000000 150000000 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. Takahashi has a lot of peculiar devices. These cylindrical devices receive balls from left and right. Each device is in one of the two states A and B, and for each state, the device operates as follows: * When a device in state A receives a ball from either side (left or right), the device throws out the ball from the same side, then immediately goes into state B. * When a device in state B receives a ball from either side, the device throws out the ball from the other side, then immediately goes into state A. The transition of the state of a device happens momentarily and always completes before it receives another ball. Takahashi built a contraption by concatenating N of these devices. In this contraption, * A ball that was thrown out from the right side of the i-th device from the left (1 \leq i \leq N-1) immediately enters the (i+1)-th device from the left side. * A ball that was thrown out from the left side of the i-th device from the left (2 \leq i \leq N) immediately enters the (i-1)-th device from the right side. The initial state of the i-th device from the left is represented by the i-th character in a string S. From this situation, Takahashi performed the following K times: put a ball into the leftmost device from the left side, then wait until the ball comes out of the contraption from either end. Here, it can be proved that the ball always comes out of the contraption after a finite time. Find the state of each device after K balls are processed. Constraints * 1 \leq N \leq 200,000 * 1 \leq K \leq 10^9 * |S|=N * Each character in S is either `A` or `B`. Input The input is given from Standard Input in the following format: N K S Output Print a string that represents the state of each device after K balls are processed. The string must be N characters long, and the i-th character must correspond to the state of the i-th device from the left. Examples Input 5 1 ABAAA Output BBAAA Input 5 2 ABAAA Output ABBBA Input 4 123456789 AABB Output BABA Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. Current character pointer (CP); Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right. We repeat the following steps until the first moment that CP points to somewhere outside the sequence. If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one. If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated. It's obvious the every program in this language terminates after some steps. We have a sequence s_1, s_2, ..., s_{n} of "<", ">" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence s_{l}, s_{l} + 1, ..., s_{r} as an independent program in this language. -----Input----- The first line of input contains two integers n and q (1 ≤ n, q ≤ 100) — represents the length of the sequence s and the number of queries. The second line contains s, a sequence of "<", ">" and digits (0..9) written from left to right. Note, that the characters of s are not separated with spaces. The next q lines each contains two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) — the i-th query. -----Output----- For each query print 10 space separated integers: x_0, x_1, ..., x_9 where x_{i} equals the number of times the interpreter prints i while running the corresponding program. Print answers to the queries in the order they are given in input. -----Examples----- Input 7 4 1>3>22< 1 3 4 7 7 7 1 7 Output 0 1 0 1 0 0 0 0 0 0 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3 2 1 0 0 0 0 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. See the following triangle: ``` ____________________________________ 1 2 4 2 3 6 9 6 3 4 8 12 16 12 8 4 5 10 15 20 25 20 15 10 5 ___________________________________ ``` The total sum of the numbers in the triangle, up to the 5th line included, is ```225```, part of it, ```144```, corresponds to the total sum of the even terms and ```81``` to the total sum of the odd terms. Create a function that may output an array with three results for each value of n. ```python triang_mult(n) ----> [total_sum, total_even_sum, total_odd_sum] ``` Our example will be: ```python triang_mult(5) ----> [225, 144, 81] ``` Features of the random tests: ``` number of tests = 100 49 < n < 5000 ``` Enjoy it! This kata will be translated in another languages soon Write your solution by modifying this code: ```python def mult_triangle(n): ``` Your solution should implemented in the function "mult_triangle". The i 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. Step through my `green glass door`. You can take the `moon`, but not the `sun`. You can take your `slippers`, but not your `sandals`. You can go through `yelling`, but not `shouting`. You can't run through `fast`, but you can run with `speed`. You can take a `sheet`, but not your `blanket`. You can wear your `glasses`, but not your `contacts`. Have you figured it out? Good! Then write a program that can figure it out as well. Write your solution by modifying this code: ```python def step_through_with(s): ``` Your solution should implemented in the function "step_through_with". The i 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. 10^{10^{10}} participants, including Takahashi, competed in two programming contests. In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th. The score of a participant is the product of his/her ranks in the two contests. Process the following Q queries: - In the i-th query, you are given two positive integers A_i and B_i. Assuming that Takahashi was ranked A_i-th in the first contest and B_i-th in the second contest, find the maximum possible number of participants whose scores are smaller than Takahashi's. -----Constraints----- - 1 \leq Q \leq 100 - 1\leq A_i,B_i\leq 10^9(1\leq i\leq Q) - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: Q A_1 B_1 : A_Q B_Q -----Output----- For each query, print the maximum possible number of participants whose scores are smaller than Takahashi's. -----Sample Input----- 8 1 4 10 5 3 3 4 11 8 9 22 40 8 36 314159265 358979323 -----Sample Output----- 1 12 4 11 14 57 31 671644785 Let us denote a participant who was ranked x-th in the first contest and y-th in the second contest as (x,y). In the first query, (2,1) is a possible candidate of a participant whose score is smaller than Takahashi's. There are never two or more participants whose scores are smaller than Takahashi's, so we should print 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. After you had helped Fedor to find friends in the «Call of Soldiers 3» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all. Now Fedor is going to change the essay using the synonym dictionary of the English language. Fedor does not want to change the meaning of the essay. So the only change he would do: change a word from essay to one of its synonyms, basing on a replacement rule from the dictionary. Fedor may perform this operation any number of times. As a result, Fedor wants to get an essay which contains as little letters «R» (the case doesn't matter) as possible. If there are multiple essays with minimum number of «R»s he wants to get the one with minimum length (length of essay is the sum of the lengths of all the words in it). Help Fedor get the required essay. Please note that in this problem the case of letters doesn't matter. For example, if the synonym dictionary says that word cat can be replaced with word DOG, then it is allowed to replace the word Cat with the word doG. -----Input----- The first line contains a single integer m (1 ≤ m ≤ 10^5) — the number of words in the initial essay. The second line contains words of the essay. The words are separated by a single space. It is guaranteed that the total length of the words won't exceed 10^5 characters. The next line contains a single integer n (0 ≤ n ≤ 10^5) — the number of pairs of words in synonym dictionary. The i-th of the next n lines contains two space-separated non-empty words x_{i} and y_{i}. They mean that word x_{i} can be replaced with word y_{i} (but not vise versa). It is guaranteed that the total length of all pairs of synonyms doesn't exceed 5·10^5 characters. All the words at input can only consist of uppercase and lowercase letters of the English alphabet. -----Output----- Print two integers — the minimum number of letters «R» in an optimal essay and the minimum length of an optimal essay. -----Examples----- Input 3 AbRb r Zz 4 xR abRb aA xr zz Z xr y Output 2 6 Input 2 RuruRu fedya 1 ruruRU fedor Output 1 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. Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen. One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get? The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of n marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least n marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want. Input The single line contains a single integer n (1 ≤ n ≤ 1017). Please, do not use the %lld specifier to read or write 64 bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Output In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with. Examples Input 1 Output 1 Input 4 Output 2 Note In the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change. In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives. 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 of us are going on a trip, by train or taxi. The train will cost each of us A yen (the currency of Japan). The taxi will cost us a total of B yen. How much is our minimum total travel expense? -----Constraints----- - All values in input are integers. - 1 \leq N \leq 20 - 1 \leq A \leq 50 - 1 \leq B \leq 50 -----Input----- Input is given from Standard Input in the following format: N A B -----Output----- Print an integer representing the minimum total travel expense. -----Sample Input----- 4 2 9 -----Sample Output----- 8 The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen. 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. Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is c_{i}. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya. Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k. Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins. -----Input----- The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of coins and the price of the chocolate, respectively. Next line will contain n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 500) — the values of Pari's coins. It's guaranteed that one can make value k using these coins. -----Output----- First line of the output must contain a single integer q— the number of suitable values x. Then print q integers in ascending order — the values that Arya can make for some subset of coins of Pari that pays for the chocolate. -----Examples----- Input 6 18 5 6 1 10 12 2 Output 16 0 1 2 3 5 6 7 8 10 11 12 13 15 16 17 18 Input 3 50 25 25 50 Output 3 0 25 50 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No". Constraints * 0 ≤ a, b, c ≤ 100 Input Three integers a, b and c separated by a single space are given in a line. Output Print "Yes" or "No" in a line. Examples Input 1 3 8 Output Yes Input 3 8 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. A population of bears consists of black bears, brown bears, and white bears. The input is an array of two elements. Determine whether the offspring of the two bears will return `'black'`, `'brown'`, `'white'`, `'dark brown'`, `'grey'`, `'light brown'`, or `'unknown'`. Elements in the the array will always be a string. ## Examples: bear_fur(['black', 'black']) returns 'black' bear_fur(['brown', 'brown']) returns 'brown' bear_fur(['white', 'white']) returns 'white' bear_fur(['black', 'brown']) returns 'dark brown' bear_fur(['black', 'white']) returns 'grey' bear_fur(['brown', 'white']) returns 'light brown' bear_fur(['yellow', 'magenta']) returns 'unknown' Write your solution by modifying this code: ```python def bear_fur(bears): ``` Your solution should implemented in the function "bear_fur". The i 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. Clock shows 'h' hours, 'm' minutes and 's' seconds after midnight. Your task is to make 'Past' function which returns time converted to milliseconds. ## Example: ```python past(0, 1, 1) == 61000 ``` Input constraints: `0 <= h <= 23`, `0 <= m <= 59`, `0 <= s <= 59` Write your solution by modifying this code: ```python def past(h, m, s): ``` Your solution should implemented in the function "past". The i 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 of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation. Input The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold. * In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold. * In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold. Output Output the answer with absolute or relative error no more than 1e - 9. Examples Input 3 1 1 2 3 Output 0.833333333333333 Input 3 4 1 3 2 Output 1.458333333333334 Note Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <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. Dante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots. For every bullet that hits the shield, Ebony deals a units of damage while Ivory deals b units of damage. In order to break the shield Dante has to deal exactly c units of damage. Find out if this is possible. -----Input----- The first line of the input contains three integers a, b, c (1 ≤ a, b ≤ 100, 1 ≤ c ≤ 10 000) — the number of units of damage dealt by Ebony gun and Ivory gun, and the total number of damage required to break the shield, respectively. -----Output----- Print "Yes" (without quotes) if Dante can deal exactly c damage to the shield and "No" (without quotes) otherwise. -----Examples----- Input 4 6 15 Output No Input 3 2 7 Output Yes Input 6 11 6 Output Yes -----Note----- In the second sample, Dante can fire 1 bullet from Ebony and 2 from Ivory to deal exactly 1·3 + 2·2 = 7 damage. In the third sample, Dante can fire 1 bullet from ebony and no bullets from ivory to do 1·6 + 0·11 = 6 damage. 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. Arithmetic Progressions An arithmetic progression is a sequence of numbers $a_1, a_2, ..., a_k$ where the difference of consecutive members $a_{i+1} - a_i$ is a constant ($1 \leq i \leq k-1$). For example, the sequence 5, 8, 11, 14, 17 is an arithmetic progression of length 5 with the common difference 3. In this problem, you are requested to find the longest arithmetic progression which can be formed selecting some numbers from a given set of numbers. For example, if the given set of numbers is {0, 1, 3, 5, 6, 9}, you can form arithmetic progressions such as 0, 3, 6, 9 with the common difference 3, or 9, 5, 1 with the common difference -4. In this case, the progressions 0, 3, 6, 9 and 9, 6, 3, 0 are the longest. Input The input consists of a single test case of the following format. $n$ $v_1$ $v_2$ ... $v_n$ $n$ is the number of elements of the set, which is an integer satisfying $2 \leq n \leq 5000$. Each $v_i$ ($1 \leq i \leq n$) is an element of the set, which is an integer satisfying $0 \leq v_i \leq 10^9$. $v_i$'s are all different, i.e., $v_i \ne v_j$ if $i \ne j$. Output Output the length of the longest arithmetic progressions which can be formed selecting some numbers from the given set of numbers. Sample Input 1 6 0 1 3 5 6 9 Sample Output 1 4 Sample Input 2 7 1 4 7 3 2 6 5 Sample Output 2 7 Sample Input 3 5 1 2 4 8 16 Sample Output 3 2 Example Input 6 0 1 3 5 6 9 Output 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. A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers. You will be given three integers A, B, and C. If this triple is poor, print Yes; otherwise, print No. -----Constraints----- - A, B, and C are all integers between 1 and 9 (inclusive). -----Input----- Input is given from Standard Input in the following format: A B C -----Output----- If the given triple is poor, print Yes; otherwise, print No. -----Sample Input----- 5 7 5 -----Sample Output----- Yes A and C are equal, but B is different from those two numbers, so this triple is poor. 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 playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree. You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled x_1, x_2, …, x_{k_1} in your labeling, Li Chen's subtree consists of the vertices labeled y_1, y_2, …, y_{k_2} in his labeling. The values of x_1, x_2, …, x_{k_1} and y_1, y_2, …, y_{k_2} are known to both of you. <image> The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes. You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most 5 questions, each of which is in one of the following two forms: * A x: Andrew will look at vertex x in your labeling and tell you the number of this vertex in Li Chen's labeling. * B y: Andrew will look at vertex y in Li Chen's labeling and tell you the number of this vertex in your labeling. Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices. Interaction Each test consists of several test cases. The first line of input contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. For each testcase, your program should interact in the following format. The first line contains a single integer n (1 ≤ n ≤ 1 000) — the number of nodes in the tree. Each of the next n-1 lines contains two integers a_i and b_i (1≤ a_i, b_i≤ n) — the edges of the tree, indicating an edge between node a_i and b_i according to your labeling of the nodes. The next line contains a single integer k_1 (1 ≤ k_1 ≤ n) — the number of nodes in your subtree. The next line contains k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≤ x_i ≤ n) — the indices of the nodes in your subtree, according to your labeling. It is guaranteed that these vertices form a subtree. The next line contains a single integer k_2 (1 ≤ k_2 ≤ n) — the number of nodes in Li Chen's subtree. The next line contains k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≤ y_i ≤ n) — the indices (according to Li Chen's labeling) of the nodes in Li Chen's subtree. It is guaranteed that these vertices form a subtree according to Li Chen's labelling of the tree's nodes. Test cases will be provided one by one, so you must complete interacting with the previous test (i.e. by printing out a common node or -1 if there is not such node) to start receiving the next one. You can ask the Andrew two different types of questions. * You can print "A x" (1 ≤ x ≤ n). Andrew will look at vertex x in your labeling and respond to you with the number of this vertex in Li Chen's labeling. * You can print "B y" (1 ≤ y ≤ n). Andrew will look at vertex y in Li Chen's labeling and respond to you with the number of this vertex in your labeling. You may only ask at most 5 questions per tree. When you are ready to answer, print "C s", where s is your label of a vertex that is common to both subtrees, or -1, if no such vertex exists. Printing the answer does not count as a question. Remember to flush your answer to start receiving the next test case. After printing a question do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. If the judge responds with -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream. Hack Format To hack, use the following format. Note that you can only hack with one test case. The first line should contain a single integer t (t=1). The second line should contain a single integer n (1 ≤ n ≤ 1 000). The third line should contain n integers p_1, p_2, …, p_n (1≤ p_i≤ n) — a permutation of 1 to n. This encodes the labels that Li Chen chose for his tree. In particular, Li Chen chose label p_i for the node you labeled i. Each of the next n-1 lines should contain two integers a_i and b_i (1≤ a_i, b_i≤ n). These edges should form a tree. The next line should contain a single integer k_1 (1 ≤ k_1 ≤ n). The next line should contain k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≤ x_i ≤ n). These vertices should form a subtree. The next line should contain a single integer k_2 (1 ≤ k_2 ≤ n). The next line should contain k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≤ y_i ≤ n). These vertices should form a subtree in Li Chen's tree according to the permutation above. Examples Input 1 3 1 2 2 3 1 1 1 2 2 1 Output A 1 B 2 C 1 Input 2 6 1 2 1 3 1 4 4 5 4 6 4 1 3 4 5 3 3 5 2 3 6 1 2 1 3 1 4 4 5 4 6 3 1 2 3 3 4 1 6 5 Output B 2 C 1 A 1 C -1 Note For the first sample, Li Chen's hidden permutation is [2, 3, 1], and for the second, his hidden permutation is [5, 3, 2, 4, 1, 6] for both cases. In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose: <image> In the first question, you ask Andrew to look at node 1 in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with 2. At this point, you know that both of your subtrees contain the same node (i.e. node 1 according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node 2 in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with 1 (this step was given with the only reason — to show you how to ask questions). For the second sample, there are two test cases. The first looks is the one from the statement: <image> We first ask "B 2", and Andrew will tell us 3. In this case, we know 3 is a common vertex, and moreover, any subtree with size 3 that contains node 3 must contain node 1 as well, so we can output either "C 1" or "C 3" as our answer. In the second case in the second sample, the situation looks as follows: <image> In this case, you know that the only subtree of size 3 that doesn't contain node 1 is subtree 4,5,6. You ask Andrew for the label of node 1 in Li Chen's labelling and Andrew says 5. In this case, you know that Li Chen's subtree doesn't contain node 1, so his subtree must be consist of the nodes 4,5,6 (in your labelling), thus the two subtrees have no common nodes. 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. Ivan unexpectedly saw a present from one of his previous birthdays. It is array of $n$ numbers from $1$ to $200$. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally: $a_{1} \le a_{2}$, $a_{n} \le a_{n-1}$ and $a_{i} \le max(a_{i-1}, \,\, a_{i+1})$ for all $i$ from $2$ to $n-1$. Ivan does not remember the array and asks to find the number of ways to restore it. Restored elements also should be integers from $1$ to $200$. Since the number of ways can be big, print it modulo $998244353$. -----Input----- First line of input contains one integer $n$ ($2 \le n \le 10^{5}$) — size of the array. Second line of input contains $n$ integers $a_{i}$ — elements of array. Either $a_{i} = -1$ or $1 \le a_{i} \le 200$. $a_{i} = -1$ means that $i$-th element can't be read. -----Output----- Print number of ways to restore the array modulo $998244353$. -----Examples----- Input 3 1 -1 2 Output 1 Input 2 -1 -1 Output 200 -----Note----- In the first example, only possible value of $a_{2}$ is $2$. In the second example, $a_{1} = a_{2}$ so there are $200$ different values because all restored elements should be integers between $1$ and $200$. 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. General primality test are often computationally expensive, so in the biggest prime number race the idea is to study special sub-families of prime number and develop more effective tests for them. [Mersenne Primes](https://en.wikipedia.org/wiki/Mersenne_prime) are prime numbers of the form: Mn = 2^(n) - 1. So far, 49 of them was found between M2 (3) and M74,207,281 which contains 22,338,618 digits and is (by September 2015) the biggest known prime. It has been found by GIMPS (Great Internet Mersenne Prime Search), wich use the test srudied here. (plus heuristics mentionned below) Lucas and Lehmer have developed a [simple test](https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test) for Mersenne primes: > for `p` (an odd prime), the Mersenne number Mp is prime if and only if `S(p − 1) = 0 mod Mp`, >where `S(n + 1) = S(n) * S(n) − 2` and `S(1) = 4` The goal of this kata is to implement this test. Given an integer `>=2`, the program should calculate the sequence `S(n)` up to `p-1` and calculate the remainder modulo `Mp`, then return `True` or `False` as a result of the test. The case `n = 2` should return `True`. You should take advantage of the fact that: ```k = (k mod 2^n + floor(k/2^n)) mod Mn``` Or in other words, if we take the least significant `n` bits of `k`, and add the remaining bits of `k`, and then do this repeatedly until at most `n` bits remain, we can compute the remainder after dividing `k` by the Mersenne number `2^n−1` without using division. This test can be improved using the fact that if `n` is not prime, `2^n-1` will not be prime. So in theory you can test for the primality of `n` beforehand. But in practice the test for the primality of `n` will rapidly outgrow in difficulty the Lucas-Lehmer test. So we can only use heuristics to rule out `n` with small factors but not complete factorization algorithm. You don't need to implement such heuristics here. The rapid growth of `s^2` makes javascript reach its integer limit quickly (coherent result for `n = 13`, but not `17`). Whereas python seems to be only limited by the execution time limit and let us see that M11,213 is prime (contains 3376 digits). Write your solution by modifying this code: ```python def lucas_lehmer(n): ``` Your solution should implemented in the function "lucas_lehmer". The i 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. Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. [Image] Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is s_{i} = A + (i - 1) × B. For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero. Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence s_{l}, s_{l} + 1, ..., s_{r} can be eaten by performing m-bite no more than t times or print -1 if there is no such number r. -----Input----- The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 10^6, 1 ≤ n ≤ 10^5). Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 10^6) for i-th query. -----Output----- For each query, print its answer in a single line. -----Examples----- Input 2 1 4 1 5 3 3 3 10 7 10 2 6 4 8 Output 4 -1 8 -1 Input 1 5 2 1 5 10 2 7 4 Output 1 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Anu has created her own function $f$: $f(x, y) = (x | y) - y$ where $|$ denotes the bitwise OR operation . For example, $f(11, 6) = (11|6) - 6 = 15 - 6 = 9$. It can be proved that for any nonnegative numbers $x$ and $y$ value of $f(x, y)$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems. A value of an array $[a_1, a_2, \dots, a_n]$ is defined as $f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible? -----Input----- The first line contains a single integer $n$ ($1 \le n \le 10^5$). The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$). Elements of the array are not guaranteed to be different. -----Output----- Output $n$ integers, the reordering of the array with maximum value. If there are multiple answers, print any. -----Examples----- Input 4 4 0 11 6 Output 11 6 4 0 Input 1 13 Output 13 -----Note----- In the first testcase, value of the array $[11, 6, 4, 0]$ is $f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$. $[11, 4, 0, 6]$ is also a valid answer. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Your task is to determine the top 3 place finishes in a pole vault competition involving several different competitors. This is isn't always so simple, and it is often a source of confusion for people who don't know the actual rules. Here's what you need to know: As input, you will receive an array of objects. Each object contains the respective competitor's name (as a string) and his/her results at the various bar heights (as an array of strings): [{name: "Sergey", results: ["", "O", "XO", "O", "XXO", "XXX", "", ""]}{name: "Jan", results: ["", "", "", "O", "O", "XO", "XXO", "XXX"]}{name: "Bruce", results: ["", "XO", "XXO", "XXX", "", "", "", ""]}{name: "HerrWert", results: ["XXX", "", "", "", "", "", "", ""]}] In the array of strings described above, each string represents the vaulter's performance at a given height. The possible values are based on commonly used written notations on a pole vault scoresheet: An empty string indicates that the vaulter did not jump at this height for a variety of possible reasons ("passed" at this height, was temporarily called away to a different track and field event, was already eliminated from competition, or withdrew due to injury, for example).An upper-case X in the string represents an unsuccessful attempt at the height. (As you may know, the vaulter is eliminated from the competition after three consecutive failed attempts.)An upper-case O represents a successful attempt. If present at all, this will be the final character in the string, because it indicates that the vaulter has now successfully completed this height and is ready to move on. All vaulters will have a result string (though possibly empty) for every height involved in the competition, making it possible to match up the results of different vaulters with less confusion. Obviously, your first task is to determine who cleared the greatest height successfully. In other words, who has a "O" mark at a higher array element than any other competitor? You might want to work through the arrays from right to left to determine this. In the most straightforward case, you would first determine the winner, then second place, and finally third place by this simple logic. But what if there's a tie for one of these finishing places? Proceed as follows (according to American high school rules, at least): First trace backwards to find the greatest height that both vaulters cleared successfully. Then determine who had the fewest unsuccessful attempts at this height (i.e., the fewest X's in the string for this height). This person wins the tie-break.But what if they're still tied with one another? Do NOT continue to trace backwards through the heights! Instead, compare their total numbers of unsuccessful attempts at all heights in the competition. The vaulter with the fewest total misses wins the tie-break.But what if they're still tied? It depends on the finishing place:If it's for second or third place, the tie stands (i.e., is not broken).But if it's for first place, there must be a jump-off (like overtime or penalty kicks in other sports) to break the tie and determine the winner. (This jump-off occurs - hypothetically - after your code runs and is thus not a part of this kata.) Return a single object as your result. Each place-finish that is included in the results (including at least first place as property "1st" and possibly second and third places as properties "2nd" and "3rd") should have as its value the respective vaulter's name. In the event of a tie, the value of the property is the names of all tied vaulters, in alphabetical order, separated by commas, and followed by the notation "(jump-off)" if the tie is for first place or "(tie)" if it's for second or third place. Here are some possible outcomes to show you what I mean: {1st: "Jan", 2nd: "Sergey"; 3rd: "Bruce"} (These results correspond to the sample input data given above.){1st: "Julia", 2nd: "Madi, Emily (tie)}"{1st: "Caleb, Dustin (jump-off)", 3rd: "Sam"}{1st: "Meredith", 2nd: "Maddy", 3rd: "Cierra, Sara (tie)"}{1st: "Alex, Basti, Max (jump-off)"} If you are familiar with the awarding of place finishes in sporting events or team standings in a league, then you know that there won't necessarily be a 2nd or 3rd place, because ties in higher places "bump" all lower places downward accordingly. One more thing: You really shouldn't change the array of objects that you receive as input. This represents the physical scoresheet. We need this "original document" to be intact, so that we can refer back to it to resolve a disputed result! Have fun with this! - - - - - Notes for the Python version: The rules for the Python version are the same as the original JavaScript version. The input and output will look the same as the JavaScript version. But, the JavaScript objects will be replaced by Python dictionaries. The JavaScript arrays will be replaced by Python lists. The Python function name was changed to include underscores as is customary with Python names. The example below should help clarify all of this. The input for the Python version will be a list containing dictionaries with the competitors' names and results. The names in the dictionaries are strings. The results are lists with a list of strings. And example follows. score_pole_vault([ {"name": "Linda", "results": ["XXO", "O","XXO", "O"]}, {"name": "Vickie", "results": ["O","X", "", ""]}, {"name": "Debbie", "results": ["XXO", "O","XO", "XXX"]}, {"name": "Michelle", "results": ["XO","XO","XXX",""]}, {"name": "Carol", "results": ["XXX", "","",""]} ]) The returned results should be in a dictionary with one to three elements. Examples of possible returned results: {'1st': 'Linda', '2nd': 'Debbie', '3rd': 'Michelle'} {'1st': 'Green, Hayes (jump-off)', '3rd': 'Garcia'} Note: Since first place was tied in this case, there is no 2nd place awarded. {'1st': 'Wilson', '2nd': 'Laurie', '3rd': 'Joyce, Moore (tie)'} I have tried to create test cases that have every concievable tie situation. Have fun with this version, as well! Write your solution by modifying this code: ```python def score_pole_vault(vaulter_list): ``` Your solution should implemented in the function "score_pole_vault". The i 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 day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence (a_1, ..., a_N) of length N. He is interested in properties of the sequence a. For a nonempty contiguous subsequence a_l, ..., a_r (1 \leq l \leq r \leq N) of the sequence a, its beauty is defined as a_l + ... + a_r. Niwango-kun wants to know the maximum possible value of the bitwise AND of the beauties of K nonempty contiguous subsequences among all N(N+1)/2 nonempty contiguous subsequences. (Subsequences may share elements.) Find the maximum possible value for him. Constraints * 2 \leq N \leq 1000 * 1 \leq a_i \leq 10^9 * 1 \leq K \leq N(N+1)/2 * All numbers given in input are integers Input Input is given from Standard Input in the following format: N K a_1 a_2 ... a_N Output Print the answer. Examples Input 4 2 2 5 2 5 Output 12 Input 8 4 9 1 8 2 7 5 6 4 Output 32 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Zonk is addictive dice game. In each round player rolls 6 dice. Then (s)he composes combinations from them. Each combination gives certain points. Then player can take one or more dice combinations to his hand and re-roll remaining dice or save his score. Dice in player's hand won't be taken into account in subsequent rolls. If no combinations can be composed - situation is called "zonk". Player thrown zonk loses all points in this round and next player moves. So it's player decision when to reroll and when to stop and save his score. Your task is simple - just evaluate current roll and return maximum number of points can be scored from it. If no combinations can be made - function must return string ``"Zonk"`` (without quotes). There are different variations of Zonk. In this kata, we will use most common table of combinations: CombinationExample rollPoints Straight (1,2,3,4,5 and 6)6 3 1 2 5 41000 points Three pairs of any dice2 2 4 4 1 1750 points Three of 11 4 1 11000 points Three of 22 3 4 2 2200 points Three of 33 4 3 6 3 2300 points Three of 44 4 4400 points Three of 52 5 5 5 4500 points Three of 66 6 2 6600 points Four of a kind1 1 1 1 4 62 × Three-of-a-kind score (in example, 2000 pts) Five of a kind5 5 5 4 5 53 × Three-of-a-kind score (in example, 1500 pts) Six of a kind4 4 4 4 4 44 × Three-of-a-kind score (in example, 1600 pts) Every 14 3 1 2 2100 points Every 55 2 650 points Each die cannot be used in multiple combinations the same time, so three pairs of 2, 3 and 5 will worth you only ``750`` points (for three pairs), not 850 (for three pairs and two fives). But you can select multiple combinations, ``2 2 2 1 6`` will worth you ``300`` points (200 for three-of-kind '2' plus 100 for single '1' die) Examples: ```python get_score([1,2,3]) # returns 100 = points from one 1 get_score([3,4,1,1,5]) # returns 250 = points from two 1 and one 5 get_score([2,3,2,3,3,2]) # returns 500 = three of 2 + three of 3 get_score([1,1,1,1,1,5]) # returns 3050 = five 1 + one 5 get_score([2,3,4,3,6,6]) # returns "Zonk" = no combinations here get_score([2,2,6,6,2,2]) # returns 400 = four 2, this cannot be scored as three pairs get_score([1,3,4,3,4,1]) # returns 750 = three pairs get_score([3,3,3,3]) # returns 600 = four of 3 get_score([1,2,3,4,5]) # returns 150 = it's not straight ``` Of course, in real Zonk game it's sometimes not worth to collect all combination from roll. Taking less dice and rerolling more remaining may be better, but task is just to calculate maximum possible score from current single roll. P.S. Inspired by this kata: http://www.codewars.com/kata/5270d0d18625160ada0000e4 Write your solution by modifying this code: ```python def get_score(dice): ``` Your solution should implemented in the function "get_score". The i 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. King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital. The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters. The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement: [1, 2, 2, 3, 4, 4, 3, 1]; [1, 1]; [2, 2, 1, 1]; [1, 2, 3, 3, 2, 1]. Suddenly, k more requirements appeared. Each of the requirements has the form: "h[x_{i}] sign_{i} h[y_{i}]", where h[t] is the height of the t-th block, and a sign_{i} is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ 2n) and sign sign_{i}. Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met. -----Input----- The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements. Next k lines contain listed additional requirements, one per line in the format "x_{i} sign_{i} y_{i}" (1 ≤ x_{i}, y_{i} ≤ 2n), and the sign is on of the list of the five possible signs. -----Output----- Print the sought number of ways. -----Examples----- Input 3 0 Output 9 Input 3 1 2 > 3 Output 1 Input 4 1 3 = 6 Output 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Professor Matsuzaki is a scientist studying the truth of the universe. Life, the universe, all the answers are said to be 42, but Professor Matsuzaki thinks that this alone is not enough to elucidate the truth of the universe. Professor Matsuzaki believes that the truth of the universe is represented by a function consisting of two parameters, and 42 is just one of them. The function M (N, P) defined by Professor Matsuzaki selects two prime numbers larger than N (the same number can be two) and sums them, in order from the smallest number. Represents the number that appears in the Pth position when arranged. Here, there are numbers that can be represented by two or more sums, but such numbers are arranged in the same number as the number of combinations of sums. As an example, consider the case of N = 0. In this case, two are selected from all the prime numbers and summed. Considering the smallest number among such sums, it is permissible to select the same number twice, which shows that 2 + 2 = 4. That is, M (0, 1) = 4. The next smallest number is 2 + 3 = 5, so M (0, 2) = 5. Considering in the same way, it can be seen that the sums are arranged as 4, 5, 6, 7, 8, 9, 10, 10, 12, 13, 14, 14, 16, .... That is, for example, M (0, 9) = 12. Considering the case of N = 10 in the same way, in this case, two prime numbers greater than 10 {11, 13, 17, 19, ...} are selected, and the sums obtained are arranged in ascending order. And 22, 24, 26, 28, 30, 30, 32, ... Your job is to write a program that calculates M (N, P) given N and P. Input The input consists of multiple datasets. The dataset is one line, given two integers N (0 ≤ N ≤ 100,000) and P (1 ≤ P ≤ 100) separated by a single space. The end of the input is indicated by a single line containing two blank-separated -1s. Output For each dataset, output the value of M (N, P) on one line. The output must not contain extra blanks or line breaks. Sample Input 0 55 0 1 0 2 0 3 10 1 10 2 10 3 10 4 10 5 10 6 11 1 11 2 11 3 100000 100 -1 -1 Output for the Sample Input 42 Four Five 6 twenty two twenty four 26 28 30 30 26 30 32 200274 Example Input 0 55 0 1 0 2 0 3 10 1 10 2 10 3 10 4 10 5 10 6 11 1 11 2 11 3 100000 100 -1 -1 Output 42 4 5 6 22 24 26 28 30 30 26 30 32 200274 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 the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct. Initially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers: an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it. You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 200\,000$) — the number of rows in the bus. The second line contains the sequence of integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le 10^{9}$), where $w_i$ is the width of each of the seats in the $i$-th row. It is guaranteed that all $w_i$ are distinct. The third line contains a string of length $2n$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $j$-th character is '0', then the passenger that enters the bus on the $j$-th stop is an introvert. If the $j$-th character is '1', the the passenger that enters the bus on the $j$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $n$), and for each extrovert there always is a suitable row. -----Output----- Print $2n$ integers — the rows the passengers will take. The order of passengers should be the same as in input. -----Examples----- Input 2 3 1 0011 Output 2 1 1 2 Input 6 10 8 9 11 13 5 010010011101 Output 6 6 2 3 3 1 4 4 1 2 5 5 -----Note----- In the first example the first passenger (introvert) chooses the row $2$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $1$, because it is the only empty row now. The third passenger (extrovert) chooses the row $1$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $2$, because it is the only row with an empty place. 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 tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem: - We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence. Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}. -----Constraints----- - 2 \leq N \leq 2 \times 10^5 - 1 \leq a_i \leq 10^9 - 1 \leq u_i , v_i \leq N - u_i \neq v_i - The given graph is a tree. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N a_1 a_2 ... a_N u_1 v_1 u_2 v_2 : u_{N-1} v_{N-1} -----Output----- Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k. -----Sample Input----- 10 1 2 5 3 4 6 7 3 2 4 1 2 2 3 3 4 4 5 3 6 6 7 1 8 8 9 9 10 -----Sample Output----- 1 2 3 3 4 4 5 2 2 3 For example, the sequence A obtained from the shortest path from Vertex 1 to Vertex 5 is 1,2,5,3,4. Its longest increasing subsequence is A_1, A_2, A_4, A_5, with the length of 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. We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7. The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string. Input The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106. Output Print the minimum number of steps modulo 109 + 7. Examples Input ab Output 1 Input aab Output 3 Note The first example: "ab" → "bba". The second example: "aab" → "abba" → "bbaba" → "bbbbaa". 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. Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L. She will concatenate all of the strings in some order, to produce a long string. Among all strings that she can produce in this way, find the lexicographically smallest one. Here, a string s=s_1s_2s_3...s_n is lexicographically smaller than another string t=t_1t_2t_3...t_m if and only if one of the following holds: - There exists an index i(1≦i≦min(n,m)), such that s_j = t_j for all indices j(1≦j<i), and s_i<t_i. - s_i = t_i for all integers i(1≦i≦min(n,m)), and n<m. -----Constraints----- - 1 ≦ N, L ≦ 100 - For each i, the length of S_i equals L. - For each i, S_i consists of lowercase letters. -----Input----- The input is given from Standard Input in the following format: N L S_1 S_2 : S_N -----Output----- Print the lexicographically smallest string that Iroha can produce. -----Sample Input----- 3 3 dxx axx cxx -----Sample Output----- axxcxxdxx The following order should be used: axx, cxx, dxx. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Suppose there is a $h \times w$ grid consisting of empty or full cells. Let's make some definitions: $r_{i}$ is the number of consecutive full cells connected to the left side in the $i$-th row ($1 \le i \le h$). In particular, $r_i=0$ if the leftmost cell of the $i$-th row is empty. $c_{j}$ is the number of consecutive full cells connected to the top end in the $j$-th column ($1 \le j \le w$). In particular, $c_j=0$ if the topmost cell of the $j$-th column is empty. In other words, the $i$-th row starts exactly with $r_i$ full cells. Similarly, the $j$-th column starts exactly with $c_j$ full cells. [Image] These are the $r$ and $c$ values of some $3 \times 4$ grid. Black cells are full and white cells are empty. You have values of $r$ and $c$. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of $r$ and $c$. Since the answer can be very large, find the answer modulo $1000000007\,(10^{9} + 7)$. In other words, find the remainder after division of the answer by $1000000007\,(10^{9} + 7)$. -----Input----- The first line contains two integers $h$ and $w$ ($1 \le h, w \le 10^{3}$) — the height and width of the grid. The second line contains $h$ integers $r_{1}, r_{2}, \ldots, r_{h}$ ($0 \le r_{i} \le w$) — the values of $r$. The third line contains $w$ integers $c_{1}, c_{2}, \ldots, c_{w}$ ($0 \le c_{j} \le h$) — the values of $c$. -----Output----- Print the answer modulo $1000000007\,(10^{9} + 7)$. -----Examples----- Input 3 4 0 3 1 0 2 3 0 Output 2 Input 1 1 0 1 Output 0 Input 19 16 16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12 6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4 Output 797922655 -----Note----- In the first example, this is the other possible case. [Image] In the second example, it's impossible to make a grid to satisfy such $r$, $c$ values. In the third example, make sure to print answer modulo $(10^9 + 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. In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets. Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem. Constraints * 1 ≤ x ≤ 10000 * The number of datasets ≤ 10000 Input The input consists of multiple datasets. Each dataset consists of an integer x in a line. The input ends with an integer 0. You program should not process (print) for this terminal symbol. Output For each dataset, print x in the following format: Case i: x where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x. Example Input 3 5 11 7 8 19 0 Output Case 1: 3 Case 2: 5 Case 3: 11 Case 4: 7 Case 5: 8 Case 6: 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. All of the animals are having a feast! Each animal is bringing one dish. There is just one rule: the dish must start and end with the same letters as the animal's name. For example, the great blue heron is bringing garlic naan and the chickadee is bringing chocolate cake. Write a function `feast` that takes the animal's name and dish as arguments and returns true or false to indicate whether the beast is allowed to bring the dish to the feast. Assume that `beast` and `dish` are always lowercase strings, and that each has at least two letters. `beast` and `dish` may contain hyphens and spaces, but these will not appear at the beginning or end of the string. They will not contain numerals. Write your solution by modifying this code: ```python def feast(beast, dish): ``` Your solution should implemented in the function "feast". The i 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. <image> <image> *The two images are equivalent, feel free to use either one. Input The input contains a single integer a (-100 ≤ a ≤ 100). Output Output the result – an integer number. Example Input 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. There are S sheep and W wolves. If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep. If the wolves will attack the sheep, print unsafe; otherwise, print safe. -----Constraints----- - 1 \leq S \leq 100 - 1 \leq W \leq 100 -----Input----- Input is given from Standard Input in the following format: S W -----Output----- If the wolves will attack the sheep, print unsafe; otherwise, print safe. -----Sample Input----- 4 5 -----Sample Output----- unsafe There are four sheep and five wolves. The number of wolves is not less than that of sheep, so they will attack them. 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 pair of integer numbers `(m, n)`, such that `10 > m > n > 0`, (below 10), that its sum, `(m + n)`, and rest, `(m - n)`, are perfect squares, is (5, 4). Let's see what we have explained with numbers. ``` 5 + 4 = 9 = 3² 5 - 4 = 1 = 1² (10 > 5 > 4 > 0) ``` The pair of numbers `(m, n)`, closest to and below 50, having the property described above is `(45, 36)`. ``` 45 + 36 = 81 = 9² 45 - 36 = 9 = 3² (50 > 45 > 36 > 0) ``` With the function `closest_pair_tonum()`, that receives a number `upper_limit`, as an upper limit, we should be able to obtain the closest pair to `upper_limit`, that fulfills the property described above. The function should return the largest pair of numbers `(m, n)`, satisfying `upper_limit > m > n > 0`. Note that we say pair A `(a0, a1)` is larger than pair B `(b0, b1)` when `a0 > b0` or `a0 == b0 and a1 > b1`. Let's see some cases: ```python closest_pair_tonum(10) == (5, 4) # (m = 5, n = 4) closest_pair_tonum(30) == (29, 20) closest_pair_tonum(50) == (45, 36) ``` Happy coding and enjoy it!! (We will be having a second part of a similar exercise (in some days) that will need a faster algorithm for values of `upper_limit` < 1000) Write your solution by modifying this code: ```python def closest_pair_tonum(upper_lim): ``` Your solution should implemented in the function "closest_pair_tonum". The i 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. Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten. He remembers that the remainder of a divided by b was greater than or equal to K. Find the number of possible pairs that he may have had. Constraints * 1 \leq N \leq 10^5 * 0 \leq K \leq N-1 * All input values are integers. Input Input is given from Standard Input in the following format: N K Output Print the number of possible pairs that he may have had. Examples Input 5 2 Output 7 Input 10 0 Output 100 Input 31415 9265 Output 287927211 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. Food contains three nutrients called "protein", "fat" and "carbohydrate", which are called three major nutrients. It is calculated that protein and carbohydrate are 4 kcal (kilocalories) and fat is 9 kcal per 1 g (gram). For example, according to the table below, the number 1 cake contains 7 g of protein, 14 g of fat and 47 g of carbohydrates. If you calculate the calories contained based on this, it will be 4 x 7 + 9 x 14 + 4 x 47 = 342 kcal. Others are calculated in the same way. Number | Name | Protein (g) | Lipids (g) | Carbohydrates (g) | Calories (kcal) --- | --- | --- | --- | --- | --- 1 | Cake | 7 | 14 | 47 | 342 2 | Potato Chips | 5 | 35 | 55 | 555 3 | Dorayaki | 6 | 3 | 59 | 287 4 | Pudding | 6 | 5 | 15 | 129 Input the number of sweets to be classified n, the information of each sweet, and the limit information, and output a list of sweets that do not exceed the limit (may be eaten) if only one sweet is used. Create a program. The candy information consists of the candy number s, the weight p of the protein contained in the candy, the weight q of the lipid, and the weight r of the carbohydrate. The limit information consists of the maximum protein weight P that can be included, the fat weight Q, the carbohydrate weight R, and the maximum calorie C that can be consumed, of protein, fat, carbohydrate, and calories. If any one of them is exceeded, the restriction will be violated and it will be judged as "sweets that should not be eaten". For a list of sweets that you can eat, output the numbers of sweets that you can eat in the order in which you entered them. If there are no sweets you can eat, please output "NA". For the four sweets in the table above, if the limit is P = 10, Q = 15, R = 50, C = 400, cake and pudding may be eaten as their respective nutrients and calories are below the limit. Although it is classified as sweets, potato chips are classified as sweets that should not be eaten because the amount of carbohydrates exceeds the limit value. input Given a sequence of multiple datasets. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: n s1 p1 q1 r1 s2 p2 q2 r2 :: sn pn qn rn P Q R C The first line gives the number of sweets n (1 ≤ n ≤ 1000). The next n lines are given the number si (1 ≤ si ≤ 1000) of the i-th candy and the integers pi, qi, ri (0 ≤ pi, qi, ri ≤ 100) representing the weight of each nutrient. The following lines are given the integers P, Q, R (0 ≤ P, Q, R ≤ 100), C (0 ≤ C ≤ 1700) representing the limits for each nutrient and calorie. The number of datasets does not exceed 100. output For each dataset, it outputs the number of sweets you can eat or "NA". Example Input 4 1 7 14 47 2 5 35 55 3 6 3 59 4 6 5 15 10 15 50 400 2 1 8 10 78 2 4 18 33 10 10 50 300 0 Output 1 4 NA 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. I'm traveling to a country with a rabbit. There are n cities in this country numbered from 1 to n, and the rabbit is now in city 1. City i is a point on the coordinate plane (xi, yi) ). Rabbits travel to meet the following conditions. * The travel path is a polygonal line, each part of which must be a line segment connecting two different cities. * The total length of the travel route must be r or less. The overlapping part of the route is also counted for the number of times it has passed. * When the direction of movement changes, the bending angle must be less than or equal to θ. There is no limit to the initial direction of movement. If you move from one city to another, you will get one carrot in the destination city. You can visit the same city multiple times, and you will get a carrot each time you visit. Find the maximum number of carrots you can put in. Input One integer n is given on the first line of the input, and two real numbers r and θ are given on the second line, separated by a space. 1 ≤ n ≤ 20 0 <r <104 0 ° <θ <180 ° The following n lines are given the integers xi and yi separated by spaces. -10 000 ≤ xi, yi ≤ 10 000 The answer does not change even if r and θ are changed within ± 10-3. The locations of both cities are different. Output Output the maximum number of carrots that the rabbit can get on this trip in one line. Example Input 5 100.1 90.1 0 0 0 10 5 5 10 0 10 10 Output 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. Numbers of black and white points are placed on a plane. Let's imagine that a straight line of infinite length is drawn on the plane. When the line does not meet any of the points, the line divides these points into two groups. If the division by such a line results in one group consisting only of black points and the other consisting only of white points, we say that the line "separates black and white points". Let's see examples in Figure 3. In the leftmost example, you can easily find that the black and white points can be perfectly separated by the dashed line according to their colors. In the remaining three examples, there exists no such straight line that gives such a separation. <image> Figure 3: Example planes In this problem, given a set of points with their colors and positions, you are requested to decide whether there exists a straight line that separates black and white points. Input The input is a sequence of datasets, each of which is formatted as follows. n m x1 y1 . . . xn yn xn+1 yn+1 . . . xn+m yn+m The first line contains two positive integers separated by a single space; n is the number of black points, and m is the number of white points. They are less than or equal to 100. Then n + m lines representing the coordinates of points follow. Each line contains two integers xi and yi separated by a space, where (xi , yi ) represents the x-coordinate and the y-coordinate of the i-th point. The color of the i-th point is black for 1 ≤ i ≤ n, and is white for n + 1 ≤ i ≤ n + m. All the points have integral x- and y-coordinate values between 0 and 10000 inclusive. You can also assume that no two points have the same position. The end of the input is indicated by a line containing two zeros separated by a space. Output For each dataset, output "YES" if there exists a line satisfying the condition. If not, output "NO". In either case, print it in one line for each input dataset. Example Input 3 3 100 700 200 200 600 600 500 100 500 300 800 500 3 3 100 300 400 600 400 100 600 400 500 900 300 300 3 4 300 300 500 300 400 600 100 100 200 900 500 900 800 100 1 2 300 300 100 100 500 500 1 1 100 100 200 100 2 2 0 0 500 700 1000 1400 1500 2100 2 2 0 0 1000 1000 1000 0 0 1000 3 3 0 100 4999 102 10000 103 5001 102 10000 102 0 101 3 3 100 100 200 100 100 200 0 0 400 0 0 400 3 3 2813 1640 2583 2892 2967 1916 541 3562 9298 3686 7443 7921 0 0 Output YES NO NO NO YES YES NO NO NO YES Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Consider a tic-tac-toe on a 3x3 board. Tic-tac-toe is a two-player battle game. Decide the first attack and the second attack, one hits Kuroishi and one hits Shiraishi. The winner is the person who puts stones one by one on the board alternately and arranges three of his own stones first in either the vertical, horizontal, or diagonal direction. Create a program that inputs the information on the board, judges the victory or defeat, outputs "b" if black wins, "w" if white wins, and "NA" if neither is available. please. The board information consists of 3 rows and 3 columns of character strings. "B" is Kuroishi, "w" is Shiraishi, and "+" (half-width plus) is nothing. However, three blacks and three whites cannot be lined up at the same time. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: board1 board2 board3 The i-line is given the string boardi that represents the information on the i-th line of the board. The number of datasets does not exceed 50. Output Outputs "b", "w", or "NA" on one line for each data set. Example Input bbw wbw +b+ bwb wbw wbw 0 Output b NA 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 has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes. The exam consists of $n$ problems that can be solved in $T$ minutes. Thus, the exam begins at time $0$ and ends at time $T$. Petya can leave the exam at any integer time from $0$ to $T$, inclusive. All problems are divided into two types: easy problems — Petya takes exactly $a$ minutes to solve any easy problem; hard problems — Petya takes exactly $b$ minutes ($b > a$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $x$, then it will be solved at time $x+a$. Similarly, if at a time $x$ Petya starts to solve a hard problem, then it will be solved at time $x+b$. For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $t_i$ ($0 \le t_i \le T$) at which it will become mandatory (required). If Petya leaves the exam at time $s$ and there is such a problem $i$ that $t_i \le s$ and he didn't solve it, then he will receive $0$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $t_i \le s$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $s$ Petya can have both "mandatory" and "non-mandatory" problems solved. For example, if $n=2$, $T=5$, $a=2$, $b=3$, the first problem is hard and $t_1=3$ and the second problem is easy and $t_2=2$. Then: if he leaves at time $s=0$, then he will receive $0$ points since he will not have time to solve any problems; if he leaves at time $s=1$, he will receive $0$ points since he will not have time to solve any problems; if he leaves at time $s=2$, then he can get a $1$ point by solving the problem with the number $2$ (it must be solved in the range from $0$ to $2$); if he leaves at time $s=3$, then he will receive $0$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $s=4$, then he will receive $0$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $s=5$, then he can get $2$ points by solving all problems. Thus, the answer to this test is $2$. Help Petya to determine the maximal number of points that he can receive, before leaving the exam. -----Input----- The first line contains the integer $m$ ($1 \le m \le 10^4$) — the number of test cases in the test. The next lines contain a description of $m$ test cases. The first line of each test case contains four integers $n, T, a, b$ ($2 \le n \le 2\cdot10^5$, $1 \le T \le 10^9$, $1 \le a < b \le 10^9$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $n$ numbers $0$ or $1$, separated by single space: the $i$-th number means the type of the $i$-th problem. A value of $0$ means that the problem is easy, and a value of $1$ that the problem is hard. The third line of each test case contains $n$ integers $t_i$ ($0 \le t_i \le T$), where the $i$-th number means the time at which the $i$-th problem will become mandatory. It is guaranteed that the sum of $n$ for all test cases does not exceed $2\cdot10^5$. -----Output----- Print the answers to $m$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam. -----Example----- Input 10 3 5 1 3 0 0 1 2 1 4 2 5 2 3 1 0 3 2 1 20 2 4 0 16 6 20 2 5 1 1 0 1 0 0 0 8 2 9 11 6 4 16 3 6 1 0 1 1 8 3 5 6 6 20 3 6 0 1 0 0 1 0 20 11 3 20 16 17 7 17 1 6 1 1 0 1 0 0 0 1 7 0 11 10 15 10 6 17 2 6 0 0 1 0 0 1 7 6 3 7 10 12 5 17 2 5 1 1 1 1 0 17 11 10 6 4 1 1 1 2 0 1 Output 3 2 1 0 1 4 0 1 2 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya is reading a e-book. The file of the book consists of $n$ pages, numbered from $1$ to $n$. The screen is currently displaying the contents of page $x$, and Vasya wants to read the page $y$. There are two buttons on the book which allow Vasya to scroll $d$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $10$ pages, and $d = 3$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth. Help Vasya to calculate the minimum number of times he needs to press a button to move to page $y$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^3$) — the number of testcases. Each testcase is denoted by a line containing four integers $n$, $x$, $y$, $d$ ($1\le n, d \le 10^9$, $1 \le x, y \le n$) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively. -----Output----- Print one line for each test. If Vasya can move from page $x$ to page $y$, print the minimum number of times he needs to press a button to do it. Otherwise print $-1$. -----Example----- Input 3 10 4 5 2 5 1 3 4 20 4 19 3 Output 4 -1 5 -----Note----- In the first test case the optimal sequence is: $4 \rightarrow 2 \rightarrow 1 \rightarrow 3 \rightarrow 5$. In the second test case it is possible to get to pages $1$ and $5$. In the third test case the optimal sequence is: $4 \rightarrow 7 \rightarrow 10 \rightarrow 13 \rightarrow 16 \rightarrow 19$. 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. Chef loves to prepare delicious dishes. This time, Chef has decided to prepare a special dish for you, and needs to gather several apples to do so. Chef has N apple trees in his home garden. Each tree has a certain (non-zero) number of apples on it. In order to create his dish, Chef wants to pluck every apple from every tree. Chef has an unusual method of collecting apples. In a single minute, he can perform the following task: Pick any subset of trees such that every tree in the subset has the same number of apples. From each tree in the subset, pluck any number of apples, as long as the number of apples left on the tree equals the number of apples on a tree not in the subset. If all trees have the same number of apples left, Chef can pluck all of the apples remaining in a single minute. Chef does not want to keep you waiting, so wants to achieve this task in the minimum possible time. Can you tell him what the minimum time required is? ------ Input ------ The first line of the input contains a single integer T denoting the number of test cases. This will be followed by T test cases. The first line of each test case contains a single integer N denoting the number of apple trees in Chef's garden. The next line of each test case contains N space separated integers denoting the number of apples on each tree. ------ Output ------ For each of the T test cases, output a single line - the minimum time to pluck all apples from all trees. ------ Constraints ------ $1 ≤ T ≤ 10$ $1 ≤ N ≤ 10^{5}$ $1 ≤ Number of apples on a tree ≤ 10^{5}$ ------ Scoring ------ $Subtask 1 : 1 ≤ T ≤ 10 , 1 ≤ N ≤ 10^{3}: (27 pts) $ $Subtask 2 : 1 ≤ T ≤ 10 , 1 ≤ N ≤ 10^{4}: (25 pts) $ $Subtask 3 : 1 ≤ T ≤ 10 , 1 ≤ N ≤ 10^{5}: (48 pts) $ ----- Sample Input 1 ------ 2 3 3 3 3 4 1 2 3 3 ----- Sample Output 1 ------ 1 3 ----- explanation 1 ------ For test 1, Chef can select all the trees and can pluck all the apples in 1 minute. For test 2, there are many ways Chef can pluck all of the apples in 3 minutes. Here is one example: First minute: Select the third and fourth trees. Pluck 1 apple from the third tree, and 2 apples from the fourth tree. Second minute: Select the second and third tree. Pluck 1 apple from each tree. Third minute: Select all of the trees and pluck the last apple from each tree. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The only difference between easy and hard versions is constraints. There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are distinct integers from $1$ to $n$ (i.e. $p$ is a permutation). The sequence $p$ doesn't change from day to day, it is fixed. For example, if $n=6$ and $p=[4, 6, 1, 3, 5, 2]$ then at the end of the first day the book of the $1$-st kid will belong to the $4$-th kid, the $2$-nd kid will belong to the $6$-th kid and so on. At the end of the second day the book of the $1$-st kid will belong to the $3$-th kid, the $2$-nd kid will belong to the $2$-th kid and so on. Your task is to determine the number of the day the book of the $i$-th child is returned back to him for the first time for every $i$ from $1$ to $n$. Consider the following example: $p = [5, 1, 2, 4, 3]$. The book of the $1$-st kid will be passed to the following kids: after the $1$-st day it will belong to the $5$-th kid, after the $2$-nd day it will belong to the $3$-rd kid, after the $3$-rd day it will belong to the $2$-nd kid, after the $4$-th day it will belong to the $1$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day. You have to answer $q$ independent queries. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 200$) — the number of queries. Then $q$ queries follow. The first line of the query contains one integer $n$ ($1 \le n \le 200$) — the number of kids in the query. The second line of the query contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ are distinct, i.e. $p$ is a permutation), where $p_i$ is the kid which will get the book of the $i$-th kid. -----Output----- For each query, print the answer on it: $n$ integers $a_1, a_2, \dots, a_n$, where $a_i$ is the number of the day the book of the $i$-th child is returned back to him for the first time in this query. -----Example----- Input 6 5 1 2 3 4 5 3 2 3 1 6 4 6 2 1 5 3 1 1 4 3 4 1 2 5 5 1 2 4 3 Output 1 1 1 1 1 3 3 3 2 3 3 2 1 3 1 2 2 2 2 4 4 4 1 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. We define $x \bmod y$ as the remainder of division of $x$ by $y$ ($\%$ operator in C++ or Java, mod operator in Pascal). Let's call an array of positive integers $[a_1, a_2, \dots, a_k]$ stable if for every permutation $p$ of integers from $1$ to $k$, and for every non-negative integer $x$, the following condition is met: $ (((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k = (((x \bmod a_{p_1}) \bmod a_{p_2}) \dots \bmod a_{p_{k - 1}}) \bmod a_{p_k} $ That is, for each non-negative integer $x$, the value of $(((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k$ does not change if we reorder the elements of the array $a$. For two given integers $n$ and $k$, calculate the number of stable arrays $[a_1, a_2, \dots, a_k]$ such that $1 \le a_1 < a_2 < \dots < a_k \le n$. -----Input----- The only line contains two integers $n$ and $k$ ($1 \le n, k \le 5 \cdot 10^5$). -----Output----- Print one integer — the number of stable arrays $[a_1, a_2, \dots, a_k]$ such that $1 \le a_1 < a_2 < \dots < a_k \le n$. Since the answer may be large, print it modulo $998244353$. -----Examples----- Input 7 3 Output 16 Input 3 7 Output 0 Input 1337 42 Output 95147305 Input 1 1 Output 1 Input 500000 1 Output 500000 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.