question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Snuke signed up for a new website which holds programming competitions. He worried that he might forget his password, and he took notes of it. Since directly recording his password would cause him trouble if stolen, he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions. You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order. Restore the original password. -----Constraints----- - O and E consists of lowercase English letters (a - z). - 1 \leq |O|,|E| \leq 50 - |O| - |E| is either 0 or 1. -----Input----- Input is given from Standard Input in the following format: O E -----Output----- Print the original password. -----Sample Input----- xyz abc -----Sample Output----- xaybzc The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 is a tree with N vertices numbered 1 to N, and N-1 edges numbered 1 to N-1. Edge i connects Vertex a_i and b_i bidirectionally and has a length of 1. Snuke will paint each vertex white or black. The niceness of a way of painting the graph is \max(X, Y), where X is the maximum among the distances between white vertices, and Y is the maximum among the distances between black vertices. Here, if there is no vertex of one color, we consider the maximum among the distances between vertices of that color to be 0. There are 2^N ways of painting the graph. Compute the sum of the nicenesses of all those ways, modulo (10^{9}+7). -----Constraints----- - 2 \leq N \leq 2 \times 10^{5} - 1 \leq a_i, b_i \leq N - The given graph is a tree. -----Input----- Input is given from Standard Input in the following format: N a_1 b_1 \vdots a_{N-1} b_{N-1} -----Output----- Print the sum of the nicenesses of the ways of painting the graph, modulo (10^{9}+7). -----Sample Input----- 2 1 2 -----Sample Output----- 2 - If we paint Vertex 1 and 2 the same color, the niceness will be 1; if we paint them different colors, the niceness will be 0. - The sum of those nicenesses is 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The __Hamming weight__ of a string is the number of symbols that are different from the zero-symbol of the alphabet used. There are several algorithms for efficient computing of the Hamming weight for numbers. In this Kata, speaking technically, you have to find out the number of '1' bits in a binary representation of a number. Thus, The interesting part of this task is that you have to do it *without* string operation (hey, it's not really interesting otherwise) ;) Write your solution by modifying this code: ```python def hamming_weight(x): ``` Your solution should implemented in the function "hamming_weight". 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. Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to gain dexterity that never mistypes by carefully stacking blocks. Since there are many building blocks, let's build a tall tower. There are N blocks, and the i-th (1 ≤ i ≤ N) building blocks are in the shape of a rectangular parallelepiped of 1 x Ai x Bi. The side of length 1 is used in the depth direction, and the sides of lengths Ai and Bi are assigned one by one in the horizontal direction and one in the height direction. When building blocks, the upper building blocks must be exactly shorter in width than the lower building blocks. The blocks can be used in any order, and some blocks may not be used. Under these restrictions, I want to make the tallest tower that can be built. Input N A1 B1 ... AN BN Satisfy 1 ≤ N ≤ 1,000, 1 ≤ Ai, Bi ≤ 1,000,000. All input values ​​are integers. Output Output the maximum height of the tower on one line. Examples Input 3 10 40 10 40 20 30 Output 80 Input 4 1 2 2 3 3 4 4 1 Output 11 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task Smartphones software security has become a growing concern related to mobile telephony. It is particularly important as it relates to the security of available personal information. For this reason, Ahmed decided to encrypt phone numbers of contacts in such a way that nobody can decrypt them. At first he tried encryption algorithms very complex, but the decryption process is tedious, especially when he needed to dial a speed dial. He eventually found the algorithm following: instead of writing the number itself, Ahmed multiplied by 10, then adds the result to the original number. For example, if the phone number is `123`, after the transformation, it becomes `1353`. Ahmed truncates the result (from the left), so it has as many digits as the original phone number. In this example Ahmed wrote `353` instead of `123` in his smart phone. Ahmed needs a program to recover the original phone number from number stored on his phone. The program return "impossible" if the initial number can not be calculated. Note: There is no left leading zero in either the input or the output; Input `s` is given by string format, because it may be very huge ;-) # Example For `s="353"`, the result should be `"123"` ``` 1230 + 123 ....... = 1353 truncates the result to 3 digit -->"353" So the initial number is "123" ``` For `s="123456"`, the result should be `"738496"` ``` 7384960 + 738496 ......... = 8123456 truncates the result to 6 digit -->"123456" So the initial number is "738496" ``` For `s="4334"`, the result should be `"impossible"` Because no such a number can be encrypted to `"4334"`. # Input/Output - `[input]` string `s` string presentation of n with `1 <= n <= 10^100` - `[output]` a string The original phone number before encryption, or `"impossible"` if the initial number can not be calculated. Write your solution by modifying this code: ```python def decrypt(s): ``` Your solution should implemented in the function "decrypt". 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. "What are your shoe sizes?" Suddenly, the doctor asked me when I met him for the first time. "It's 23.5" "Oh, that's a really nice number. It's 2 to the 4th power plus 2 to the 2nd power, 2 to the 1st power, 2 to the 0th power, and 2 to the 1st power." Then the doctor asked. "You, how tall are you?" "Yes, it's 158.1." He folded his arms and closed his eyes. After a while of silence, I opened my mouth. "Nah ~" After that, during the time I spent together, I gradually became able to understand the behavior of the doctor. First, I say the real number at the request of the doctor. If the real number is represented by a binary number with no more than 8 digits for the integer part and no more than 4 digits for the decimal part, he is happy to say the result of the conversion to binary. If not, it will sadly yell "Nah ~". This repeats until I say a negative real number. By the way, as he got older, it became more and more difficult to make long calculations. Therefore, please make a program for you to input real numbers and convert / output them to binary numbers on your behalf. However, if the binary representation does not fit within the limit number of digits (integer part within 8 digits + decimal part within 4 digits), output NA (half-width alphabetic characters). The input real number shall fit within 8 digits of the integer part and within 4 digits of the decimal part, and the binary representation to be output should be output with 8 digits of the integer part and 4 digits of the decimal part. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single negative real line. One real number n is given to one row for each dataset. The number of datasets does not exceed 1200. Output Outputs the conversion result to binary number for each input data set. Example Input 23.5 158.1 -1.0 Output 00010111.1000 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. # Task Consider the following algorithm for constructing 26 strings S(1) .. S(26): ``` S(1) = "a"; For i in [2, 3, ..., 26]: S(i) = S(i - 1) + character(i) + S(i - 1).``` For example: ``` S(1) = "a" S(2) = S(1) + "b" + S(1) = "a" + "b" + "a" = "aba" S(3) = S(2) + "c" + S(2) = "aba" + "c" +"aba" = "abacaba" ... S(26) = S(25) + "z" + S(25)``` Finally, we got a long string S(26). Your task is to find the `k`th symbol (indexing from 1) in the string S(26). All strings consist of lowercase letters only. # Input / Output - `[input]` integer `k` 1 ≤ k < 2^(26) - `[output]` a string(char in C#) the `k`th symbol of S(26) Write your solution by modifying this code: ```python def abacaba(k): ``` Your solution should implemented in the function "abacaba". 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. Slime and his $n$ friends are at a party. Slime has designed a game for his friends to play. At the beginning of the game, the $i$-th player has $a_i$ biscuits. At each second, Slime will choose a biscuit randomly uniformly among all $a_1 + a_2 + \ldots + a_n$ biscuits, and the owner of this biscuit will give it to a random uniform player among $n-1$ players except himself. The game stops when one person will have all the biscuits. As the host of the party, Slime wants to know the expected value of the time that the game will last, to hold the next activity on time. For convenience, as the answer can be represented as a rational number $\frac{p}{q}$ for coprime $p$ and $q$, you need to find the value of $(p \cdot q^{-1})\mod 998\,244\,353$. You can prove that $q\mod 998\,244\,353 \neq 0$. -----Input----- The first line contains one integer $n\ (2\le n\le 100\,000)$: the number of people playing the game. The second line contains $n$ non-negative integers $a_1,a_2,\dots,a_n\ (1\le a_1+a_2+\dots+a_n\le 300\,000)$, where $a_i$ represents the number of biscuits the $i$-th person own at the beginning. -----Output----- Print one integer: the expected value of the time that the game will last, modulo $998\,244\,353$. -----Examples----- Input 2 1 1 Output 1 Input 2 1 2 Output 3 Input 5 0 0 0 0 35 Output 0 Input 5 8 4 2 0 1 Output 801604029 -----Note----- For the first example, in the first second, the probability that player $1$ will give the player $2$ a biscuit is $\frac{1}{2}$, and the probability that player $2$ will give the player $1$ a biscuit is $\frac{1}{2}$. But anyway, the game will stop after exactly $1$ second because only one player will occupy all biscuits after $1$ second, so the 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. Поликарп мечтает стать программистом и фанатеет от степеней двойки. Среди двух чисел ему больше нравится то, которое делится на большую степень числа 2. По заданной последовательности целых положительных чисел a_1, a_2, ..., a_{n} требуется найти r — максимальную степень числа 2, на которую делится хотя бы одно из чисел последовательности. Кроме того, требуется вывести количество чисел a_{i}, которые делятся на r. -----Входные данные----- В первой строке записано целое число n (1 ≤ n ≤ 100) — длина последовательности a. Во второй строке записана последовательность целых чисел a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). -----Выходные данные----- Выведите два числа: r — максимальную степень двойки, на которую делится хотя бы одно из чисел заданной последовательности, количество элементов последовательности, которые делятся на r. -----Примеры----- Входные данные 5 80 7 16 4 48 Выходные данные 16 3 Входные данные 4 21 5 3 33 Выходные данные 1 4 -----Примечание----- В первом тестовом примере максимальная степень двойки, на которую делится хотя бы одно число, равна 16 = 2^4, на неё делятся числа 80, 16 и 48. Во втором тестовом примере все четыре числа нечётные, поэтому делятся только на 1 = 2^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 certainly can tell which is the larger number between 2^(10) and 2^(15). But what about, say, 2^(10) and 3^(10)? You know this one too. Things tend to get a bit more complicated with **both** different bases and exponents: which is larger between 3^(9) and 5^(6)? Well, by now you have surely guessed that you have to build a function to compare powers, returning -1 if the first member is larger, 0 if they are equal, 1 otherwise; powers to compare will be provided in the `[base, exponent]` format: ```python compare_powers([2,10],[2,15])==1 compare_powers([2,10],[3,10])==1 compare_powers([2,10],[2,10])==0 compare_powers([3,9],[5,6])==-1 compare_powers([7,7],[5,8])==-1 ``` ```if:nasm int compare_powers(const int n1[2], const int n2[2]) ``` Only positive integers will be tested, incluing bigger numbers - you are warned now, so be diligent try to implement an efficient solution not to drain too much on CW resources ;)! Write your solution by modifying this code: ```python def compare_powers(n1,n2): ``` Your solution should implemented in the function "compare_powers". 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. ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '<image>' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1. When ZS the Coder is at level k, he can : 1. Press the ' + ' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes x + k. 2. Press the '<image>' button. Let the number on the screen be x. After pressing this button, the number becomes <image>. After that, ZS the Coder levels up, so his current level becomes k + 1. This button can only be pressed when x is a perfect square, i.e. x = m2 for some positive integer m. Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '<image>' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5. ZS the Coder needs your help in beating the game — he wants to reach level n + 1. In other words, he needs to press the '<image>' button n times. Help him determine the number of times he should press the ' + ' button before pressing the '<image>' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level n + 1, but not necessarily a sequence minimizing the number of presses. Input The first and only line of the input contains a single integer n (1 ≤ n ≤ 100 000), denoting that ZS the Coder wants to reach level n + 1. Output Print n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the ' + ' button before pressing the '<image>' button at level i. Each number in the output should not exceed 1018. However, the number on the screen can be greater than 1018. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them. Examples Input 3 Output 14 16 46 Input 2 Output 999999999999999998 44500000000 Input 4 Output 2 17 46 97 Note In the first sample case: On the first level, ZS the Coder pressed the ' + ' button 14 times (and the number on screen is initially 2), so the number became 2 + 14·1 = 16. Then, ZS the Coder pressed the '<image>' button, and the number became <image>. After that, on the second level, ZS pressed the ' + ' button 16 times, so the number becomes 4 + 16·2 = 36. Then, ZS pressed the '<image>' button, levelling up and changing the number into <image>. After that, on the third level, ZS pressed the ' + ' button 46 times, so the number becomes 6 + 46·3 = 144. Then, ZS pressed the '<image>' button, levelling up and changing the number into <image>. Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4. Also, note that pressing the ' + ' button 10 times on the third level before levelling up does not work, because the number becomes 6 + 10·3 = 36, and when the '<image>' button is pressed, the number becomes <image> and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution. In the second sample case: On the first level, ZS the Coder pressed the ' + ' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2 + 999999999999999998·1 = 1018. Then, ZS the Coder pressed the '<image>' button, and the number became <image>. After that, on the second level, ZS pressed the ' + ' button 44500000000 times, so the number becomes 109 + 44500000000·2 = 9·1010. Then, ZS pressed the '<image>' button, levelling up and changing the number into <image>. Note that 300000 is a multiple of 3, so ZS the Coder can reach level 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. [Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) (RLE) is a very simple form of lossless data compression in which runs of data are stored as a single data value and count. A simple form of RLE would encode the string `"AAABBBCCCD"` as `"3A3B3C1D"` meaning, first there are `3 A`, then `3 B`, then `3 C` and last there is `1 D`. Your task is to write a RLE encoder and decoder using this technique. The texts to encode will always consist of only uppercase characters, no numbers. Write your solution by modifying this code: ```python def encode(string): ``` Your solution should implemented in the function "encode". 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. Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task. Input The single line contains an integer n (1 ≤ n ≤ 106) — the sum of digits of the required lucky number. Output Print on the single line the result — the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1. Examples Input 11 Output 47 Input 10 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. Dr. A of the Aizu Institute of Biological Research discovered a mysterious insect on a certain southern island. The shape is elongated like a hornworm, but since one segment is shaped like a ball, it looks like a beaded ball connected by a thread. What was strange was that there were many variations in body color, and some insects changed their body color over time. It seems that the color of the somites of all insects is limited to either red, green or blue, but the color of the somites changes every second, and finally all the somites become the same color and settle down. In some cases, the color seemed to keep changing no matter how long I waited. <image> As I investigated, I found that all the body segments usually have the same color, but after being surprised or excited by something, the color of the body segments changes without permission. It turns out that once the color of the segment changes, it will continue to change until all the segment are the same color again. Dr. A was curiously observing how the color changed when he caught and excited many of these insects, but the way the color changed during the color change is as follows. I noticed that there is regularity. * The color changes only in one pair of two adjacent somites of different colors, and the colors of the other somites do not change. However, when there are multiple such pairs, it is not possible to predict in advance which pair will change color. * Such a pair will change to a color that is neither of the colors of the two segmentes at the same time (for example, if the green and red segment are adjacent, they will change to blue at the same time). <image> The figure above shows all the changes in the color of the insects up to 2 seconds later. Suppose you have an insect that has the color shown in the upper part of the figure. At this time, there are 3 pairs of adjacent somites of different colors, so after 1 second, it will change to one of the 3 colors drawn side by side in the middle row. After 1 second, all the segments can turn green after 2 seconds (second from the left in the lower row of the figure) when they change to the two on the left side of the middle row. On the other hand, when it changes like the one on the far right in the middle row after 1 second, all the segments do not change to the same color after 2 seconds. He decided to predict if all the insect segments in front of him could be the same color, and if so, at the earliest, how many seconds later. Create a program that takes the color sequence of the insect body segments in front of you as input and outputs the shortest time required for all the insect body segments to have the same color in seconds. However, if there is no possibility that the colors will be the same, output "NA (half-width uppercase letters)". In addition, the color sequence of the insect body segment is represented by a character string consisting of r (red), g (green), and b (blue) of 2 or more and 10 or less. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. For each dataset, one string is given on one line that represents information about the insect's somites. The number of datasets does not exceed 100. Output For each dataset, the minimum time (integer in seconds) or NA required for all segment colors to be the same is output on one line. Example Input rbgrg rbbgbbr bgr bgrbrgbr bggrgbgrr gbrggrbggr rrrrr bgbr 0 Output 5 7 1 6 NA 8 0 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. Read problems statements in Mandarin Chinese and Russian as well. After IOI Ilya decided to make a business. He found a social network called "TheScorpyBook.com". It currently has N registered users. As in any social network two users can be friends. Ilya wants the world to be as connected as possible, so he wants to suggest friendship to some pairs of users. He will suggest user u to have a friendship with user v if they are not friends yet and there is a user w who is friends of both of them. Note that u, v and w are different users. Ilya is too busy with IPO these days, so he asks you to count how many friendship suggestions he has to send over his social network.   ------ Input ------ The first line contains an integer number N — the number of users in the network. Next N lines contain N characters each denoting friendship relations. j^{th} character if the i^{th} lines equals one, if users i and j are friends and equals to zero otherwise. This relation is symmetric, i.e. if user a is friend of b then b is also a friend of a.   ------ Output ------ Output a single integer — number of friendship suggestions Ilya has to send.   ------ Constraints ------ $1 ≤ N ≤ 2000$ ------ Example ------ Input: 4 0111 1000 1000 1000 Output: 6 ------ Explanation ------ Each of users [2, 3, 4] should receive two friendship suggestions, while user 1 does not need any, since he already has all other users in his friend-list. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy. Input The only line contains three integers n, a and b (0 ≤ a, b < n ≤ 100). Output Print the single number — the number of the sought positions. Examples Input 3 1 1 Output 2 Input 5 2 3 Output 3 Note The possible positions in the first sample are: 2 and 3 (if we number the positions starting with 1). In the second sample they are 3, 4 and 5. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds. Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation: * If s does not contain X_i: add X_i to the end of s. * If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s. Find the elements of s after Snuke finished the operations. Constraints * 1 \leq N \leq 2 \times 10^5 * 1 \leq K \leq 10^{12} * 1 \leq A_i \leq 2 \times 10^5 * All values in input are integers. Input Input is given from Standard Input in the following format: N K A_0 A_1 \cdots A_{N-1} Output Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between. Examples Input 3 2 1 2 3 Output 2 3 Input 5 10 1 2 3 2 3 Output 3 Input 6 1000000000000 1 1 2 2 3 3 Output Input 11 97 3 1 4 1 5 9 2 6 5 3 5 Output 9 2 6 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ```if-not:julia,racket Write a function that returns the total surface area and volume of a box as an array: `[area, volume]` ``` ```if:julia Write a function that returns the total surface area and volume of a box as a tuple: `(area, volume)` ``` ```if:racket Write a function that returns the total surface area and volume of a box as a list: `'(area, volume)` ``` Write your solution by modifying this code: ```python def get_size(w,h,d): ``` Your solution should implemented in the function "get_size". 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 will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i. In the contest, N foods numbered 1 through N will be presented, and the difficulty of Food i is F_i. The details of the contest are as follows: - A team should assign one member to each food, and should not assign the same member to multiple foods. - It will take x \times y seconds for a member to finish the food, where x is the consumption coefficient of the member and y is the difficulty of the dish. - The score of a team is the longest time it takes for an individual member to finish the food. Before the contest, Takahashi's team decided to do some training. In one set of training, a member can reduce his/her consumption coefficient by 1, as long as it does not go below 0. However, for financial reasons, the N members can do at most K sets of training in total. What is the minimum possible score of the team, achieved by choosing the amounts of members' training and allocating the dishes optimally? -----Constraints----- - All values in input are integers. - 1 \leq N \leq 2 \times 10^5 - 0 \leq K \leq 10^{18} - 1 \leq A_i \leq 10^6\ (1 \leq i \leq N) - 1 \leq F_i \leq 10^6\ (1 \leq i \leq N) -----Input----- Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N F_1 F_2 ... F_N -----Output----- Print the minimum possible score of the team. -----Sample Input----- 3 5 4 2 1 2 3 1 -----Sample Output----- 2 They can achieve the score of 2, as follows: - Member 1 does 4 sets of training and eats Food 2 in (4-4) \times 3 = 0 seconds. - Member 2 does 1 set of training and eats Food 3 in (2-1) \times 1 = 1 second. - Member 3 does 0 sets of training and eats Food 1 in (1-0) \times 2 = 2 seconds. They cannot achieve a score of less than 2, so the answer is 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two integers $n$ and $m$ ($m < n$). Consider a convex regular polygon of $n$ vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). [Image] Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with $m$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. The next $t$ lines describe test cases. Each test case is given as two space-separated integers $n$ and $m$ ($3 \le m < n \le 100$) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build. -----Output----- For each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with $m$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise. -----Example----- Input 2 6 3 7 3 Output YES NO -----Note----- $0$ The first test case of the example It can be shown that the answer for the second test case of the example 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. Arkady decided to buy roses for his girlfriend. A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color. Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is b_{i}, and its color is c_{i} ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose). Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet. -----Input----- The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy. The second line contains a sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10 000), where b_{i} equals the beauty of the i-th rose. The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where c_{i} denotes the color of the i-th rose: 'W' denotes white, 'O'  — orange, 'R' — red. -----Output----- Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1. -----Examples----- Input 5 3 4 3 4 1 6 RROWW Output 11 Input 5 2 10 20 14 20 11 RRRRR Output -1 Input 11 5 5 6 3 2 3 4 7 5 4 5 6 RWOORWORROW Output 28 -----Note----- In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11. In the second example Arkady can not buy a bouquet because all roses have the same color. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$. Find out the non-negative remainder of division of $\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$ by $10^{9} + 9$. Note that the modulo is unusual! -----Input----- The first line contains four integers $n, a, b$ and $k$ $(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$. The second line contains a sequence of length $k$ consisting of characters '+' and '-'. If the $i$-th character (0-indexed) is '+', then $s_{i} = 1$, otherwise $s_{i} = -1$. Note that only the first $k$ members of the sequence are given, the rest can be obtained using the periodicity property. -----Output----- Output a single integer — value of given expression modulo $10^{9} + 9$. -----Examples----- Input 2 2 3 3 +-+ Output 7 Input 4 1 5 1 - Output 999999228 -----Note----- In the first example: $(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$ = $2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$ = 7 In the second example: $(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and a_{i} is the length of i-th segment. No two segments touch or intersect. For example: If x = 6 and the crossword is 111011, then its encoding is an array {3, 2}; If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1}; If x = 5 and the crossword is 11111, then its encoding is an array {5}; If x = 5 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it! -----Input----- The first line contains two integer numbers n and x (1 ≤ n ≤ 100000, 1 ≤ x ≤ 10^9) — the number of elements in the encoding and the length of the crossword Mishka picked. The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10000) — the encoding. -----Output----- Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO. -----Examples----- Input 2 4 1 3 Output NO Input 3 10 3 3 2 Output YES Input 2 10 1 3 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. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. Figure 4: another example of a path that does not satisfy the condition -----Constraints----- - 2≦N≦8 - 0≦M≦N(N-1)/2 - 1≦a_i<b_i≦N - The given graph contains neither self-loops nor double edges. -----Input----- The input is given from Standard Input in the following format: N M a_1 b_1 a_2 b_2 : a_M b_M -----Output----- Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. -----Sample Input----- 3 3 1 2 1 3 2 3 -----Sample Output----- 2 The given graph is shown in the following figure: The following two paths satisfy the condition: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Example Input mmemewwemeww Output Cat Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Devu has an array A consisting of N positive integers. He would like to perform following operation on array. - Pick some two elements a, b in the array (a could be same as b, but their corresponding indices in the array should not be same). Remove both the elements a and b and instead add a number x such that x lies between min(a, b) and max(a, b), both inclusive, (i.e. min(a, b) ≤ x ≤ max(a, b)). Now, as you know after applying the above operation N - 1 times, Devu will end up with a single number in the array. He is wondering whether it is possible to do the operations in such a way that he ends up a number t. He asks your help in answering Q such queries, each of them will contain an integer t and you have to tell whether it is possible to end up t. -----Input----- There is only one test case per test file. First line of the input contains two space separated integers N, Q denoting number of elements in A and number of queries for which Devu asks your help, respectively Second line contains N space separated integers denoting the content of array A. Each of the next Q lines, will contain a single integer t corresponding to the query. -----Output----- Output Q lines, each containing "Yes" or "No" (both without quotes) corresponding to the answer of corresponding query. -----Constraints----- - 1 ≤ N, Q ≤ 105 - 0 ≤ t ≤ 109 -----Subtasks----- Subtask #1 : 30 points - 1 ≤ Ai ≤ 2 Subtask #2 : 70 points - 1 ≤ Ai ≤ 109 -----Example----- Input 1: 1 2 1 1 2 Output: Yes No Input 2: 2 4 1 3 1 2 3 4 Output: Yes Yes Yes No -----Explanation----- In the first example, Devu can't apply any operation. So the final element in the array will be 1 itself. In the second example, Devu can replace 1 and 3 with any of the numbers among 1, 2, 3. Hence final element of the array could be 1, 2 or 3. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You've come to your favorite store Infinitesco to buy some ice tea. The store sells ice tea in bottles of different volumes at different costs. Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen. The store has an infinite supply of bottles of each type. You want to buy exactly N liters of ice tea. How many yen do you have to spend? Constraints * 1 \leq Q, H, S, D \leq 10^8 * 1 \leq N \leq 10^9 * All input values are integers. Input Input is given from Standard Input in the following format: Q H S D N Output Print the smallest number of yen you have to spend to buy exactly N liters of ice tea. Examples Input 20 30 70 90 3 Output 150 Input 10000 1000 100 10 1 Output 100 Input 10 100 1000 10000 1 Output 40 Input 12345678 87654321 12345678 87654321 123456789 Output 1524157763907942 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression. To achieve the goal, the gym teacher ordered a lot of magical buns from the dining room. The magic buns come in two types: when a student eats one magic bun of the first type, his height increases by one, when the student eats one magical bun of the second type, his height decreases by one. The physical education teacher, as expected, cares about the health of his students, so he does not want them to eat a lot of buns. More precisely, he wants the maximum number of buns eaten by some student to be minimum. Help the teacher, get the maximum number of buns that some pupils will have to eat to achieve the goal of the teacher. Also, get one of the possible ways for achieving the objective, namely, the height of the lowest student in the end and the step of the resulting progression. -----Input----- The single line contains integer n (2 ≤ n ≤ 10^3) — the number of students. The second line contains n space-separated integers — the heights of all students. The height of one student is an integer which absolute value doesn't exceed 10^4. -----Output----- In the first line print the maximum number of buns eaten by some student to achieve the teacher's aim. In the second line, print two space-separated integers — the height of the lowest student in the end and the step of the progression. Please, pay attention that the step should be non-negative. If there are multiple possible answers, you can print any of them. -----Examples----- Input 5 -3 -4 -2 -3 3 Output 2 -3 1 Input 5 2 -3 -1 -4 3 Output 1 -4 2 -----Note----- Lets look at the first sample. We can proceed in the following manner: don't feed the 1-st student, his height will stay equal to -3; give two buns of the first type to the 2-nd student, his height become equal to -2; give two buns of the first type to the 3-rd student, his height become equal to 0; give two buns of the first type to the 4-th student, his height become equal to -1; give two buns of the second type to the 5-th student, his height become equal to 1. To sum it up, when the students line up in non-decreasing height it will be an arithmetic progression: -3, -2, -1, 0, 1. The height of the lowest student is equal to -3, the step of the progression is equal to 1. The maximum number of buns eaten by one student is equal to 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. Peter can see a clock in the mirror from the place he sits in the office. When he saw the clock shows 12:22 1 2 3 4 5 6 7 8 9 10 11 12 He knows that the time is 11:38 1 2 3 4 5 6 7 8 9 10 11 12 in the same manner: 05:25 --> 06:35 01:50 --> 10:10 11:58 --> 12:02 12:01 --> 11:59 Please complete the function `WhatIsTheTime(timeInMirror)`, where `timeInMirror` is the mirrored time (what Peter sees) as string. Return the _real_ time as a string. Consider hours to be between 1 <= hour < 13. So there is no 00:20, instead it is 12:20. There is no 13:20, instead it is 01:20. Write your solution by modifying this code: ```python def what_is_the_time(time_in_mirror): ``` Your solution should implemented in the function "what_is_the_time". 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 non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j (1 ≤ j ≤ n-2), that s_{j}s_{j+1}s_{j+2}="one" or s_{j}s_{j+1}s_{j+2}="two". For example: * Polycarp does not like strings "oneee", "ontwow", "twone" and "oneonetwo" (they all have at least one substring "one" or "two"), * Polycarp likes strings "oonnee", "twwwo" and "twnoe" (they have no substrings "one" and "two"). Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time. For example, if the string looks like s="onetwone", then if Polycarp selects two indices 3 and 6, then "onetwone" will be selected and the result is "ontwne". What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be? Input The first line of the input contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Next, the test cases are given. Each test case consists of one non-empty string s. Its length does not exceed 1.5⋅10^5. The string s consists only of lowercase Latin letters. It is guaranteed that the sum of lengths of all lines for all input data in the test does not exceed 1.5⋅10^6. Output Print an answer for each test case in the input in order of their appearance. The first line of each answer should contain r (0 ≤ r ≤ |s|) — the required minimum number of positions to be removed, where |s| is the length of the given line. The second line of each answer should contain r different integers — the indices themselves for removal in any order. Indices are numbered from left to right from 1 to the length of the string. If r=0, then the second line can be skipped (or you can print empty). If there are several answers, print any of them. Examples Input 4 onetwone testme oneoneone twotwo Output 2 6 3 0 3 4 1 7 2 1 4 Input 10 onetwonetwooneooonetwooo two one twooooo ttttwo ttwwoo ooone onnne oneeeee oneeeeeeetwooooo Output 6 18 11 12 1 6 21 1 1 1 3 1 2 1 6 0 1 4 0 1 1 2 1 11 Note In the first example, answers are: * "onetwone", * "testme" — Polycarp likes it, there is nothing to remove, * "oneoneone", * "twotwo". In the second example, answers are: * "onetwonetwooneooonetwooo", * "two", * "one", * "twooooo", * "ttttwo", * "ttwwoo" — Polycarp likes it, there is nothing to remove, * "ooone", * "onnne" — Polycarp likes it, there is nothing to remove, * "oneeeee", * "oneeeeeeetwooooo". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given an integer N, find the base -2 representation of N. Here, S is the base -2 representation of N when the following are all satisfied: - S is a string consisting of 0 and 1. - Unless S = 0, the initial character of S is 1. - Let S = S_k S_{k-1} ... S_0, then S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S_k \times (-2)^k = N. It can be proved that, for any integer M, the base -2 representation of M is uniquely determined. -----Constraints----- - Every value in input is integer. - -10^9 \leq N \leq 10^9 -----Input----- Input is given from Standard Input in the following format: N -----Output----- Print the base -2 representation of N. -----Sample Input----- -9 -----Sample Output----- 1011 As (-2)^0 + (-2)^1 + (-2)^3 = 1 + (-2) + (-8) = -9, 1011 is the base -2 representation of -9. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible. Input The first line contains an integer N (1 ≤ N ≤ 1000) — the number of bars at Vasya’s disposal. The second line contains N space-separated integers li — the lengths of the bars. All the lengths are natural numbers not exceeding 1000. Output In one line output two numbers — the height of the largest tower and their total number. Remember that Vasya should use all the bars. Examples Input 3 1 2 3 Output 1 3 Input 4 6 5 6 7 Output 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. Treeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town. In Treeland there are 2k universities which are located in different towns. Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done! To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in k pairs should be as large as possible. Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1. -----Input----- The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ n / 2) — the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to n. The second line contains 2k distinct integers u_1, u_2, ..., u_2k (1 ≤ u_{i} ≤ n) — indices of towns in which universities are located. The next n - 1 line contains the description of roads. Each line contains the pair of integers x_{j} and y_{j} (1 ≤ x_{j}, y_{j} ≤ n), which means that the j-th road connects towns x_{j} and y_{j}. All of them are two-way roads. You can move from any town to any other using only these roads. -----Output----- Print the maximum possible sum of distances in the division of universities into k pairs. -----Examples----- Input 7 2 1 5 6 2 1 3 3 2 4 5 3 7 4 3 4 6 Output 6 Input 9 3 3 2 1 6 5 9 8 9 3 2 2 7 3 4 7 6 4 5 2 1 2 8 Output 9 -----Note----- The figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example. [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. Monocarp is playing a computer game. He's going to kill $n$ monsters, the $i$-th of them has $h_i$ health. Monocarp's character has two spells, either of which he can cast an arbitrary number of times (possibly, zero) and in an arbitrary order: choose exactly two alive monsters and decrease their health by $1$; choose a single monster and kill it. When a monster's health becomes $0$, it dies. What's the minimum number of spell casts Monocarp should perform in order to kill all monsters? -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases. The first line of each testcase contains a single integer $n$ ($1 \le n \le 100$) — the number of monsters. The second line contains $n$ integers $h_1, h_2, \dots, h_n$ ($1 \le h_i \le 100$) — the health of each monster. The sum of $n$ over all testcases doesn't exceed $2 \cdot 10^4$. -----Output----- For each testcase, print a single integer — the minimum number of spell casts Monocarp should perform in order to kill all monsters. -----Examples----- Input 3 4 1 2 1 2 3 2 4 2 5 1 2 3 4 5 Output 3 3 5 -----Note----- In the first testcase, the initial health list is $[1, 2, 1, 2]$. Three spells are casted: the first spell on monsters $1$ and $2$ — monster $1$ dies, monster $2$ has now health $1$, new health list is $[0, 1, 1, 2]$; the first spell on monsters $3$ and $4$ — monster $3$ dies, monster $4$ has now health $1$, new health list is $[0, 1, 0, 1]$; the first spell on monsters $2$ and $4$ — both monsters $2$ and $4$ die. In the second testcase, the initial health list is $[2, 4, 2]$. Three spells are casted: the first spell on monsters $1$ and $3$ — both monsters have health $1$ now, new health list is $[1, 4, 1]$; the second spell on monster $2$ — monster $2$ dies, new health list is $[1, 0, 1]$; the first spell on monsters $1$ and $3$ — both monsters $1$ and $3$ die. In the third testcase, the initial health list is $[1, 2, 3, 4, 5]$. Five spells are casted. The $i$-th of them kills the $i$-th monster with the second spell. Health list sequence: $[1, 2, 3, 4, 5]$ $\rightarrow$ $[0, 2, 3, 4, 5]$ $\rightarrow$ $[0, 0, 3, 4, 5]$ $\rightarrow$ $[0, 0, 0, 4, 5]$ $\rightarrow$ $[0, 0, 0, 0, 5]$ $\rightarrow$ $[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. For this kata, you are given three points ```(x1,y1,z1)```, ```(x2,y2,z2)```, and ```(x3,y3,z3)``` that lie on a straight line in 3-dimensional space. You have to figure out which point lies in between the other two. Your function should return 1, 2, or 3 to indicate which point is the in-between one. Write your solution by modifying this code: ```python def middle_point(x1, y1, z1, x2, y2, z2, x3, y3, z3): ``` Your solution should implemented in the function "middle_point". 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. Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again. The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): <image> Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut. To understand the problem better please read the notes to the test samples. Input The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≤ n ≤ 100000). The i-th (1 ≤ i ≤ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise. Output Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled. Examples Input -++- Output Yes Input +- Output No Input ++ Output Yes Input - Output No Note The first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses. In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: <image> In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: <image> In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself: <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. Nick has n bottles of soda left after his birthday. Each bottle is described by two values: remaining amount of soda a_{i} and bottle volume b_{i} (a_{i} ≤ b_{i}). Nick has decided to pour all remaining soda into minimal number of bottles, moreover he has to do it as soon as possible. Nick spends x seconds to pour x units of soda from one bottle to another. Nick asks you to help him to determine k — the minimal number of bottles to store all remaining soda and t — the minimal time to pour soda into k bottles. A bottle can't store more soda than its volume. All remaining soda should be saved. -----Input----- The first line contains positive integer n (1 ≤ n ≤ 100) — the number of bottles. The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100), where a_{i} is the amount of soda remaining in the i-th bottle. The third line contains n positive integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 100), where b_{i} is the volume of the i-th bottle. It is guaranteed that a_{i} ≤ b_{i} for any i. -----Output----- The only line should contain two integers k and t, where k is the minimal number of bottles that can store all the soda and t is the minimal time to pour the soda into k bottles. -----Examples----- Input 4 3 3 4 3 4 7 6 5 Output 2 6 Input 2 1 1 100 100 Output 1 1 Input 5 10 30 5 6 24 10 41 7 8 24 Output 3 11 -----Note----- In the first example Nick can pour soda from the first bottle to the second bottle. It will take 3 seconds. After it the second bottle will contain 3 + 3 = 6 units of soda. Then he can pour soda from the fourth bottle to the second bottle and to the third bottle: one unit to the second and two units to the third. It will take 1 + 2 = 3 seconds. So, all the soda will be in two bottles and he will spend 3 + 3 = 6 seconds to do it. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly a_{i} feet high. [Image] A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group. Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x. -----Input----- The first line of input contains integer n (1 ≤ n ≤ 2 × 10^5), the number of bears. The second line contains n integers separated by space, a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), heights of bears. -----Output----- Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x. -----Examples----- Input 10 1 2 3 4 5 4 3 2 1 6 Output 6 4 4 3 3 2 2 1 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. Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has $n$ positions to install lamps, they correspond to the integer numbers from $0$ to $n - 1$ on the OX axis. However, some positions are blocked and no post lamp can be placed there. There are post lamps of different types which differ only by their power. When placed in position $x$, post lamp of power $l$ illuminates the segment $[x; x + l]$. The power of each post lamp is always a positive integer number. The post lamp shop provides an infinite amount of lamps of each type from power $1$ to power $k$. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power $l$ cost $a_l$ each. What is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment $[0; n]$ of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power $3$ in position $n - 1$ (even though its illumination zone doesn't completely belong to segment $[0; n]$). -----Input----- The first line contains three integer numbers $n$, $m$ and $k$ ($1 \le k \le n \le 10^6$, $0 \le m \le n$) — the length of the segment of the street Adilbek wants to illuminate, the number of the blocked positions and the maximum power of the post lamp available. The second line contains $m$ integer numbers $s_1, s_2, \dots, s_m$ ($0 \le s_1 < s_2 < \dots s_m < n$) — the blocked positions. The third line contains $k$ integer numbers $a_1, a_2, \dots, a_k$ ($1 \le a_i \le 10^6$) — the costs of the post lamps. -----Output----- Print the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment $[0; n]$ of the street. If illumintaing the entire segment $[0; n]$ is impossible, print -1. -----Examples----- Input 6 2 3 1 3 1 2 3 Output 6 Input 4 3 4 1 2 3 1 10 100 1000 Output 1000 Input 5 1 5 0 3 3 3 3 3 Output -1 Input 7 4 3 2 4 5 6 3 14 15 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. If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $n$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light. Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $g$ seconds green, and then $r$ seconds red, then again $g$ seconds green and so on. Formally, the road can be represented as a segment $[0, n]$. Initially, Denis is at point $0$. His task is to get to point $n$ in the shortest possible time. He knows many different integers $d_1, d_2, \ldots, d_m$, where $0 \leq d_i \leq n$  — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on. Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $\pm 1$ in $1$ second. While doing so, he must always stay inside the segment $[0, n]$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $+1$ and he walked on a safety island, then he can change his position by $\pm 1$. Otherwise, he can change his position only by $+1$. Similarly, if in the previous second he changed his position by $-1$, on a safety island he can change position by $\pm 1$, and at any other point by $-1$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $n$. This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. -----Input----- The first line contains two integers $n$ and $m$ $(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$  — road width and the number of safety islands. The second line contains $m$ distinct integers $d_1, d_2, \ldots, d_m$ $(0 \leq d_i \leq n)$  — the points where the safety islands are located. It is guaranteed that there are $0$ and $n$ among them. The third line contains two integers $g, r$ $(1 \leq g, r \leq 1000)$  — the time that the green light stays on and the time that the red light stays on. -----Output----- Output a single integer  — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $-1$. -----Examples----- Input 15 5 0 3 7 14 15 11 11 Output 45 Input 13 4 0 3 7 13 9 9 Output -1 -----Note----- In the first test, the optimal route is:      for the first green light, go to $7$ and return to $3$. In this case, we will change the direction of movement at the point $7$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $3$, where there is also a safety island. The next $11$ seconds we have to wait for the red light.      for the second green light reaches $14$. Wait for the red light again.      for $1$ second go to $15$. As a result, Denis is at the end of the road. In total, $45$ seconds are obtained. In the second test, it is impossible to cross the road according to all the rules. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke has an integer sequence A of length N. He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E. The positions of the cuts can be freely chosen. Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively. Snuke is happier when the absolute difference of the maximum and the minimum among P,Q,R,S is smaller. Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S. -----Constraints----- - 4 \leq N \leq 2 \times 10^5 - 1 \leq A_i \leq 10^9 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N A_1 A_2 ... A_N -----Output----- Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S. -----Sample Input----- 5 3 2 4 1 2 -----Sample Output----- 2 If we divide A as B,C,D,E=(3),(2),(4),(1,2), then P=3,Q=2,R=4,S=1+2=3. Here, the maximum and the minimum among P,Q,R,S are 4 and 2, with the absolute difference of 2. We cannot make the absolute difference of the maximum and the minimum less than 2, so the answer is 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A sequence of $n$ numbers is called a permutation if it contains all integers from $1$ to $n$ exactly once. For example, the sequences [$3, 1, 4, 2$], [$1$] and [$2,1$] are permutations, but [$1,2,1$], [$0,1$] and [$1,3,4$] — are not. Polycarp lost his favorite permutation and found only some of its elements — the numbers $b_1, b_2, \dots b_m$. He is sure that the sum of the lost elements equals $s$. Determine whether one or more numbers can be appended to the given sequence $b_1, b_2, \dots b_m$ such that the sum of the added numbers equals $s$, and the resulting new array is a permutation? -----Input----- The first line of input contains a single integer $t$ ($1 \le t \le 100$) —the number of test cases. Then the descriptions of the test cases follow. The first line of each test set contains two integers $m$ and $s$ ($1 \le m \le 50$, $1 \le s \le 1000$)—-the number of found elements and the sum of forgotten numbers. The second line of each test set contains $m$ different integers $b_1, b_2 \dots b_m$ ($1 \le b_i \le 50$) — the elements Polycarp managed to find. -----Output----- Print $t$ lines, each of which is the answer to the corresponding test set. Print as the answer YES if you can append several elements to the array $b$, that their sum equals $s$ and the result will be a permutation. Output NO otherwise. You can output the answer in any case (for example, yEs, yes, Yes and YES will be recognized as positive answer). -----Examples----- Input 5 3 13 3 1 4 1 1 1 3 3 1 4 2 2 1 4 3 5 6 1 2 3 4 5 Output YES NO YES NO YES -----Note----- In the test case of the example, $m=3, s=13, b=[3,1,4]$. You can append to $b$ the numbers $6,2,5$, the sum of which is $6+2+5=13$. Note that the final array will become $[3,1,4,6,2,5]$, which is a permutation. In the second test case of the example, $m=1, s=1, b=[1]$. You cannot append one or more numbers to $[1]$ such that their sum equals $1$ and the result is a permutation. In the third test case of the example, $m=3, s=3, b=[1,4,2]$. You can append the number $3$ to $b$. Note that the resulting array will be $[1,4,2,3]$, which is a permutation. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 triangle formed by three points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$ on a plain. Write a program which prints "YES" if a point $P$ $(x_p, y_p)$ is in the triangle and "NO" if not. Constraints You can assume that: * $ -100 \leq x_1, y_1, x_2, y_2, x_3, y_3, x_p, y_p \leq 100$ * 1.0 $\leq$ Length of each side of a tringle * 0.001 $\leq$ Distance between $P$ and each side of a triangle Input Input consists of several datasets. Each dataset consists of: $x_1$ $y_1$ $x_2$ $y_2$ $x_3$ $y_3$ $x_p$ $y_p$ All the input are real numbers. Input ends with EOF. The number of datasets is less than or equal to 100. Output For each dataset, print "YES" or "NO" in a line. Example Input 0.0 0.0 2.0 0.0 2.0 2.0 1.5 0.5 0.0 0.0 1.0 4.0 5.0 3.0 -1.0 3.0 Output YES NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task You're given a two-dimensional array of integers `matrix`. Your task is to determine the smallest non-negative integer that is not present in this array. # Input/Output - `[input]` 2D integer array `matrix` A non-empty rectangular matrix. `1 ≤ matrix.length ≤ 10` `1 ≤ matrix[0].length ≤ 10` - `[output]` an integer The smallest non-negative integer that is not present in matrix. # Example For ``` matrix = [ [0, 2], [5, 1]]``` the result should be `3` 0,1,2,`(3)`...5 Write your solution by modifying this code: ```python def smallest_integer(matrix): ``` Your solution should implemented in the function "smallest_integer". 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 N integers; the i-th of them is A_i. Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 : A_N Output Print the maximum possible sum of the absolute differences between the adjacent elements after arranging the given integers in a row in any order you like. Examples Input 5 6 8 1 2 3 Output 21 Input 6 3 1 4 1 5 9 Output 25 Input 3 5 5 1 Output 8 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Triangular number is the amount of points that can fill equilateral triangle. Example: the number 6 is a triangular number because all sides of a triangle has the same amount of points. ``` Hint! T(n) = n * (n + 1) / 2, n - is the size of one side. T(n) - is the triangular number. ``` Given a number 'T' from interval [1; 2147483646], find if it is triangular number or not. Write your solution by modifying this code: ```python def is_triangular(t): ``` Your solution should implemented in the function "is_triangular". 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 integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: Pick a random segment (continuous subsequence) from l to r. All $\frac{n(n + 1)}{2}$ segments are equiprobable. Let k = r - l + 1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p_1, p_2, ..., p_{k}. All k! permutation are equiprobable. This permutation is applied to elements of the chosen segment, i.e. permutation a_1, a_2, ..., a_{l} - 1, a_{l}, a_{l} + 1, ..., a_{r} - 1, a_{r}, a_{r} + 1, ..., a_{n} is transformed to a_1, a_2, ..., a_{l} - 1, a_{l} - 1 + p_1, a_{l} - 1 + p_2, ..., a_{l} - 1 + p_{k} - 1, a_{l} - 1 + p_{k}, a_{r} + 1, ..., a_{n}. Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i, j) such that i < j and a_{i} > a_{j}. Find the expected number of inversions after we apply exactly one operation mentioned above. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 100 000) — the length of the permutation. The second line contains n distinct integers from 1 to n — elements of the permutation. -----Output----- Print one real value — the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 9}. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-9}$. -----Example----- Input 3 2 3 1 Output 1.916666666666666666666666666667 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 two standard ways to represent a graph $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges; Adjacency list representation and Adjacency matrix representation. An adjacency-list representation consists of an array $Adj[|V|]$ of $|V|$ lists, one for each vertex in $V$. For each $u \in V$, the adjacency list $Adj[u]$ contains all vertices $v$ such that there is an edge $(u, v) \in E$. That is, $Adj[u]$ consists of all vertices adjacent to $u$ in $G$. An adjacency-matrix representation consists of $|V| \times |V|$ matrix $A = a_{ij}$ such that $a_{ij} = 1$ if $(i, j) \in E$, $a_{ij} = 0$ otherwise. Write a program which reads a directed graph $G$ represented by the adjacency list, and prints its adjacency-matrix representation. $G$ consists of $n\; (=|V|)$ vertices identified by their IDs $1, 2,.., n$ respectively. Constraints * $1 \leq n \leq 100$ Input In the first line, an integer $n$ is given. In the next $n$ lines, an adjacency list $Adj[u]$ for vertex $u$ are given in the following format: $u$ $k$ $v_1$ $v_2$ ... $v_k$ $u$ is vertex ID and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$. Output As shown in the following sample output, print the adjacent-matrix representation of $G$. Put a single space character between $a_{ij}$. Example Input 4 1 2 2 4 2 1 4 3 0 4 1 3 Output 0 1 0 1 0 0 0 1 0 0 0 0 0 0 1 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. Given are integers A, B, and N. Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N. Here floor(t) denotes the greatest integer not greater than the real number t. -----Constraints----- - 1 ≤ A ≤ 10^{6} - 1 ≤ B ≤ 10^{12} - 1 ≤ N ≤ 10^{12} - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: A B N -----Output----- Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer. -----Sample Input----- 5 7 4 -----Sample Output----- 2 When x=3, floor(Ax/B)-A×floor(x/B) = floor(15/7) - 5×floor(3/7) = 2. This is the maximum value possible. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a number from the second bag, and then sums them modulo M. What are the residues modulo M that Ajs cannot obtain with this action? Input The first line contains two positive integer N (1 ≤ N ≤ 200 000) and M (N+1 ≤ M ≤ 10^{9}), denoting the number of the elements in the first bag and the modulus, respectively. The second line contains N nonnegative integers a_1,a_2,…,a_N (0 ≤ a_1<a_2< …< a_N<M), the contents of the first bag. Output In the first line, output the cardinality K of the set of residues modulo M which Ajs cannot obtain. In the second line of the output, print K space-separated integers greater or equal than zero and less than M, which represent the residues Ajs cannot obtain. The outputs should be sorted in increasing order of magnitude. If K=0, do not output the second line. Examples Input 2 5 3 4 Output 1 2 Input 4 1000000000 5 25 125 625 Output 0 Input 2 4 1 3 Output 2 0 2 Note In the first sample, the first bag and the second bag contain \{3,4\} and \{0,1,2\}, respectively. Ajs can obtain every residue modulo 5 except the residue 2: 4+1 ≡ 0, 4+2 ≡ 1, 3+0 ≡ 3, 3+1 ≡ 4 modulo 5. One can check that there is no choice of elements from the first and the second bag which sum to 2 modulo 5. In the second sample, the contents of the first bag are \{5,25,125,625\}, while the second bag contains all other nonnegative integers with at most 9 decimal digits. Every residue modulo 1 000 000 000 can be obtained as a sum of an element in the first bag and an element in the second bag. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Pathfinder is a distinguished authority on the structure of hyperlinks in the World Wide Web. For establishing his hypotheses, he has been developing software agents, which automatically traverse hyperlinks and analyze the structure of the Web. Today, he has gotten an intriguing idea to improve his software agents. However, he is very busy and requires help from good programmers. You are now being asked to be involved in his development team and to create a small but critical software module of his new type of software agents. Upon traversal of hyperlinks, Pathfinder’s software agents incrementally generate a map of visited portions of the Web. So the agents should maintain the list of traversed hyperlinks and visited web pages. One problem in keeping track of such information is that two or more different URLs can point to the same web page. For instance, by typing any one of the following five URLs, your favorite browsers probably bring you to the same web page, which as you may have visited is the home page of the ACM ICPC Ehime contest. http://www.ehime-u.ac.jp/ICPC/ http://www.ehime-u.ac.jp/ICPC http://www.ehime-u.ac.jp/ICPC/../ICPC/ http://www.ehime-u.ac.jp/ICPC/./ http://www.ehime-u.ac.jp/ICPC/index.html Your program should reveal such aliases for Pathfinder’s experiments. Well, . . . but it were a real challenge and to be perfect you might have to embed rather compli- cated logic into your program. We are afraid that even excellent programmers like you could not complete it in five hours. So, we make the problem a little simpler and subtly unrealis- tic. You should focus on the path parts (i.e. /ICPC/, /ICPC, /ICPC/../ICPC/, /ICPC/./, and /ICPC/index.html in the above example) of URLs and ignore the scheme parts (e.g. http://), the server parts (e.g. www.ehime-u.ac.jp), and other optional parts. You should carefully read the rules described in the sequel since some of them may not be based on the reality of today’s Web and URLs. Each path part in this problem is an absolute pathname, which specifies a path from the root directory to some web page in a hierarchical (tree-shaped) directory structure. A pathname always starts with a slash (/), representing the root directory, followed by path segments delim- ited by a slash. For instance, /ICPC/index.html is a pathname with two path segments ICPC and index.html. All those path segments but the last should be directory names and the last one the name of an ordinary file where a web page is stored. However, we have one exceptional rule: an ordinary file name index.html at the end of a pathname may be omitted. For instance, a pathname /ICPC/index.html can be shortened to /ICPC/, if index.html is an existing ordinary file name. More precisely, if ICPC is the name of an existing directory just under the root and index.html is the name of an existing ordinary file just under the /ICPC directory, /ICPC/index.html and /ICPC/ refer to the same web page. Furthermore, the last slash following the last path segment can also be omitted. That is, for instance, /ICPC/ can be further shortened to /ICPC. However, /index.html can only be abbreviated to / (a single slash). You should pay special attention to path segments consisting of a single period (.) or a double period (..), both of which are always regarded as directory names. The former represents the directory itself and the latter represents its parent directory. Therefore, if /ICPC/ refers to some web page, both /ICPC/./ and /ICPC/../ICPC/ refer to the same page. Also /ICPC2/../ICPC/ refers to the same page if ICPC2 is the name of an existing directory just under the root; otherwise it does not refer to any web page. Note that the root directory does not have any parent directory and thus such pathnames as /../ and /ICPC/../../index.html cannot point to any web page. Your job in this problem is to write a program that checks whether two given pathnames refer to existing web pages and, if so, examines whether they are the same. Input The input consists of multiple datasets. The first line of each dataset contains two positive integers N and M, both of which are less than or equal to 100 and are separated by a single space character. The rest of the dataset consists of N + 2M lines, each of which contains a syntactically correct pathname of at most 100 characters. You may assume that each path segment enclosed by two slashes is of length at least one. In other words, two consecutive slashes cannot occur in any pathname. Each path segment does not include anything other than alphanumerical characters (i.e. ‘a’-‘z’, ‘A’-‘Z’, and ‘0’-‘9’) and periods (‘.’). The first N pathnames enumerate all the web pages (ordinary files). Every existing directory name occurs at least once in these pathnames. You can assume that these pathnames do not include any path segments consisting solely of single or double periods and that the last path segments are ordinary file names. Therefore, you do not have to worry about special rules for index.html and single/double periods. You can also assume that no two of the N pathnames point to the same page. Each of the following M pairs of pathnames is a question: do the two pathnames point to the same web page? These pathnames may include single or double periods and may be terminated by a slash. They may include names that do not correspond to existing directories or ordinary files. Two zeros in a line indicate the end of the input. Output For each dataset, your program should output the M answers to the M questions, each in a separate line. Each answer should be “yes” if both point to the same web page, “not found” if at least one of the pathnames does not point to any one of the first N web pages listed in the input, or “no” otherwise. Example Input 5 6 /home/ACM/index.html /ICPC/index.html /ICPC/general.html /ICPC/japanese/index.html /ICPC/secret/confidential/2005/index.html /home/ACM/ /home/ICPC/../ACM/ /ICPC/secret/ /ICPC/secret/index.html /ICPC /ICPC/../ICPC/index.html /ICPC /ICPC/general.html /ICPC/japanese/.././ /ICPC/japanese/./../ /home/ACM/index.html /home/ACM/index.html/ 1 4 /index.html/index.html / /index.html/index.html /index.html /index.html/index.html /.. /index.html/../.. /index.html/ /index.html/index.html/.. 0 0 Output not found not found yes no yes not found not found yes not found not found Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. From Wikipedia : "The n-back task is a continuous performance task that is commonly used as an assessment in cognitive neuroscience to measure a part of working memory and working memory capacity. [...] The subject is presented with a sequence of stimuli, and the task consists of indicating when the current stimulus matches the one from n steps earlier in the sequence. The load factor n can be adjusted to make the task more or less difficult." In this kata, your task is to "teach" your computer to do the n-back task. Specifically, you will be implementing a function that counts the number of "targets" (stimuli that match the one from n steps earlier) in a sequence of digits. Your function will take two parameters : n, a positive integer equal to the number of steps to look back to find a match sequence, a sequence of digits containing 0 or more targets A few hints : The first digit in a sequence can never be a target Targets can be "chained" together (e.g., for n = 1 and sequence = [1, 1, 1], there are 2 targets) Write your solution by modifying this code: ```python def count_targets(n, sequence): ``` Your solution should implemented in the function "count_targets". 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. Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first. Consider the 2D plane. There is a token which is initially at $(0,0)$. In one move a player must increase either the $x$ coordinate or the $y$ coordinate of the token by exactly $k$. In doing so, the player must ensure that the token stays within a (Euclidean) distance $d$ from $(0,0)$. In other words, if after a move the coordinates of the token are $(p,q)$, then $p^2 + q^2 \leq d^2$ must hold. The game ends when a player is unable to make a move. It can be shown that the game will end in a finite number of moves. If both players play optimally, determine who will win. -----Input----- The first line contains a single integer $t$ ($1 \leq t \leq 100$) — the number of test cases. The only line of each test case contains two space separated integers $d$ ($1 \leq d \leq 10^5$) and $k$ ($1 \leq k \leq d$). -----Output----- For each test case, if Ashish wins the game, print "Ashish", otherwise print "Utkarsh" (without the quotes). -----Examples----- Input 5 2 1 5 2 10 3 25 4 15441 33 Output Utkarsh Ashish Utkarsh Utkarsh Ashish -----Note----- In the first test case, one possible sequence of moves can be $(0, 0) \xrightarrow{\text{Ashish }} (0, 1) \xrightarrow{\text{Utkarsh }} (0, 2)$. Ashish has no moves left, so Utkarsh wins. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke loves constructing integer sequences. There are N piles of stones, numbered 1 through N. The pile numbered i consists of a_i stones. Snuke will construct an integer sequence s of length Σa_i, as follows: - Among the piles with the largest number of stones remaining, let x be the index of the pile with the smallest index. Append x to the end of s. - Select a pile with one or more stones remaining, and remove a stone from that pile. - If there is a pile with one or more stones remaining, go back to step 1. Otherwise, terminate the process. We are interested in the lexicographically smallest sequence that can be constructed. For each of the integers 1,2,3,...,N, how many times does it occur in the lexicographically smallest sequence? -----Constraints----- - 1 ≤ N ≤ 10^{5} - 1 ≤ a_i ≤ 10^{9} -----Input----- The input is given from Standard Input in the following format: N a_1 a_2 ... a_{N} -----Output----- Print N lines. The i-th line should contain the number of the occurrences of the integer i in the lexicographically smallest sequence that can be constructed. -----Sample Input----- 2 1 2 -----Sample Output----- 2 1 The lexicographically smallest sequence is constructed as follows: - Since the pile with the largest number of stones remaining is pile 2, append 2 to the end of s. Then, remove a stone from pile 2. - Since the piles with the largest number of stones remaining are pile 1 and 2, append 1 to the end of s (we take the smallest index). Then, remove a stone from pile 2. - Since the pile with the largest number of stones remaining is pile 1, append 1 to the end of s. Then, remove a stone from pile 1. The resulting sequence is (2,1,1). In this sequence, 1 occurs twice, and 2 occurs once. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. For given three integers $a, b, c$, print the minimum value and the maximum value. Constraints * $-1,000,000,000 \leq a, b, c \leq 1,000,000,000$ Input The input is given in the following format. $a \; b \; c\;$ Three integers $a, b, c$ are given in a line. Output Print the minimum and maximum values separated by a space in a line. Example Input 4 5 3 Output 3 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with? Input The first line contains two integers n and k (1 ≤ n ≤ 200 000, 0 ≤ k ≤ n) — the number of digits in the decimal representation of S and the maximum allowed number of changed digits. The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes. Output Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits. Examples Input 5 3 51528 Output 10028 Input 3 2 102 Output 100 Input 1 1 1 Output 0 Note A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1. Constraints * 1\leq N,K\leq 100 * N and K are integers. Input Input is given from Standard Input in the following format: N K Output If we can choose K integers as above, print `YES`; otherwise, print `NO`. Examples Input 3 2 Output YES Input 5 5 Output NO Input 31 10 Output YES Input 10 90 Output NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Chef has prepared the appetizers in the shapes of letters to spell a special message for the guests. There are n appetizers numbered from 0 to n-1 such that if the appetizers are arrayed in this order, they will display the message. The Chef plans to display them in this order on a table that can be viewed by all guests as they enter. The appetizers will only be served once all guests are seated. The appetizers are not necessarily finished in the same order as they are numbered. So, when an appetizer is finished the Chef will write the number on a piece of paper and place it beside the appetizer on a counter between the kitchen and the restaurant. A server will retrieve this appetizer and place it in the proper location according to the number written beside it. The Chef has a penchant for binary numbers. The number of appetizers created is a power of 2, say n = 2^{k}. Furthermore, he has written the number of the appetizer in binary with exactly k bits. That is, binary numbers with fewer than k bits are padded on the left with zeros so they are written with exactly k bits. Unfortunately, this has unforseen complications. A binary number still "looks" binary when it is written upside down. For example, the binary number "0101" looks like "1010" when read upside down and the binary number "110" looks like "011" (the Chef uses simple vertical lines to denote a 1 bit). The Chef didn't realize that the servers would read the numbers upside down so he doesn't rotate the paper when he places it on the counter. Thus, when the server picks up an appetizer they place it the location indexed by the binary number when it is read upside down. You are given the message the chef intended to display and you are to display the message that will be displayed after the servers move all appetizers to their locations based on the binary numbers they read. ------ Input ------ The first line consists of a single integer T ≤ 25 indicating the number of test cases to follow. Each test case consists of a single line beginning with an integer 1 ≤ k ≤ 16 followed by a string of precisely 2^{k} characters. The integer and the string are separated by a single space. The string has no spaces and is composed only of lower case letters from a to z. ------ Output ------ For each test case you are to output the scrambled message on a single line. ----- Sample Input 1 ------ 2 2 chef 4 enjoyourapplepie ----- Sample Output 1 ------ cehf eayejpuinpopolre Read the inputs from stdin solve the problem and write the answer to stdout (do 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 observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i. There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j. Obs. i is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road. Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road. How many good observatories are there? -----Constraints----- - 2 \leq N \leq 10^5 - 1 \leq M \leq 10^5 - 1 \leq H_i \leq 10^9 - 1 \leq A_i,B_i \leq N - A_i \neq B_i - Multiple roads may connect the same pair of observatories. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N M H_1 H_2 ... H_N A_1 B_1 A_2 B_2 : A_M B_M -----Output----- Print the number of good observatories. -----Sample Input----- 4 3 1 2 3 4 1 3 2 3 2 4 -----Sample Output----- 2 - From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good. - From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good. - From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good. - From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good. Thus, the good observatories are Obs. 3 and 4, so there are two good observatories. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 is a positive integer L. Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L. -----Constraints----- - 1 ≤ L ≤ 1000 - L is an integer. -----Input----- Input is given from Standard Input in the following format: L -----Output----- Print the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L. Your output is considered correct if its absolute or relative error from our answer is at most 10^{-6}. -----Sample Input----- 3 -----Sample Output----- 1.000000000000 For example, a rectangular cuboid whose dimensions are 0.8, 1, and 1.2 has a volume of 0.96. On the other hand, if the dimensions are 1, 1, and 1, the volume of the rectangular cuboid is 1, which is greater. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $(0, 0)$ on an infinite grid. You also have the sequence of instructions of this robot. It is written as the string $s$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $(x, y)$ right now, he can move to one of the adjacent cells (depending on the current instruction). If the current instruction is 'L', then the robot can move to the left to $(x - 1, y)$; if the current instruction is 'R', then the robot can move to the right to $(x + 1, y)$; if the current instruction is 'U', then the robot can move to the top to $(x, y + 1)$; if the current instruction is 'D', then the robot can move to the bottom to $(x, y - 1)$. You've noticed the warning on the last page of the manual: if the robot visits some cell (except $(0, 0)$) twice then it breaks. So the sequence of instructions is valid if the robot starts in the cell $(0, 0)$, performs the given instructions, visits no cell other than $(0, 0)$ two or more times and ends the path in the cell $(0, 0)$. Also cell $(0, 0)$ should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: "UD", "RL", "UUURULLDDDDLDDRRUU", and the following are considered invalid: "U" (the endpoint is not $(0, 0)$) and "UUDD" (the cell $(0, 1)$ is visited twice). The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain. Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric). You have to answer $q$ independent test cases. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 2 \cdot 10^4$) — the number of test cases. The next $q$ lines contain test cases. The $i$-th test case is given as the string $s$ consisting of at least $1$ and no more than $10^5$ characters 'L', 'R', 'U' and 'D' — the initial sequence of instructions. It is guaranteed that the sum of $|s|$ (where $|s|$ is the length of $s$) does not exceed $10^5$ over all test cases ($\sum |s| \le 10^5$). -----Output----- For each test case print the answer on it. In the first line print the maximum number of remaining instructions. In the second line print the valid sequence of remaining instructions $t$ the robot has to perform. The moves are performed from left to right in the order of the printed sequence. If there are several answers, you can print any. If the answer is $0$, you are allowed to print an empty line (but you can don't print it). -----Example----- Input 6 LRU DURLDRUDRULRDURDDL LRUDDLRUDRUL LLLLRRRR URDUR LLL Output 2 LR 14 RUURDDDDLLLUUR 12 ULDDDRRRUULL 2 LR 2 UD 0 -----Note----- There are only two possible answers in the first test case: "LR" and "RL". The picture corresponding to the second test case: [Image] Note that the direction of traverse does not matter Another correct answer to the third test case: "URDDLLLUURDR". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters. Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (a_{i}) represents the number of meters the guest is going to take up if he sits at the restaurant table. Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than p. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table. Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible n! orders of guests in the queue. Help Maxim, calculate this number. -----Input----- The first line contains integer n (1 ≤ n ≤ 50) — the number of guests in the restaurant. The next line contains integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 50) — the guests' sizes in meters. The third line contains integer p (1 ≤ p ≤ 50) — the table's length in meters. The numbers in the lines are separated by single spaces. -----Output----- In a single line print a real number — the answer to the problem. The answer will be considered correct, if the absolute or relative error doesn't exceed 10^{ - 4}. -----Examples----- Input 3 1 2 3 3 Output 1.3333333333 -----Note----- In the first sample the people will come in the following orders: (1, 2, 3) — there will be two people in the restaurant; (1, 3, 2) — there will be one person in the restaurant; (2, 1, 3) — there will be two people in the restaurant; (2, 3, 1) — there will be one person in the restaurant; (3, 1, 2) — there will be one person in the restaurant; (3, 2, 1) — there will be one person in the restaurant. In total we get (2 + 1 + 2 + 1 + 1 + 1) / 6 = 8 / 6 = 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. British mathematician John Littlewood once said about Indian mathematician Srinivasa Ramanujan that "every positive integer was one of his personal friends." It turns out that positive integers can also be friends with each other! You are given an array a of distinct positive integers. Define a subarray a_i, a_{i+1}, …, a_j to be a friend group if and only if there exists an integer m ≥ 2 such that a_i mod m = a_{i+1} mod m = … = a_j mod m, where x mod y denotes the remainder when x is divided by y. Your friend Gregor wants to know the size of the largest friend group in a. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 2⋅ 10^4). Each test case begins with a line containing the integer n (1 ≤ n ≤ 2 ⋅ 10^5), the size of the array a. The next line contains n positive integers a_1, a_2, …, a_n (1 ≤ a_i ≤ {10}^{18}), representing the contents of the array a. It is guaranteed that all the numbers in a are distinct. It is guaranteed that the sum of n over all test cases is less than 2⋅ 10^5. Output Your output should consist of t lines. Each line should consist of a single integer, the size of the largest friend group in a. Example Input 4 5 1 5 2 4 6 4 8 2 5 10 2 1000 2000 8 465 55 3 54 234 12 45 78 Output 3 3 2 6 Note In the first test case, the array is [1,5,2,4,6]. The largest friend group is [2,4,6], since all those numbers are congruent to 0 modulo 2, so m=2. In the second test case, the array is [8,2,5,10]. The largest friend group is [8,2,5], since all those numbers are congruent to 2 modulo 3, so m=3. In the third case, the largest friend group is [1000,2000]. There are clearly many possible values of m that work. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Our hardworking chef is bored of sleeping in his restaurants. He has decided to settle down. The first thing he must do is to find a suitable location to build a palatial home. Think of the city as a two-dimensional grid. There are N restaurants in the city. Each of the chef's restaurant is a point denoted by (X , Y). A house can be located at a grid point (R, S) if the sum of the distances between this point and each of the restaurants is as small as possible. Find the number of possible house locations in the city to help out chef build a home. More than one restaurant can be located at the same point. Houses and restaurants can be located at the same point. Every house must have integer co-ordinates. In other words, R and S are integers. The distance between two points (A,B) and (C,D) is |A-C| + |B-D|. Here |X| is the absolute function. ------ Input ------ First line in the input contains T, number of test cases. First line of each test case contains N, number of restaurants. Each of the next N lines contain two integers X and Y separated by a space. T ≤ 100 N ≤ 10^{3} -10^{8} ≤ X ≤10^{8} -10^{8} ≤ Y ≤10^{8} ------ Output ------ The number of possible locations (grid points) where houses can be built. ----- Sample Input 1 ------ 3 5 0 0 -1 0 1 0 0 1 0 -1 5 31 11 30 -41 20 14 25 18 25 38 2 0 0 1 1 ----- Sample Output 1 ------ 1 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. Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has a_{i} apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length). Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses. In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things: eat the apples, if the node is a leaf. move the apples to one of the children, if the node is non-leaf. Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v. Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u, v) and (v, u) are considered to be the same pair. -----Input----- The first line will contain one integer n (2 ≤ n ≤ 10^5) — the number of nodes in the apple tree. The second line will contain n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^7) — the number of apples on each node of the tree. The third line will contain n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_{i} ≤ n) — the parent of each node of the tree. Node i has parent p_{i} (for 2 ≤ i ≤ n). Node 1 is the root of the tree. It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity. -----Output----- On a single line, print the number of different pairs of nodes (u, v), u ≠ v such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u, v) and (v, u) are considered to be the same pair. -----Examples----- Input 3 2 2 3 1 1 Output 1 Input 3 1 2 3 1 1 Output 0 Input 8 7 2 2 5 4 3 1 1 1 1 1 4 4 5 6 Output 4 -----Note----- In the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move. In the second sample, There is no swap that will make Sagheer win the game. Note that Sagheer must make the swap even if he can win with the initial tree. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. To participate in a prize draw each one gives his/her firstname. Each letter of a firstname has a value which is its rank in the English alphabet. `A` and `a` have rank `1`, `B` and `b` rank `2` and so on. The *length* of the firstname is added to the *sum* of these ranks hence a number `som`. An array of random weights is linked to the firstnames and each `som` is multiplied by its corresponding weight to get what they call a `winning number`. Example: ``` names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH" weights: [1, 4, 4, 5, 2, 1] PauL -> som = length of firstname + 16 + 1 + 21 + 12 = 4 + 50 -> 54 The *weight* associated with PauL is 2 so PauL's *winning number* is 54 * 2 = 108. ``` Now one can sort the firstnames in decreasing order of the `winning numbers`. When two people have the same `winning number` sort them *alphabetically* by their firstnames. ### Task: - parameters: `st` a string of firstnames, `we` an array of weights, `n` a rank - return: the firstname of the participant whose rank is `n` (ranks are numbered from 1) ### Example: ``` names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH" weights: [1, 4, 4, 5, 2, 1] n: 4 The function should return: "PauL" ``` # Notes: - The weight array is at least as long as the number of names, it can be longer. - If `st` is empty return "No participants". - If n is greater than the number of participants then return "Not enough participants". - See Examples Test Cases for more examples. Write your solution by modifying this code: ```python def rank(st, we, n): ``` Your solution should implemented in the function "rank". 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. It started as a discussion with a friend, who didn't fully grasp some way of setting defaults, but I thought the idea was cool enough for a beginner kata: binary `OR` each matching element of two given arrays (or lists, if you do it in Python; vectors in c++) of integers and give the resulting ORed array [starts to sound like a tonguetwister, doesn't it?]. If one array is shorter than the other, use the optional third parametero (defaulted to `0`) to `OR` the unmatched elements. For example: ```python or_arrays([1,2,3],[1,2,3]) == [1,2,3] or_arrays([1,2,3],[4,5,6]) == [5,7,7] or_arrays([1,2,3],[1,2]) == [1,2,3] or_arrays([1,2],[1,2,3]) == [1,2,3] or_arrays([1,2,3],[1,2,3],3) == [1,2,3] ``` Write your solution by modifying this code: ```python def or_arrays(a, b, filler=0): ``` Your solution should implemented in the function "or_arrays". 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. Compute A + B. Constraints * -1000 ≤ A, B ≤ 1000 Input The input will consist of a series of pairs of integers A and B separated by a space, one pair of integers per line. The input will be terminated by EOF. Output For each pair of input integers A and B, you must output the sum of A and B in one line. Example Input 1 2 10 5 100 20 Output 3 15 120 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 city of Saint Petersburg, a day lasts for $2^{100}$ minutes. From the main station of Saint Petersburg, a train departs after $1$ minute, $4$ minutes, $16$ minutes, and so on; in other words, the train departs at time $4^k$ for each integer $k \geq 0$. Team BowWow has arrived at the station at the time $s$ and it is trying to count how many trains have they missed; in other words, the number of trains that have departed strictly before time $s$. For example if $s = 20$, then they missed trains which have departed at $1$, $4$ and $16$. As you are the only one who knows the time, help them! Note that the number $s$ will be given you in a binary representation without leading zeroes. -----Input----- The first line contains a single binary number $s$ ($0 \leq s < 2^{100}$) without leading zeroes. -----Output----- Output a single number — the number of trains which have departed strictly before the time $s$. -----Examples----- Input 100000000 Output 4 Input 101 Output 2 Input 10100 Output 3 -----Note----- In the first example $100000000_2 = 256_{10}$, missed trains have departed at $1$, $4$, $16$ and $64$. In the second example $101_2 = 5_{10}$, trains have departed at $1$ and $4$. The third example is explained in the statements. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is a vertex number $1$. A tree is a connected undirected graph with $n-1$ edges. You are given $m$ queries. The $i$-th query consists of the set of $k_i$ distinct vertices $v_i[1], v_i[2], \dots, v_i[k_i]$. Your task is to say if there is a path from the root to some vertex $u$ such that each of the given $k$ vertices is either belongs to this path or has the distance $1$ to some vertex of this path. -----Input----- The first line of the input contains two integers $n$ and $m$ ($2 \le n \le 2 \cdot 10^5$, $1 \le m \le 2 \cdot 10^5$) — the number of vertices in the tree and the number of queries. Each of the next $n-1$ lines describes an edge of the tree. Edge $i$ is denoted by two integers $u_i$ and $v_i$, the labels of vertices it connects $(1 \le u_i, v_i \le n, u_i \ne v_i$). It is guaranteed that the given edges form a tree. The next $m$ lines describe queries. The $i$-th line describes the $i$-th query and starts with the integer $k_i$ ($1 \le k_i \le n$) — the number of vertices in the current query. Then $k_i$ integers follow: $v_i[1], v_i[2], \dots, v_i[k_i]$ ($1 \le v_i[j] \le n$), where $v_i[j]$ is the $j$-th vertex of the $i$-th query. It is guaranteed that all vertices in a single query are distinct. It is guaranteed that the sum of $k_i$ does not exceed $2 \cdot 10^5$ ($\sum\limits_{i=1}^{m} k_i \le 2 \cdot 10^5$). -----Output----- For each query, print the answer — "YES", if there is a path from the root to some vertex $u$ such that each of the given $k$ vertices is either belongs to this path or has the distance $1$ to some vertex of this path and "NO" otherwise. -----Example----- Input 10 6 1 2 1 3 1 4 2 5 2 6 3 7 7 8 7 9 9 10 4 3 8 9 10 3 2 4 6 3 2 1 5 3 4 8 2 2 6 10 3 5 4 7 Output YES YES YES YES NO NO -----Note----- The picture corresponding to the example: [Image] Consider the queries. The first query is $[3, 8, 9, 10]$. The answer is "YES" as you can choose the path from the root $1$ to the vertex $u=10$. Then vertices $[3, 9, 10]$ belong to the path from $1$ to $10$ and the vertex $8$ has distance $1$ to the vertex $7$ which also belongs to this path. The second query is $[2, 4, 6]$. The answer is "YES" as you can choose the path to the vertex $u=2$. Then the vertex $4$ has distance $1$ to the vertex $1$ which belongs to this path and the vertex $6$ has distance $1$ to the vertex $2$ which belongs to this path. The third query is $[2, 1, 5]$. The answer is "YES" as you can choose the path to the vertex $u=5$ and all vertices of the query belong to this path. The fourth query is $[4, 8, 2]$. The answer is "YES" as you can choose the path to the vertex $u=9$ so vertices $2$ and $4$ both have distance $1$ to the vertex $1$ which belongs to this path and the vertex $8$ has distance $1$ to the vertex $7$ which belongs to this path. The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex $u$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)? -----Input----- The first line of the input contains two integers s and x (2 ≤ s ≤ 10^12, 0 ≤ x ≤ 10^12), the sum and bitwise xor of the pair of positive integers, respectively. -----Output----- Print a single integer, the number of solutions to the given conditions. If no solutions exist, print 0. -----Examples----- Input 9 5 Output 4 Input 3 3 Output 2 Input 5 2 Output 0 -----Note----- In the first sample, we have the following solutions: (2, 7), (3, 6), (6, 3), (7, 2). In the second sample, the only solutions are (1, 2) and (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. Koto Municipal Subway Koto Municipal Subway Koto City is a famous city whose roads are in a grid pattern, as shown in the figure below. The roads extending from north to south and the roads extending from east to west are lined up at intervals of 1 km each. Let Koto station at the southwestern intersection of Koto city be (0, 0), and mark x km east and y km north from it as (x, y) (0 ≤ x, y). ). <image> In anticipation of an increase in tourists due to the Olympic Games to be held five years later, the city has decided to build a new subway line starting from Koto station. Currently, we are planning to lay a rail to Shin-Koto station, which will be newly constructed as the next station after Koto station. The rail will be laid straight from Koto station to Shin-Koto station. Therefore, when the location of Shin-Koto station is (x, y), the length of the rail is √ (x2 + y2). The cost of laying the rail is the same as the length of the laid rail. Even if the rail length is a decimal number such as 1.5km, the cost is also 1.5. The location (x, y) of Shin-Koto station has not been decided yet, and we plan to make it a location that meets the following conditions. * It is an intersection. That is, x and y are integers, respectively. * The shortest distance walked along the road from Koto station is exactly D. That is, x + y = D is satisfied. Among the above two conditions, select the location of Shin-Koto station so that the difference between the rail budget E and the rail cost set by the city | √ (x2 + y2) --E | is minimized. Here, | A | represents the absolute value of A. Your job is to create a program that outputs the difference between the cost and budget for laying rails when the Shin-Koto station was constructed as described above. Input The input consists of multiple data sets, and the number of data sets contained in one input is 100 or less. The format of each data set is as follows. > D E D (1 ≤ D ≤ 100) is an integer that represents the shortest distance when walking along the road from Koto station to Shin-Koto station. E (1 ≤ E ≤ 100) is an integer representing the budget for rail construction. The end of the input is indicated by a line of two zeros separated by a blank. Output For each data set, output the difference between the cost and budget when laying the rail so as to satisfy the problem condition in one line. The answer must have an absolute error greater than 10-3. Note that if you do not output a line break at the end of each line, or if you output unnecessary characters, it will be judged as an incorrect answer. Sample Input twenty one 7 5 7 6 7 7 76 5 8 41 0 0 Output for Sample Input 0.4142135624 0 0.0827625303 0 48.7401153702 33 Hint In the first data set, as shown in the figure below, an intersection 2 km along the road from Koto station is a candidate for a place to build Shin-Koto station. <image> When Shin-Koto station is constructed at each intersection, the difference between the cost for laying the rail and budget 1 is as follows. * (2, 0): | √ (22 + 02) --1 | = 1.0 * (1, 1): | √ (12 + 12) --1 | = 0.4142135623 ... * (0, 2): | √ (02 + 22) --1 | = 1.0 Therefore, the difference between the cost and the budget is minimized when the construction is done in (1, 1). Example Input 2 1 7 5 7 6 7 7 76 5 8 41 0 0 Output 0.4142135624 0 0.0827625303 0 48.7401153702 33 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Failed Sort - Bug Fixing #4 Oh no, Timmy's Sort doesn't seem to be working? Your task is to fix the sortArray function to sort all numbers in ascending order Write your solution by modifying this code: ```python def sort_array(value): ``` Your solution should implemented in the function "sort_array". 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. There are N slimes standing on a number line. The i-th slime from the left is at position x_i. It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}. Niwango will perform N-1 operations. The i-th operation consists of the following procedures: * Choose an integer k between 1 and N-i (inclusive) with equal probability. * Move the k-th slime from the left, to the position of the neighboring slime to the right. * Fuse the two slimes at the same position into one slime. Find the total distance traveled by the slimes multiplied by (N-1)! (we can show that this value is an integer), modulo (10^{9}+7). If a slime is born by a fuse and that slime moves, we count it as just one slime. Constraints * 2 \leq N \leq 10^{5} * 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9} * x_i is an integer. Input Input is given from Standard Input in the following format: N x_1 x_2 \ldots x_N Output Print the answer. Examples Input 3 1 2 3 Output 5 Input 12 161735902 211047202 430302156 450968417 628894325 707723857 731963982 822804784 880895728 923078537 971407775 982631932 Output 750927044 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A binary string is a string that consists of characters $0$ and $1$. Let $\operatorname{MEX}$ of a binary string be the smallest digit among $0$, $1$, or $2$ that does not occur in the string. For example, $\operatorname{MEX}$ of $001011$ is $2$, because $0$ and $1$ occur in the string at least once, $\operatorname{MEX}$ of $1111$ is $0$, because $0$ and $2$ do not occur in the string and $0 < 2$. A binary string $s$ is given. You should cut it into any number of substrings such that each character is in exactly one substring. It is possible to cut the string into a single substring — the whole string. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. What is the minimal sum of $\operatorname{MEX}$ of all substrings pieces can be? -----Input----- The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Description of the test cases follows. Each test case contains a single binary string $s$ ($1 \le |s| \le 10^5$). It's guaranteed that the sum of lengths of $s$ over all test cases does not exceed $10^5$. -----Output----- For each test case print a single integer — the minimal sum of $\operatorname{MEX}$ of all substrings that it is possible to get by cutting $s$ optimally. -----Examples----- Input 6 01 1111 01100 101 0000 01010 Output 1 0 2 1 1 2 -----Note----- In the first test case the minimal sum is $\operatorname{MEX}(0) + \operatorname{MEX}(1) = 1 + 0 = 1$. In the second test case the minimal sum is $\operatorname{MEX}(1111) = 0$. In the third test case the minimal sum is $\operatorname{MEX}(01100) = 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. A Bingo game is played by one gamemaster and several players. At the beginning of a game, each player is given a card with M × M numbers in a matrix (See Figure 10). <image> As the game proceeds, the gamemaster announces a series of numbers one by one. Each player punches a hole in his card on the announced number, if any. When at least one 'Bingo' is made on the card, the player wins and leaves the game. The 'Bingo' means that all the M numbers in a line are punched vertically, horizontally or diagonally (See Figure 11). <image> The gamemaster continues announcing numbers until all the players make a Bingo. In the ordinary Bingo games, the gamemaster chooses numbers by a random process and has no control on them. But in this problem the gamemaster knows all the cards at the beginning of the game and controls the game by choosing the number sequence to be announced at his will. Specifically, he controls the game to satisfy the following condition. Cardi makes a Bingo no later than Cardj, for i < j. (*) Figure 12 shows an example of how a game proceeds. The gamemaster cannot announce '5' before '16', because Card4 makes a Bingo before Card2 and Card3, violating the condition (*). Your job is to write a program which finds the minimum length of such sequence of numbers for the given cards. Input The input consists of multiple datasets. The format of each dataset is as follows. <image> All data items are integers. P is the number of the cards, namely the number of the players. M is the number of rows and the number of columns of the matrix on each card. Nkij means the number written at the position (i, j) on the k-th card. If (i, j) ≠ (p, q), then Nkij ≠ Nkpq. The parameters P, M, and N satisfy the conditions 2 ≤ P ≤ 4, 3 ≤ M ≤ 4, and 0 ≤ Nkij ≤ 99. The end of the input is indicated by a line containing two zeros separated by a space. It is not a dataset. Output For each dataset, output the minimum length of the sequence of numbers which satisfy the condition (*). Output a zero if there are no such sequences. Output for each dataset must be printed on a separate line. Example Input 4 3 10 25 11 20 6 2 1 15 23 5 21 3 12 23 17 7 26 2 8 18 4 22 13 27 16 5 11 19 9 24 2 11 5 14 28 16 4 3 12 13 20 24 28 32 15 16 17 12 13 21 25 29 33 16 17 18 12 13 22 26 30 34 17 18 15 12 13 23 27 31 35 18 15 16 4 3 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 41 42 43 44 45 46 47 48 49 4 4 2 6 9 21 15 23 17 31 33 12 25 4 8 24 13 36 22 18 27 26 35 28 3 7 11 20 38 16 5 32 14 29 26 7 16 29 27 3 38 14 18 28 20 32 22 35 11 5 36 13 24 8 4 25 12 33 31 17 23 15 21 9 6 2 0 0 Output 5 4 12 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. The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness". The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct. A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves. Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case? Input The first line contains a positive integer n (1 ≤ n ≤ 100). It is the number of questions in the test. The second line contains space-separated n positive integers ai (1 ≤ ai ≤ 109), the number of answer variants to question i. Output Print a single number — the minimal number of clicks needed to pass the test it the worst-case scenario. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 1 1 Output 2 Input 2 2 2 Output 5 Input 1 10 Output 10 Note Note to the second sample. In the worst-case scenario you will need five clicks: * the first click selects the first variant to the first question, this answer turns out to be wrong. * the second click selects the second variant to the first question, it proves correct and we move on to the second question; * the third click selects the first variant to the second question, it is wrong and we go back to question 1; * the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question; * the fifth click selects the second variant to the second question, it proves correct, the test is finished. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Arpa is taking a geometry exam. Here is the last problem of the exam. You are given three points a, b, c. Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c. Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not. -----Input----- The only line contains six integers a_{x}, a_{y}, b_{x}, b_{y}, c_{x}, c_{y} (|a_{x}|, |a_{y}|, |b_{x}|, |b_{y}|, |c_{x}|, |c_{y}| ≤ 10^9). It's guaranteed that the points are distinct. -----Output----- Print "Yes" if the problem has a solution, "No" otherwise. You can print each letter in any case (upper or lower). -----Examples----- Input 0 1 1 1 1 0 Output Yes Input 1 1 0 0 1000 1000 Output No -----Note----- In the first sample test, rotate the page around (0.5, 0.5) by $90^{\circ}$. In the second sample test, you can't find any solution. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter. -----Constraints----- - 2\leq K\leq 100 - K is an integer. -----Input----- Input is given from Standard Input in the following format: K -----Output----- Print the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). -----Sample Input----- 3 -----Sample Output----- 2 Two pairs can be chosen: (2,1) and (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. There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos. The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. Input The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105). Output Output a single integer — the optimal number of visible kangaroos. Examples Input 8 2 5 7 6 9 8 4 2 Output 5 Input 8 9 1 6 2 6 5 8 3 Output 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k. -----Input----- The only line contains two integers n and k (1 ≤ n, k ≤ 10^9). -----Output----- Print the smallest integer x > n, so it is divisible by the number k. -----Examples----- Input 5 3 Output 6 Input 25 13 Output 26 Input 26 13 Output 39 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 is not good at problems about trees in programming contests, and Aoki is helping him practice. First, Takahashi created a tree with N vertices numbered 1 through N, and wrote 0 at each edge. Then, Aoki gave him M queries. The i-th of them is as follows: * Increment the number written at each edge along the path connecting vertices a_i and b_i, by one. After Takahashi executed all of the queries, he told Aoki that, for every edge, the written number became an even number. However, Aoki forgot to confirm that the graph Takahashi created was actually a tree, and it is possible that Takahashi made a mistake in creating a tree or executing queries. Determine whether there exists a tree that has the property mentioned by Takahashi. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ M ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print `YES` if there exists a tree that has the property mentioned by Takahashi; print `NO` otherwise. Examples Input 4 4 1 2 2 4 1 3 3 4 Output YES Input 5 5 1 2 3 5 5 1 3 4 2 3 Output NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The city of Fishtopia can be imagined as a grid of 4 rows and an odd number of columns. It has two main villages; the first is located at the top-left cell (1,1), people who stay there love fishing at the Tuna pond at the bottom-right cell (4, n). The second village is located at (4, 1) and its people love the Salmon pond at (1, n). The mayor of Fishtopia wants to place k hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells. A person can move from one cell to another if those cells are not occupied by hotels and share a side. Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? Input The first line of input contain two integers, n and k (3 ≤ n ≤ 99, 0 ≤ k ≤ 2×(n-2)), n is odd, the width of the city, and the number of hotels to be placed, respectively. Output Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra 4 lines that describe the city, each line should have n characters, each of which is "#" if that cell has a hotel on it, or "." if not. Examples Input 7 2 Output YES ....... .#..... .#..... ....... Input 5 3 Output YES ..... .###. ..... ..... Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be... To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains <image> distinct theorems. Besides, no theorem is mentioned in more than one card (that is, <image> theorems won't be mentioned in any card). During the exam several students may get the same card. We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 100) — the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 ≤ ai ≤ 100), the i-th number (1 ≤ i ≤ n) corresponds to Vasya's proficiency in the i-th theorem. The third line contains number q (0 ≤ q ≤ 100) — the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card: <image> integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation). Output Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6. Examples Input 7 3 7 15 0 19 10 5 12 2 1 6 7 4 Output 5.0000000000 15.5000000000 Input 4 2 10 8 1 17 2 2 3 3 2 Output 4.5000000000 13.5000000000 Note Let's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5). The ⌊ x⌋ operation denotes taking integer part of real number x (rounding down). Read the inputs from stdin solve the problem and write the answer to stdout (do 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. If you write a solution in Python, then prefer to send it in PyPy to speed up execution time. A session has begun at Beland State University. Many students are taking exams. Polygraph Poligrafovich is going to examine a group of $n$ students. Students will take the exam one-by-one in order from $1$-th to $n$-th. Rules of the exam are following: The $i$-th student randomly chooses a ticket. if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam. if the student finds the ticket easy, he spends exactly $t_i$ minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student. The duration of the whole exam for all students is $M$ minutes ($\max t_i \le M$), so students at the end of the list have a greater possibility to run out of time to pass the exam. For each student $i$, you should count the minimum possible number of students who need to fail the exam so the $i$-th student has enough time to pass the exam. For each student $i$, find the answer independently. That is, if when finding the answer for the student $i_1$ some student $j$ should leave, then while finding the answer for $i_2$ ($i_2>i_1$) the student $j$ student does not have to go home. -----Input----- The first line of the input contains two integers $n$ and $M$ ($1 \le n \le 2 \cdot 10^5$, $1 \le M \le 2 \cdot 10^7$) — the number of students and the total duration of the exam in minutes, respectively. The second line of the input contains $n$ integers $t_i$ ($1 \le t_i \le 100$) — time in minutes that $i$-th student spends to answer to a ticket. It's guaranteed that all values of $t_i$ are not greater than $M$. -----Output----- Print $n$ numbers: the $i$-th number must be equal to the minimum number of students who have to leave the exam in order to $i$-th student has enough time to pass the exam. -----Examples----- Input 7 15 1 2 3 4 5 6 7 Output 0 0 0 0 0 2 3 Input 5 100 80 40 40 40 60 Output 0 1 1 2 3 -----Note----- The explanation for the example 1. Please note that the sum of the first five exam times does not exceed $M=15$ (the sum is $1+2+3+4+5=15$). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are $0$. In order for the $6$-th student to pass the exam, it is necessary that at least $2$ students must fail it before (for example, the $3$-rd and $4$-th, then the $6$-th will finish its exam in $1+2+5+6=14$ minutes, which does not exceed $M$). In order for the $7$-th student to pass the exam, it is necessary that at least $3$ students must fail it before (for example, the $2$-nd, $5$-th and $6$-th, then the $7$-th will finish its exam in $1+3+4+7=15$ minutes, which does not exceed $M$). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Some new animals have arrived at the zoo. The zoo keeper is concerned that perhaps the animals do not have the right tails. To help her, you must correct the broken function to make sure that the second argument (tail), is the same as the last letter of the first argument (body) - otherwise the tail wouldn't fit! If the tail is right return true, else return false. The arguments will always be strings, and normal letters. Write your solution by modifying this code: ```python def correct_tail(body, tail): ``` Your solution should implemented in the function "correct_tail". 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. Dima got into number sequences. Now he's got sequence a_1, a_2, ..., a_{n}, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence: f(0) = 0; f(2·x) = f(x); f(2·x + 1) = f(x) + 1. Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤ n) are there, such that f(a_{i}) = f(a_{j}). Help him, count the number of such pairs. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5). The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). The numbers in the lines are separated by single spaces. -----Output----- In a single line print the answer to the problem. Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 3 1 2 4 Output 3 Input 3 5 3 1 Output 1 -----Note----- In the first sample any pair (i, j) will do, so the answer is 3. In the second sample only pair (1, 2) will do. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese , Russian and Vietnamese as well. Chef belongs to a very rich family which owns many gold mines. Today, he brought N gold coins and decided to form a triangle using these coins. Isn't it strange? Chef has a unusual way of forming a triangle using gold coins, which is described as follows: He puts 1 coin in the 1^{st} row. then puts 2 coins in the 2^{nd} row. then puts 3 coins in the 3^{rd} row. and so on as shown in the given figure. Chef is interested in forming a triangle with maximum possible height using at most N coins. Can you tell him the maximum possible height of the triangle? ------ Input ------ The first line of input contains a single integer T denoting the number of test cases. The first and the only line of each test case contains an integer N denoting the number of gold coins Chef has. ------ Output ------ For each test case, output a single line containing an integer corresponding to the maximum possible height of the triangle that Chef can get. ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ N ≤ 10^{9}$ ------ Subtasks ------ $Subtask 1 (48 points) : 1 ≤ N ≤ 10^{5}$ $Subtask 2 (52 points) : 1 ≤ N ≤ 10^{9}$ ----- Sample Input 1 ------ 3 3 5 7 ----- Sample Output 1 ------ 2 2 3 ----- explanation 1 ------ Test 1: Chef can't form a triangle with height > 2 as it requires atleast 6 gold coins. Test 2: Chef can't form a triangle with height > 2 as it requires atleast 6 gold coins. Test 3: Chef can't form a triangle with height > 3 as it requires atleast 10 gold coins. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 goal in this kata is to implement a difference function, which subtracts one list from another and returns the result. It should remove all values from list `a`, which are present in list `b`. ```python array_diff([1,2],[1]) == [2] ``` If a value is present in `b`, all of its occurrences must be removed from the other: ```python array_diff([1,2,2,2,3],[2]) == [1,3] ``` ~~~ if:c NOTE: In C, assign return array length to pointer *z ~~~ Write your solution by modifying this code: ```python def array_diff(a, b): ``` Your solution should implemented in the function "array_diff". 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. Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins. Across all the sets Misha scored a points in total, and Vanya scored b points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible. Note that the game consisted of several complete sets. -----Input----- The first line contains three space-separated integers k, a and b (1 ≤ k ≤ 10^9, 0 ≤ a, b ≤ 10^9, a + b > 0). -----Output----- If the situation is impossible, print a single number -1. Otherwise, print the maximum possible number of sets. -----Examples----- Input 11 11 5 Output 1 Input 11 2 3 Output -1 -----Note----- Note that the rules of the game in this problem differ from the real table tennis game, for example, the rule of "balance" (the winning player has to be at least two points ahead to win a set) has no power within the present problem. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 problem consists of three subproblems: for solving subproblem F1 you will receive 8 points, for solving subproblem F2 you will receive 15 points, and for solving subproblem F3 you will receive 10 points. Manao has developed a model to predict the stock price of a company over the next n days and wants to design a profit-maximizing trading algorithm to make use of these predictions. Unfortunately, Manao's trading account has the following restrictions: * It only allows owning either zero or one shares of stock at a time; * It only allows buying or selling a share of this stock once per day; * It allows a maximum of k buy orders over the next n days; For the purposes of this problem, we define a trade to a be the act of buying one share of stock on day i, then holding the stock until some day j > i at which point the share is sold. To restate the above constraints, Manao is permitted to make at most k non-overlapping trades during the course of an n-day trading period for which Manao's model has predictions about the stock price. Even though these restrictions limit the amount of profit Manao can make compared to what would be achievable with an unlimited number of trades or the ability to hold more than one share at a time, Manao still has the potential to make a lot of money because Manao's model perfectly predicts the daily price of the stock. For example, using this model, Manao could wait until the price is low, then buy one share and hold until the price reaches a high value, then sell for a profit, and repeat this process up to k times until n days have passed. Nevertheless, Manao is not satisfied by having a merely good trading algorithm, and wants to develop an optimal strategy for trading subject to these constraints. Help Manao achieve this goal by writing a program that will determine when to buy and sell stock to achieve the greatest possible profit during the n-day trading period subject to the above constraints. Input The first line contains two integers n and k, separated by a single space, with <image>. The i-th of the following n lines contains a single integer pi (0 ≤ pi ≤ 1012), where pi represents the price at which someone can either buy or sell one share of stock on day i. 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 F1 (8 points), n will be between 1 and 3000, inclusive. * In subproblem F2 (15 points), n will be between 1 and 100000, inclusive. * In subproblem F3 (10 points), n will be between 1 and 4000000, inclusive. Output For this problem, the program will only report the amount of the optimal profit, rather than a list of trades that can achieve this profit. Therefore, the program should print one line containing a single integer, the maximum profit Manao can achieve over the next n days with the constraints of starting with no shares on the first day of trading, always owning either zero or one shares of stock, and buying at most k shares over the course of the n-day trading period. Examples Input 10 2 2 7 3 9 8 7 9 7 1 9 Output 15 Input 10 5 2 7 3 9 8 7 9 7 1 9 Output 21 Note In the first example, the best trade overall is to buy at a price of 1 on day 9 and sell at a price of 9 on day 10 and the second best trade overall is to buy at a price of 2 on day 1 and sell at a price of 9 on day 4. Since these two trades do not overlap, both can be made and the profit is the sum of the profits of the two trades. Thus the trade strategy looks like this: 2 | 7 | 3 | 9 | 8 | 7 | 9 | 7 | 1 | 9 buy | | | sell | | | | | buy | sell The total profit is then (9 - 2) + (9 - 1) = 15. In the second example, even though Manao is allowed up to 5 trades there are only 4 profitable trades available. Making a fifth trade would cost Manao money so he only makes the following 4: 2 | 7 | 3 | 9 | 8 | 7 | 9 | 7 | 1 | 9 buy | sell | buy | sell | | buy | sell | | buy | sell The total profit is then (7 - 2) + (9 - 3) + (9 - 7) + (9 - 1) = 21. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem. You are given a binary table of size n × m. This table consists of symbols 0 and 1. You can make such operation: select 3 different cells that belong to one 2 × 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0). Your task is to make all symbols in the table equal to 0. You are allowed to make at most 3nm operations. You don't need to minimize the number of operations. It can be proved that it is always possible. Input The first line contains a single integer t (1 ≤ t ≤ 5000) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains two integers n, m (2 ≤ n, m ≤ 100). Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table. It is guaranteed that the sum of nm for all test cases does not exceed 20000. Output For each test case print the integer k (0 ≤ k ≤ 3nm) — the number of operations. In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 ≤ x_1, x_2, x_3 ≤ n, 1 ≤ y_1, y_2, y_3 ≤ m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong into some 2 × 2 square. Example Input 5 2 2 10 11 3 3 011 101 110 4 4 1111 0110 0110 1111 5 5 01011 11001 00010 11011 10000 2 3 011 101 Output 1 1 1 2 1 2 2 2 2 1 3 1 3 2 1 2 1 3 2 3 4 1 1 1 2 2 2 1 3 1 4 2 3 3 2 4 1 4 2 3 3 4 3 4 4 4 1 2 2 1 2 2 1 4 1 5 2 5 4 1 4 2 5 1 4 4 4 5 3 4 2 1 3 2 2 2 3 1 2 2 1 2 2 Note In the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0. In the second test case: * operation with cells (2, 1), (3, 1), (3, 2). After it the table will be: 011 001 000 * operation with cells (1, 2), (1, 3), (2, 3). After it the table will be: 000 000 000 In the fifth test case: * operation with cells (1, 3), (2, 2), (2, 3). After it the table will be: 010 110 * operation with cells (1, 2), (2, 1), (2, 2). After it the table will be: 000 000 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 finite set of integers X, let f(X)=\max X - \min X. Given are N integers A_1,...,A_N. We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over all those ways. Since the answer can be enormous, print it \bmod (10^9+7). -----Constraints----- - 1 \leq N \leq 10^5 - 1 \leq K \leq N - |A_i| \leq 10^9 -----Input----- Input is given from Standard Input in the following format: N K A_1 ... A_N -----Output----- Print the answer \bmod (10^9+7). -----Sample Input----- 4 2 1 1 3 4 -----Sample Output----- 11 There are six ways to choose S: \{1,1\},\{1,3\},\{1,4\},\{1,3\},\{1,4\}, \{3,4\} (we distinguish the two 1s). The value of f(S) for these choices are 0,2,3,2,3,1, respectively, for the total of 11. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function $g : \{1,2, \ldots, n \} \rightarrow \{1,2, \ldots, n \}$, that for any $x \in \{1,2, \ldots, n \}$ the formula g(g(x)) = g(x) holds. Let's denote as f^{(}k)(x) the function f applied k times to the value x. More formally, f^{(1)}(x) = f(x), f^{(}k)(x) = f(f^{(}k - 1)(x)) for each k > 1. You are given some function $f : \{1,2, \ldots, n \} \rightarrow \{1,2, \ldots, n \}$. Your task is to find minimum positive integer k such that function f^{(}k)(x) is idempotent. -----Input----- In the first line of the input there is a single integer n (1 ≤ n ≤ 200) — the size of function f domain. In the second line follow f(1), f(2), ..., f(n) (1 ≤ f(i) ≤ n for each 1 ≤ i ≤ n), the values of a function. -----Output----- Output minimum k such that function f^{(}k)(x) is idempotent. -----Examples----- Input 4 1 2 2 4 Output 1 Input 3 2 3 3 Output 2 Input 3 2 3 1 Output 3 -----Note----- In the first sample test function f(x) = f^{(1)}(x) is already idempotent since f(f(1)) = f(1) = 1, f(f(2)) = f(2) = 2, f(f(3)) = f(3) = 2, f(f(4)) = f(4) = 4. In the second sample test: function f(x) = f^{(1)}(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2; function f(x) = f^{(2)}(x) is idempotent since for any x it is true that f^{(2)}(x) = 3, so it is also true that f^{(2)}(f^{(2)}(x)) = 3. In the third sample test: function f(x) = f^{(1)}(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2; function f(f(x)) = f^{(2)}(x) isn't idempotent because f^{(2)}(f^{(2)}(1)) = 2 but f^{(2)}(1) = 3; function f(f(f(x))) = f^{(3)}(x) is idempotent since it is identity function: f^{(3)}(x) = x for any $x \in \{1,2,3 \}$ meaning that the formula f^{(3)}(f^{(3)}(x)) = f^{(3)}(x) also holds. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. How Many Divisors? Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b. Constraints * 1 ≤ a, b, c ≤ 10000 * a ≤ b Input Three integers a, b and c are given in a line separated by a single space. Output Print the number of divisors in a line. Example Input 5 14 80 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. Gilbert is the network admin of Ginkgo company. His boss is mad about the messy network cables on the floor. He finally walked up to Gilbert and asked the lazy network admin to illustrate how computers and switches are connected. Since he is a programmer, he is very reluctant to move throughout the office and examine cables and switches with his eyes. He instead opted to get this job done by measurement and a little bit of mathematical thinking, sitting down in front of his computer all the time. Your job is to help him by writing a program to reconstruct the network topology from measurements. There are a known number of computers and an unknown number of switches. Each computer is connected to one of the switches via a cable and to nothing else. Specifically, a computer is never connected to another computer directly, or never connected to two or more switches. Switches are connected via cables to form a tree (a connected undirected graph with no cycles). No switches are ‘useless.’ In other words, each switch is on the path between at least one pair of computers. All in all, computers and switches together form a tree whose leaves are computers and whose internal nodes switches (See Figure 9). Gilbert measures the distances between all pairs of computers. The distance between two com- puters is simply the number of switches on the path between the two, plus one. Or equivalently, it is the number of cables used to connect them. You may wonder how Gilbert can actually obtain these distances solely based on measurement. Well, he can do so by a very sophisticated statistical processing technique he invented. Please do not ask the details. You are therefore given a matrix describing distances between leaves of a tree. Your job is to construct the tree from it. Input The input is a series of distance matrices, followed by a line consisting of a single '0'. Each distance matrix is formatted as follows. N a11 a12 ... a1N a21 a22 ... a2N . . . . . . . . . . . . aN1 aN2 ... aNN <image> N is the size, i.e. the number of rows and the number of columns, of the matrix. aij gives the distance between the i-th leaf node (computer) and the j-th. You may assume 2 ≤ N ≤ 50 and the matrix is symmetric whose diagonal elements are all zeros. That is, aii = 0 and aij = aji for each i and j. Each non-diagonal element aij (i ≠ j) satisfies 2 ≤ aij ≤ 30. You may assume there is always a solution. That is, there is a tree having the given distances between leaf nodes. Output For each distance matrix, find a tree having the given distances between leaf nodes. Then output the degree of each internal node (i.e. the number of cables adjoining each switch), all in a single line and in ascending order. Numbers in a line should be separated by a single space. A line should not contain any other characters, including trailing spaces. Examples Input 4 0 2 2 2 2 0 2 2 2 2 0 2 2 2 2 0 4 0 2 4 4 2 0 4 4 4 4 0 2 4 4 2 0 2 0 12 12 0 0 Output 4 2 3 3 2 2 2 2 2 2 2 2 2 2 2 Input 4 0 2 2 2 2 0 2 2 2 2 0 2 2 2 2 0 4 0 2 4 4 2 0 4 4 4 4 0 2 4 4 2 0 2 0 12 12 0 0 Output 4 2 3 3 2 2 2 2 2 2 2 2 2 2 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. According to a new ISO standard, a flag of every country should have, strangely enough, a chequered field n × m, each square should be wholly painted one of 26 colours. The following restrictions are set: * In each row at most two different colours can be used. * No two adjacent squares can be painted the same colour. Pay attention, please, that in one column more than two different colours can be used. Berland's government took a decision to introduce changes into their country's flag in accordance with the new standard, at the same time they want these changes to be minimal. By the given description of Berland's flag you should find out the minimum amount of squares that need to be painted different colour to make the flag meet the new ISO standard. You are as well to build one of the possible variants of the new Berland's flag. Input The first input line contains 2 integers n and m (1 ≤ n, m ≤ 500) — amount of rows and columns in Berland's flag respectively. Then there follows the flag's description: each of the following n lines contains m characters. Each character is a letter from a to z, and it stands for the colour of the corresponding square. Output In the first line output the minimum amount of squares that need to be repainted to make the flag meet the new ISO standard. The following n lines should contain one of the possible variants of the new flag. Don't forget that the variant of the flag, proposed by you, should be derived from the old flag with the minimum amount of repainted squares. If the answer isn't unique, output any. Examples Input 3 4 aaaa bbbb cccc Output 6 abab baba acac Input 3 3 aba aba zzz Output 4 aba bab zbz Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Can you imagine our life if we removed all zeros from it? For sure we will have many problems. In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a and b. Now let's remove all zeros from this equation. Will the equation remain correct after removing all zeros? For example if the equation is 101 + 102 = 203, if we removed all zeros it will be 11 + 12 = 23 which is still a correct equation. But if the equation is 105 + 106 = 211, if we removed all zeros it will be 15 + 16 = 211 which is not a correct equation. Input The input will consist of two lines, the first line will contain the integer a, and the second line will contain the integer b which are in the equation as described above (1 ≤ a, b ≤ 109). There won't be any leading zeros in both. The value of c should be calculated as c = a + b. Output The output will be just one line, you should print "YES" if the equation will remain correct after removing all zeros, and print "NO" otherwise. Examples Input 101 102 Output YES Input 105 106 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. You've had a baby. Well done. Nice isn't it? Life destroying... but in a good way. Part of your new routine is lying awake at night worrying that you've either lost the baby... or that you have more than 1! Given a string of words (x), you need to calculate how many babies are in it. To count as a baby you must have all of the letters in baby ('b', 'a', 'b', 'y'). That counts as 1. They do not need to be in order in the string. Upper and lower case letters count. Examples: If there are no babies in the string - you lost the baby!! Return a different value, as shown below: ```if-not:kotlin 'none here' = "Where's the baby?!" '' = "Where's the baby?!" ``` ```if:kotlin "none here" = null "" = null ``` Write your solution by modifying this code: ```python def baby_count(x): ``` Your solution should implemented in the function "baby_count". 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. Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q_1q_2... q_{k}. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string. Sereja wants to test his algorithm. For that, he has string s = s_1s_2... s_{n}, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring s_{l}_{i}s_{l}_{i} + 1... s_{r}_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (l_{i}, r_{i}) determine if the algorithm works correctly on this test or not. -----Input----- The first line contains non-empty string s, its length (n) doesn't exceed 10^5. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 10^5) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). -----Output----- For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. -----Examples----- Input zyxxxxxxyyz 5 5 5 1 3 1 11 1 4 3 6 Output YES YES NO YES NO -----Note----- In the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.