question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. There are n cities in Berland. Each city has its index β€” an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi β€” index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≀ n ≀ 5Β·104, 1 ≀ r1 β‰  r2 ≀ n) β€” amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers β€” the old representation of the road map. For each city, apart from r1, there is given integer pi β€” index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers β€” new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name β€” The Huff-puffer. So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with Ξ± liters of petrol (Ξ± β‰₯ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with Ξ± liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if Ξ± = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage. One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the Ξ± number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be. Input The first line contains an integer n (1 ≀ n ≀ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number Ξ± β‰₯ 10, to which such a succession of stops corresponds. Output Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique". Examples Input 3 1 2 4 Output unique 5 Input 2 1 2 Output not unique Note In the second example the answer is not unique. For example, if Ξ± = 10, we'll have such a sequence as 1, 2, 3, and if Ξ± = 14, the sequence will be 1, 2, 4. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes). The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation. Input The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits. Output In the single line print the number that is written without leading zeroes in the binary notation β€” the answer to the problem. Examples Input 101 Output 11 Input 110010 Output 11010 Note In the first sample the best strategy is to delete the second digit. That results in number 112 = 310. In the second sample the best strategy is to delete the third or fourth digits β€” that results in number 110102 = 2610. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Even if the world is full of counterfeits, I still regard it as wonderful. Pile up herbs and incense, and arise again from the flames and ashes of its predecessorΒ β€” as is known to many, the phoenix does it like this. The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes the factorial of integer a, that is, a! = 1 Γ— 2 Γ— ... Γ— a. Specifically, 0! = 1. Koyomi doesn't care much about this, but before he gets into another mess with oddities, he is interested in the number of times the phoenix will reincarnate in a timespan of b! years, that is, [Image]. Note that when b β‰₯ a this value is always integer. As the answer can be quite large, it would be enough for Koyomi just to know the last digit of the answer in decimal representation. And you're here to provide Koyomi with this knowledge. -----Input----- The first and only line of input contains two space-separated integers a and b (0 ≀ a ≀ b ≀ 10^18). -----Output----- Output one line containing a single decimal digitΒ β€” the last digit of the value that interests Koyomi. -----Examples----- Input 2 4 Output 2 Input 0 10 Output 0 Input 107 109 Output 2 -----Note----- In the first example, the last digit of $\frac{4 !}{2 !} = 12$ is 2; In the second example, the last digit of $\frac{10 !}{0 !} = 3628800$ is 0; In the third example, the last digit of $\frac{109 !}{107 !} = 11772$ 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. Read problems statements in Mandarin Chinese and Russian as well. In every contest there should be an easy problem about matrices. December Cook-Off is not an exception. Given a matrix A which consists of n rows and m columns, and contains integer numbers. Consider every possible vector v of m elements, such that every 1 ≀ v_{i} ≀ n. Let value of the vector be product of all Av_{i}, i (1 ≀ i ≀ m). You are to count the sum of values over all possible vectors v. ------ Input details ------ The first line contains two integers n and m β€” dimensions of the matrix. Then n lines of m integers follow. The j_{th} element of i_{th} line contains A_{i, j}. ------ Output details ------ Output single integer β€” the answer for the problem modulo 10^{7} + 7, i.e the smallest non-negative integer number r that answer - r is divisible by 10^{7} + 7. ------ Constraints ------ 1 ≀ n ≀ 47 1 ≀ m ≀ 38 0 ≀ |A_{i, j}| ≀ 100 ----- Sample Input 1 ------ 2 2 1 2 3 4 ----- Sample Output 1 ------ 24 ----- explanation 1 ------ All possible vectors are {(1, 1), (1, 2), (2, 1), (2, 2)} value(1, 1) = A1, 1 * A1, 2 = 1 * 2 = 2value(1, 2) = A1, 1 * A2, 2 = 1 * 4 = 4value(2, 1) = A2, 1 * A1, 2 = 3 * 2 = 6value(2, 2) = A2, 1 * A2, 2 = 3 * 4 = 12answer = 2 + 4 + 6 + 12 = 24 Read the inputs from stdin solve the problem and write the answer to stdout (do 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$ boxers, the weight of the $i$-th boxer is $a_i$. Each of them can change the weight by no more than $1$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number. It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique). Write a program that for given current values ​$a_i$ will find the maximum possible number of boxers in a team. It is possible that after some change the weight of some boxer is $150001$ (but no more). -----Input----- The first line contains an integer $n$ ($1 \le n \le 150000$) β€” the number of boxers. The next line contains $n$ integers $a_1, a_2, \dots, a_n$, where $a_i$ ($1 \le a_i \le 150000$) is the weight of the $i$-th boxer. -----Output----- Print a single integer β€” the maximum possible number of people in a team. -----Examples----- Input 4 3 2 4 1 Output 4 Input 6 1 1 1 4 4 4 Output 5 -----Note----- In the first example, boxers should not change their weights β€” you can just make a team out of all of them. In the second example, one boxer with a weight of $1$ can be increased by one (get the weight of $2$), one boxer with a weight of $4$ can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of $3$ and $5$, respectively). Thus, you can get a team consisting of boxers with weights of $5, 4, 3, 2, 1$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integersΒ β€” amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number. For each two integer numbers a and b such that l ≀ a ≀ r and x ≀ b ≀ y there is a potion with experience a and cost b in the store (that is, there are (r - l + 1)Β·(y - x + 1) potions). Kirill wants to buy a potion which has efficiency k. Will he be able to do this? -----Input----- First string contains five integer numbers l, r, x, y, k (1 ≀ l ≀ r ≀ 10^7, 1 ≀ x ≀ y ≀ 10^7, 1 ≀ k ≀ 10^7). -----Output----- Print "YES" without quotes if a potion with efficiency exactly k can be bought in the store and "NO" without quotes otherwise. You can output each of the letters in any register. -----Examples----- Input 1 10 1 10 1 Output YES Input 1 5 6 10 1 Output NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height). Boris chose m types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type. The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely. After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him. Input The first line contains a positive integer n (1 ≀ n ≀ 500) β€” the number of rooms in Boris's apartment. Each of the next n lines contains three space-separated positive integers β€” the length, width and height of the walls in a given room in meters, respectively. The next line contains a positive integer m (1 ≀ m ≀ 500) β€” the number of available wallpaper types. Each of the following m lines contains three space-separated positive integers β€” the length and width in meters of a given wallpaper and the price of one roll, respectively. All numbers in the input data do not exceed 500. It is guaranteed that each room can be papered using these types of wallpaper. Output Print a single number β€” the minimum total cost of the rolls. Examples Input 1 5 5 3 3 10 1 100 15 2 320 3 19 500 Output 640 Note Note to the sample: The total length of the walls (the perimeter) of the room is 20 m. One roll of the first type can be cut into pieces to get three vertical 1 meter wide strips, ergo you need 7 rolls of this type, the price equals 700. A roll of the second type can be cut into pieces to get five 2 meter wide strips, we need 2 rolls, the price is 640. One roll of the third type can immediately paper 19 meters out of 20, but we cannot use other types and we have to buy a second roll, the price is 1000. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 decide which is the strongest among Rock, Paper, and Scissors, we will hold an RPS tournament. There are 2^k players in this tournament, numbered 0 through 2^k-1. Each player has his/her favorite hand, which he/she will use in every match. A string s of length n consisting of R, P, and S represents the players' favorite hands. Specifically, the favorite hand of Player i is represented by the ((i\text{ mod } n) + 1)-th character of s; R, P, and S stand for Rock, Paper, and Scissors, respectively. For l and r such that r-l is a power of 2, the winner of the tournament held among Players l through r-1 will be determined as follows: - If r-l=1 (that is, there is just one player), the winner is Player l. - If r-l\geq 2, let m=(l+r)/2, and we hold two tournaments, one among Players l through m-1 and the other among Players m through r-1. Let a and b be the respective winners of these tournaments. a and b then play a match of rock paper scissors, and the winner of this match - or a if the match is drawn - is the winner of the tournament held among Players l through r-1. Find the favorite hand of the winner of the tournament held among Players 0 through 2^k-1. -----Notes----- - a\text{ mod } b denotes the remainder when a is divided by b. - The outcome of a match of rock paper scissors is determined as follows: - If both players choose the same hand, the match is drawn; - R beats S; - P beats R; - S beats P. -----Constraints----- - 1 \leq n,k \leq 100 - s is a string of length n consisting of R, P, and S. -----Input----- Input is given from Standard Input in the following format: n k s -----Output----- Print the favorite hand of the winner of the tournament held among Players 0 through 2^k-1, as R, P, or S. -----Sample Input----- 3 2 RPS -----Sample Output----- P - The favorite hand of the winner of the tournament held among Players 0 through 1 is P. - The favorite hand of the winner of the tournament held among Players 2 through 3 is R. - The favorite hand of the winner of the tournament held among Players 0 through 3 is P. Thus, the answer is P. P β”Œβ”€β”΄β”€β” P R β”Œβ”΄β” β”Œβ”΄β” R P S R ``` S β”Œβ”€β”€β”€β”΄β”€β”€β”€β” P S β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” P R S P β”Œβ”΄β” β”Œβ”΄β” β”Œβ”΄β” β”Œβ”΄β” R P S R P S R P ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Consider the following well known rules: - A number is divisible by 3 if the sum of its digits is divisible by 3. Let's call '3' a "1-sum" prime - For 37, we take numbers in groups of threes from the right and check if the sum of these groups is divisible by 37. Example: 37 * 123456787 = 4567901119 => 4 + 567 + 901 + 119 = 1591 = 37 * 43. Let's call this a "3-sum" prime because we use groups of 3. - For 41, we take numbers in groups of fives from the right and check if the sum of these groups is divisible by 41. This is a "5-sum" prime. - Other examples: 239 is a "7-sum" prime (groups of 7), while 199 is a "99-sum" prime (groups of 99). Let's look at another type of prime: - For 11, we need to add all digits by alternating their signs from the right. Example: 11 * 123456 = 1358016 => 6-1+0-8+5-3+1 = 0, which is divible by 11. Let's call this a "1-altsum" prime - For 7, we need to group the digits into threes from the right and add all groups by alternating their signs. Example: 7 * 1234567891234 = 8641975238638 => 638 - 238 + 975 - 641 + 8 = 742/7 = 106. - 7 is a "3-altsum" prime because we use groups of threes. 47 is a "23-altsum" (groups of 23), while 73 is a "4-altsum" prime (groups of 4). You will be given a prime number `p` and your task is to find the smallest positive integer `n` such that `p’s` divisibility testing is `n-sum` or `n-altsum`. For example: ``` solve(3) = "1-sum" solve(7) = "3-altsum" ``` Primes will not exceed `50,000,000`. More examples in test cases. You can get some insight from [Fermat's little theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem). Good luck! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a sequence A, where its elements are either in the form + x or -, where x is an integer. For such a sequence S where its elements are either in the form + x or -, define f(S) as follows: * iterate through S's elements from the first one to the last one, and maintain a multiset T as you iterate through it. * for each element, if it's in the form + x, add x to T; otherwise, erase the smallest element from T (if T is empty, do nothing). * after iterating through all S's elements, compute the sum of all elements in T. f(S) is defined as the sum. The sequence b is a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For all A's subsequences B, compute the sum of f(B), modulo 998 244 353. Input The first line contains an integer n (1≀ n≀ 500) β€” the length of A. Each of the next n lines begins with an operator + or -. If the operator is +, then it's followed by an integer x (1≀ x<998 244 353). The i-th line of those n lines describes the i-th element in A. Output Print one integer, which is the answer to the problem, modulo 998 244 353. Examples Input 4 - + 1 + 2 - Output 16 Input 15 + 2432543 - + 4567886 + 65638788 - + 578943 - - + 62356680 - + 711111 - + 998244352 - - Output 750759115 Note In the first example, the following are all possible pairs of B and f(B): * B= {}, f(B)=0. * B= {-}, f(B)=0. * B= {+ 1, -}, f(B)=0. * B= {-, + 1, -}, f(B)=0. * B= {+ 2, -}, f(B)=0. * B= {-, + 2, -}, f(B)=0. * B= {-}, f(B)=0. * B= {-, -}, f(B)=0. * B= {+ 1, + 2}, f(B)=3. * B= {+ 1, + 2, -}, f(B)=2. * B= {-, + 1, + 2}, f(B)=3. * B= {-, + 1, + 2, -}, f(B)=2. * B= {-, + 1}, f(B)=1. * B= {+ 1}, f(B)=1. * B= {-, + 2}, f(B)=2. * B= {+ 2}, f(B)=2. The sum of these values is 16. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≀ k ≀ n ≀ 109; 0 ≀ m ≀ n). Output Print a single integer β€” the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. C: Skewering problem One day, when Homura was playing with blocks, Tempura came. Homura decided to play with blocks with Tempura. There is a rectangular parallelepiped of A \ times B \ times C, which is made by stacking A \ times B \ times C blocks of cubic blocks with a side length of 1 without any gaps. Each side of all cubes and rectangular parallelepipeds is parallel to the x-axis, y-axis, or z-axis. Homura-chan and Tempura-kun alternately repeat the following operations. * Select a row of blocks of building blocks lined up in a row from a rectangular parallelepiped in any of the vertical, horizontal, and depth directions, and paint all the blocks included in the row in red. However, you cannot select columns that contain blocks that are already painted red. More precisely * Select one of the blocks contained in the rectangular parallelepiped and one of the three directions x, y, and z. * When the selected block is moved in the selected direction by an integer distance, all the blocks that completely overlap are painted in red (think of moving the distance of 0 or a negative integer). However, this operation cannot be performed if there is at least one block that meets the conditions and has already been painted. Homura-chan is the first player to lose the game if he can't operate it first. Also, initially all cubes are uncolored. Determine which one wins when the two act optimally. Input format A B C Constraint * 1 \ leq A, B, C \ leq 100 * All inputs are integers. Output format When the two act optimally, if Homura wins, `Hom` is output, and if Tempura wins,` Tem` is output on one line. Input example 1 1 1 10 Output example 1 Hom * The first time Homura can paint all the blocks red. Input example 2 4 3 5 Output example 2 Hom Input example 3 6 4 10 Output example 3 Tem Example Input 1 1 10 Output Hom Read the inputs from stdin solve the problem and write the answer to stdout (do 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 story You've always loved both Fizz Buzz katas and cuckoo clocks, and when you walked by a garage sale and saw an ornate cuckoo clock with a missing pendulum, and a "Beyond-Ultimate Raspberry Pi Starter Kit" filled with all sorts of sensors and motors and other components, it's like you were suddenly hit by a beam of light and knew that it was your mission to combine the two to create a computerized Fizz Buzz cuckoo clock! You took them home and set up shop on the kitchen table, getting more and more excited as you got everything working together just perfectly. Soon the only task remaining was to write a function to select from the sounds you had recorded depending on what time it was: ## Your plan * When a minute is evenly divisible by three, the clock will say the word "Fizz". * When a minute is evenly divisible by five, the clock will say the word "Buzz". * When a minute is evenly divisible by both, the clock will say "Fizz Buzz", with two exceptions: 1. On the hour, instead of "Fizz Buzz", the clock door will open, and the cuckoo bird will come out and "Cuckoo" between one and twelve times depending on the hour. 2. On the half hour, instead of "Fizz Buzz", the clock door will open, and the cuckoo will come out and "Cuckoo" just once. * With minutes that are not evenly divisible by either three or five, at first you had intended to have the clock just say the numbers ala Fizz Buzz, but then you decided at least for version 1.0 to just have the clock make a quiet, subtle "tick" sound for a little more clock nature and a little less noise. Your input will be a string containing hour and minute values in 24-hour time, separated by a colon, and with leading zeros. For example, 1:34 pm would be `"13:34"`. Your return value will be a string containing the combination of Fizz, Buzz, Cuckoo, and/or tick sounds that the clock needs to make at that time, separated by spaces. Note that although the input is in 24-hour time, cuckoo clocks' cuckoos are in 12-hour time. ## Some examples ``` "13:34" "tick" "21:00" "Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo" "11:15" "Fizz Buzz" "03:03" "Fizz" "14:30" "Cuckoo" "08:55" "Buzz" "00:00" "Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo" "12:00" "Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo" ``` Have fun! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate. The path consists of $n$ consecutive tiles, numbered from $1$ to $n$. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles with numbers $i$ and $j$, such that $|j - i|$ is a divisor of $n$ greater than $1$, they have the same color. Formally, the colors of two tiles with numbers $i$ and $j$ should be the same if $|i-j| > 1$ and $n \bmod |i-j| = 0$ (where $x \bmod y$ is the remainder when dividing $x$ by $y$). Ujan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic? -----Input----- The first line of input contains a single integer $n$ ($1 \leq n \leq 10^{12}$), the length of the path. -----Output----- Output a single integer, the maximum possible number of colors that the path can be painted in. -----Examples----- Input 4 Output 2 Input 5 Output 5 -----Note----- In the first sample, two colors is the maximum number. Tiles $1$ and $3$ should have the same color since $4 \bmod |3-1| = 0$. Also, tiles $2$ and $4$ should have the same color since $4 \bmod |4-2| = 0$. In the second sample, all five colors can be used. [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. Lots of geeky customers visit our chef's restaurant everyday. So, when asked to fill the feedback form, these customers represent the feedback using a binary string (i.e a string that contains only characters '0' and '1'. Now since chef is not that great in deciphering binary strings, he has decided the following criteria to classify the feedback as Good or Bad : If the string contains the substring "010" or "101", then the feedback is Good, else it is Bad. Note that, to be Good it is not necessary to have both of them as substring. So given some binary strings, you need to output whether according to the chef, the strings are Good or Bad. -----Input----- The first line contains an integer T denoting the number of feedbacks. Each of the next T lines contains a string composed of only '0' and '1'. -----Output----- For every test case, print in a single line Good or Bad as per the Chef's method of classification. -----Constraints----- - 1 ≀ T ≀ 100 - 1 ≀ |S| ≀ 105 Sum of length of all strings in one test file will not exceed 6*106. -----Example----- Input: 2 11111110 10101010101010 Output: Bad Good -----Explanation----- Example case 1. The string doesn't contain 010 or 101 as substrings. Example case 2. The string contains both 010 and 101 as substrings. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. At the end of last year, Santa Claus forgot to give Christmas presents to the children in JOI village. Therefore, I decided to deliver the chocolate cake to the children as an apology. The day to deliver is approaching tomorrow, so it's time to come up with a move plan. JOI village is divided into a grid shape by W roads extending straight in the north-south direction and H roads extending straight in the east-west direction. The W roads in the north-south direction are west. The numbers 1, 2, ..., W are numbered in order from the south, and the H roads in the east-west direction are numbered 1, 2, ..., H in order from the south. The intersection of the xth north-south road and the yth east-west road from the south is represented by (x, y). There are N houses in JOI village, and they are located at one of the intersections. Santa Claus can only move along the road. The time it takes to move between adjacent intersections is 1. Every house in JOI village has children, so Santa Claus has to deliver one chocolate cake to every house in JOI village. It's a little to fly with a reindeer with an important chocolate cake. Being dangerous, Santa Claus and Reindeer landed at one of the intersections in JOI Village, where Santa Claus decided to walk to deliver the chocolate cake. Santa Claus would not carry more than one chocolate cake at the same time. In other words, Santa Claus returns to the intersection where he landed every time he delivered a chocolate cake to a house. Santa Claus decided to choose a travel plan that would minimize the time it took to deliver the chocolate cake to all homes after landing in JOI Village. Note that the time it takes to return to the intersection after delivering the chocolate cake to the last house is not included in the time required. Also, I don't think about anything other than the time it takes to move. input Read the following input from standard input. * On the first line, the integers W and H, which represent the number of roads in each direction, are written with blanks as delimiters. * The second line contains the integer N, which represents the number of houses. * The following N lines contain information on the location of the house. On the second line of i + (1 ≀ i ≀ N), the integers Xi and Yi are written separated by blanks, indicating that the i-th house is located at the intersection (Xi, Yi). These N intersections are all different. output Output the following data to standard output. * The first line must contain one integer that represents the minimum required time. * On the second line, when the intersection to be landed to minimize the required time is (x, y), the two integers x, y must be written in this order, separated by blanks. If there are multiple suitable intersections, the westernmost one (that is, the value of x is small), and if it is still not one, the one that is the southernmost (that is, the value of y is small). ) Choose an intersection. Example Input 5 4 3 1 1 3 4 5 3 Output 10 3 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A [Power Law](https://en.wikipedia.org/wiki/Power_law) distribution occurs whenever "a relative change in one quantity results in a proportional relative change in the other quantity." For example, if *y* = 120 when *x* = 1 and *y* = 60 when *x* = 2 (i.e. *y* halves whenever *x* doubles) then when *x* = 4, *y* = 30 and when *x* = 8, *y* = 15. Therefore, if I give you any pair of co-ordinates (x1,y1) and (x2,y2) in a power law distribution, you can plot the entire rest of the distribution and tell me the value of *y* for any other value of *x*. Given a pair of co-ordinates (x1,y1) and (x2,y2) and another x co-ordinate *x3*, return the value of *y3* ``` powerLaw(x1y1, x2y2, x3) e.g. powerLaw([1,120], [2,60], 4) - when x = 1, y = 120 - when x = 2, y = 60 - therefore whenever x doubles, y halves - therefore when x = 4, y = 60 * 0.5 - therfore solution = 30 ``` (x1,y1) and (x2,y2) will be given as arrays. Answer should be to the nearest integer, but random tests will give you leeway of 1% of the reference solution to account for possible discrepancies from different methods. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. As we all know, F.C. Barcelona is the best soccer team of our era! Their entangling and mesmerizing game style usually translates into very high ball possession, consecutive counter-attack plays and goals. Lots of goals, thanks to the natural talent of their attacker and best player in history, Lionel Andres Messi. However, at the most prestigious tournament of individual teams, the UEFA Champions League, there are no guarantees and believe it or not, Barcelona is in trouble.... They are tied versus Chelsea, which is a very defending team that usually relies on counter-strike to catch opposing teams off guard and we are in the last minute of the match. So Messi decided to settle things down for good and now he is conducting the ball on his teams' midfield and he will start a lethal counter-attack :D After dribbling the 2 strikers from Chelsea, he now finds himself near the center of the field and he won't be able to dribble the entire team on his own, so he will need to pass the ball to one of his teammates, run forward and receive the ball once again to score the final goal. Exactly K players are with him on his counter-attack and the coach, Tito Villanova knows that this counter-attack will end in a goal only if after exactly N passes are performed between the players, Messi ends up with the ball. (Note that the ball only needs to end with Messi after exactly N passes are performed between all the K+1 players, i.e. Messi can receive the ball several times during the N passes. See the 2nd test case explanation for further clarification. ) However, he realized that there are many scenarios possible for this, so he asked you, his assistant coach, to tell him in how many ways can Messi score the important victory goal. So help him!! -----Input----- Input will contain a number T denoting the number of test cases. Then T test cases follow, each one consisting of two space-sparated integers N and K. -----Output----- For each test case, output a single integer, the number of ways the winning play might happen modulo 1000000007 (109+7). -----Constraints----- - 1 ≀ T ≀ 100 - 2 ≀ N ≀ 1000 - 1 ≀ K ≀ 10 -----Example----- Input: 2 2 4 4 2 Output: 4 6 -----Explanation----- In the first test case, say four players with Messi are Xavi, Busquets, Iniesta and Jordi Alba. Then the ways of the winning play to happen when exactly 2 passes are to be performed are: 1) Messi - Xavi - Messi 2) Messi - Busquets - Messi 3) Messi - Iniesta - Messi 4) Messi - Alba - Messi In the second test case, also say that two players with Messi are Xavi and Iniesta. There are 6 ways for the winning play to happen when exactly 4 passes are performed. All the examples of such winning play are: 1) Messi - Xavi - Messi - Iniesta - Messi 2) Messi - Xavi - Iniesta - Xavi - Messi 3) Messi - Xavi - Messi - Xavi - Messi 4) Messi - Iniesta - Messi - Iniesta - Messi 5) Messi - Iniesta - Messi - Xavi - Messi 6) Messi - Iniesta - Xavi - Iniesta - Messi Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Limak is a little polar bear. He has n balls, the i-th ball has size t_{i}. Limak wants to give one ball to each of his three friends. Giving gifts isn't easyΒ β€” there are two rules Limak must obey to make friends happy: No two friends can get balls of the same size. No two friends can get balls of sizes that differ by more than 2. For example, Limak can choose balls with sizes 4, 5 and 3, or balls with sizes 90, 91 and 92. But he can't choose balls with sizes 5, 5 and 6 (two friends would get balls of the same size), and he can't choose balls with sizes 30, 31 and 33 (because sizes 30 and 33 differ by more than 2). Your task is to check whether Limak can choose three balls that satisfy conditions above. -----Input----- The first line of the input contains one integer n (3 ≀ n ≀ 50)Β β€” the number of balls Limak has. The second line contains n integers t_1, t_2, ..., t_{n} (1 ≀ t_{i} ≀ 1000) where t_{i} denotes the size of the i-th ball. -----Output----- Print "YES" (without quotes) if Limak can choose three balls of distinct sizes, such that any two of them differ by no more than 2. Otherwise, print "NO" (without quotes). -----Examples----- Input 4 18 55 16 17 Output YES Input 6 40 41 43 44 44 44 Output NO Input 8 5 972 3 4 1 4 970 971 Output YES -----Note----- In the first sample, there are 4 balls and Limak is able to choose three of them to satisfy the rules. He must must choose balls with sizes 18, 16 and 17. In the second sample, there is no way to give gifts to three friends without breaking the rules. In the third sample, there is even more than one way to choose balls: Choose balls with sizes 3, 4 and 5. Choose balls with sizes 972, 970, 971. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In this Kata, you will be given an array and your task will be to determine if an array is in ascending or descending order and if it is rotated or not. Consider the array `[1,2,3,4,5,7,12]`. This array is sorted in `Ascending` order. If we rotate this array once to the left, we get `[12,1,2,3,4,5,7]` and twice-rotated we get `[7,12,1,2,3,4,5]`. These two rotated arrays are in `Rotated Ascending` order. Similarly, the array `[9,6,5,3,1]` is in `Descending` order, but we can rotate it to get an array in `Rotated Descending` order: `[1,9,6,5,3]` or `[3,1,9,6,5]` etc. Arrays will never be unsorted, except for those that are rotated as shown above. Arrays will always have an answer, as shown in the examples below. More examples: ```Haskell solve([1,2,3,4,5,7]) = "A" -- Ascending solve([7,1,2,3,4,5]) = "RA" -- Rotated ascending solve([4,5,6,1,2,3]) = "RA" -- Rotated ascending solve([9,8,7,6]) = "D" -- Descending solve([5,9,8,7,6]) = "RD" -- Rotated Descending ``` More examples in the test cases. Good luck! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are two towers consisting of blocks of two colors: red and blue. Both towers are represented by strings of characters B and/or R denoting the order of blocks in them from the bottom to the top, where B corresponds to a blue block, and R corresponds to a red block. These two towers are represented by strings BRBB and RBR. You can perform the following operation any number of times: choose a tower with at least two blocks, and move its top block to the top of the other tower. The pair of towers is beautiful if no pair of touching blocks has the same color; i. e. no red block stands on top of another red block, and no blue block stands on top of another blue block. You have to check if it is possible to perform any number of operations (possibly zero) to make the pair of towers beautiful. -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) β€” the number of test cases. Each test case consists of three lines: the first line contains two integers $n$ and $m$ ($1 \le n, m \le 20$) β€” the number of blocks in the first tower and the number of blocks in the second tower, respectively; the second line contains $s$ β€” a string of exactly $n$ characters B and/or R, denoting the first tower; the third line contains $t$ β€” a string of exactly $m$ characters B and/or R, denoting the second tower. -----Output----- For each test case, print YES if it is possible to perform several (possibly zero) operations in such a way that the pair of towers becomes beautiful; otherwise print NO. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer). -----Examples----- Input 4 4 3 BRBB RBR 4 7 BRBR RRBRBRB 3 4 RBR BRBR 5 4 BRBRR BRBR Output YES YES YES NO -----Note----- In the first test case, you can move the top block from the first tower to the second tower (see the third picture). In the second test case, you can move the top block from the second tower to the first tower $6$ times. In the third test case, the pair of towers is already beautiful. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off. The building consists of n floors with stairs at the left and the right sides. Each floor has m rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with n rows and m + 2 columns, where the first and the last columns represent the stairs, and the m columns in the middle represent rooms. Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights. Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off. -----Input----- The first line contains two integers n and m (1 ≀ n ≀ 15 and 1 ≀ m ≀ 100) β€” the number of floors and the number of rooms in each floor, respectively. The next n lines contains the building description. Each line contains a binary string of length m + 2 representing a floor (the left stairs, then m rooms, then the right stairs) where 0 indicates that the light is off and 1 indicates that the light is on. The floors are listed from top to bottom, so that the last line represents the ground floor. The first and last characters of each string represent the left and the right stairs, respectively, so they are always 0. -----Output----- Print a single integer β€” the minimum total time needed to turn off all the lights. -----Examples----- Input 2 2 0010 0100 Output 5 Input 3 4 001000 000010 000010 Output 12 Input 4 3 01110 01110 01110 01110 Output 18 -----Note----- In the first example, Sagheer will go to room 1 in the ground floor, then he will go to room 2 in the second floor using the left or right stairs. In the second example, he will go to the fourth room in the ground floor, use right stairs, go to the fourth room in the second floor, use right stairs again, then go to the second room in the last floor. In the third example, he will walk through the whole corridor alternating between the left and right stairs at each floor. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an integer sequence A_1,...,A_N consisting of N terms, and N buttons. When the i-th (1 ≦ i ≦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1. There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so that for every i, A_i will be a multiple of B_i. Find the minimum number of times Takahashi will press the buttons. Constraints * All input values are integers. * 1 ≦ N ≦ 10^5 * 0 ≦ A_i ≦ 10^9(1 ≦ i ≦ N) * 1 ≦ B_i ≦ 10^9(1 ≦ i ≦ N) Input The input is given from Standard Input in the following format: N A_1 B_1 : A_N B_N Output Print an integer representing the minimum number of times Takahashi will press the buttons. Examples Input 3 3 5 2 7 9 4 Output 7 Input 7 3 1 4 1 5 9 2 6 5 3 5 8 9 7 Output 22 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees. Consider the point (x, y) in the 2D plane such that x and y are integers and 0 ≀ x, y. There is a tree in such a point, and it has x + y bananas. There are no trees nor bananas in other points. Now, Okabe draws a line with equation $y = - \frac{x}{m} + b$. Okabe can select a single rectangle with axis aligned sides with all points on or under the line and cut all the trees in all points that are inside or on the border of this rectangle and take their bananas. Okabe's rectangle can be degenerate; that is, it can be a line segment or even a point. Help Okabe and find the maximum number of bananas he can get if he chooses the rectangle wisely. Okabe is sure that the answer does not exceed 10^18. You can trust him. -----Input----- The first line of input contains two space-separated integers m and b (1 ≀ m ≀ 1000, 1 ≀ b ≀ 10000). -----Output----- Print the maximum number of bananas Okabe can get from the trees he cuts. -----Examples----- Input 1 5 Output 30 Input 2 3 Output 25 -----Note----- [Image] The graph above corresponds to sample test 1. The optimal rectangle is shown in red and has 30 bananas. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. It's Galactik Football time! The Galactik Football Assosiation (GFA) has announced a football tournament between all the teams of all the planets in the galaxy. Each planet of the galaxy has a government. Some governments have a mutual agreement between them. If planet $A$ has mutual agreement with planet $B$, then there is a bidirectional spaceway between $A$ and $B$, using which anybody can go from $A$ to $B$ and vice-versa. People can use these spaceways to travel from one planet to another, if there exists a path between them using some of the spaceways. Each planet has its own football ground. The GFA has planned the matches in such a way that a team can have a match at any of these grounds. The GFA has come across some problems in the execution of their plan. They have found out that there are many pairs of planets between which there does not exist any path, so the football team of one of those planets can't reach the other planet. They requested the corresponding governments to make a spaceway between them, but they can’t because of the absence of a mutual agreement. So the GFA suggested that they will make teleportation devices between some pairs of planets which will be used only by the football teams to travel. But there are two types of governments in the galaxy 1. Some of the governments are greedy and they want to make money through the GFA. Each of these government has asked the GFA for a tax value which it has to pay if it wants to make a teleport ending at their planet. 2. Others want to sponsor the event, so they will give money to the GFA if they make a teleport ending at their planet. The GFA would always avoid such governments no matter what the consequences are, because these kind of governments always have some dirty plans up their sleeves. Now, the GFA wants to make bi-directional teleports between planets such that the football teams of any planet can reach any other planet to play a football match, using spaceways between the planets and/or teleports made by the GFA. The GFA also has financial problems and want to spend as little money as possible. They have come to you so that you can help them calculate the minimum amount of money needed to fulfil their plan. ------ Input ------ The first line of the input consists of two space separated integers - $N$ and $M$. $N$ is the number of planets and $M$ is the number of spaceways. The description of the spaceways follows. The next $M$ lines, each contain two space separated integers $A$ and $B$, denoting a mutual agreement and hence a spaceway to travel, between planet $A$ and planet $B$. The next $N$ lines each contain a single integer, the integer on the $i^{th}$ line representing $C_{i}$. If $C_{i} β‰₯ 0$, then it represents the tax value which the GFA has to pay to the government of planet $i$ (it's a type $1$ government). If $C_{i} < 0$, then it represents the money that the $i^{th}$ government will pay to the GFA (it's a type $2$ government). ------ Output ------ Print the minimum amount needed for the GFA to fulfil their plan. If there is no way to do so, print "-1" (without quotes). ------ Constraints ------ $1 ≀ N ≀ 10^{5}$ $0 ≀ M ≀ 10^{6}$ $0 ≀ |C| ≀ 10^{4}$ $1 ≀ A,B ≀ N$ $A \neq B$ ----- Sample Input 1 ------ 6 6 1 2 2 3 1 3 4 5 5 6 4 6 1 3 5 2 4 6 ----- Sample Output 1 ------ 3 ----- explanation 1 ------ ----- Sample Input 2 ------ 3 1 2 3 1 -1 -1 ----- Sample Output 2 ------ -1 ----- explanation 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. When you enter 8 numbers from 0 to 9, write a program that outputs the difference between the largest integer and the smallest integer that can sort the 8 numbers. The number that can be sorted may start from 0, such as 00135569. Input Given multiple datasets. The number of datasets n (n ≀ 50) is given on the first line. Then n rows of data are given. Each data is a sequence of 8 numbers (0 to 9 numbers). Output For each dataset, output the difference between the largest and smallest integers that can be rearranged in the entered numbers on one line. Example Input 2 65539010 65539010 Output 96417531 96417531 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). <image> Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees). Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of dice in the tower. The second line contains an integer x (1 ≀ x ≀ 6) β€” the number Bob sees at the top of the tower. Next n lines contain two space-separated integers each: the i-th line contains numbers ai, bi (1 ≀ ai, bi ≀ 6; ai β‰  bi) β€” the numbers Bob sees on the two sidelong faces of the i-th dice in the tower. Consider the dice in the tower indexed from top to bottom from 1 to n. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input. Output Print "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes). Examples Input 3 6 3 2 5 4 2 4 Output YES Input 3 3 2 6 4 1 5 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. Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (x + 1, y), (x - 1, y), (x, y + 1) or (x, y - 1). Unfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to (a, b) and continue travelling. Luckily, Drazil arrived to the position (a, b) successfully. Drazil said to Varda: "It took me exactly s steps to travel from my house to yours". But Varda is confused about his words, she is not sure that it is possible to get from (0, 0) to (a, b) in exactly s steps. Can you find out if it is possible for Varda? Input You are given three integers a, b, and s ( - 109 ≀ a, b ≀ 109, 1 ≀ s ≀ 2Β·109) in a single line. Output If you think Drazil made a mistake and it is impossible to take exactly s steps and get from his home to Varda's home, print "No" (without quotes). Otherwise, print "Yes". Examples Input 5 5 11 Output No Input 10 15 25 Output Yes Input 0 5 1 Output No Input 0 0 2 Output Yes Note In fourth sample case one possible route is: <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. Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allowed. Help Arkady to find two fountains with maximum total beauty so that he can buy both at the same time. -----Input----- The first line contains three integers n, c and d (2 ≀ n ≀ 100 000, 0 ≀ c, d ≀ 100 000)Β β€” the number of fountains, the number of coins and diamonds Arkady has. The next n lines describe fountains. Each of these lines contain two integers b_{i} and p_{i} (1 ≀ b_{i}, p_{i} ≀ 100 000)Β β€” the beauty and the cost of the i-th fountain, and then a letter "C" or "D", describing in which type of money is the cost of fountain i: in coins or in diamonds, respectively. -----Output----- Print the maximum total beauty of exactly two fountains Arkady can build. If he can't build two fountains, print 0. -----Examples----- Input 3 7 6 10 8 C 4 3 C 5 6 D Output 9 Input 2 4 5 2 5 C 2 1 D Output 0 Input 3 10 10 5 5 C 5 5 C 10 11 D Output 10 -----Note----- In the first example Arkady should build the second fountain with beauty 4, which costs 3 coins. The first fountain he can't build because he don't have enough coins. Also Arkady should build the third fountain with beauty 5 which costs 6 diamonds. Thus the total beauty of built fountains is 9. In the second example there are two fountains, but Arkady can't build both of them, because he needs 5 coins for the first fountain, and Arkady has only 4 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. Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a_1, a_2, ..., a_{n} of n integer numbers β€” saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that: Each pencil belongs to exactly one box; Each non-empty box has at least k pencils in it; If pencils i and j belong to the same box, then |a_{i} - a_{j}| ≀ d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |a_{i} - a_{j}| ≀ d and they belong to different boxes. Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO". -----Input----- The first line contains three integer numbers n, k and d (1 ≀ k ≀ n ≀ 5Β·10^5, 0 ≀ d ≀ 10^9) β€” the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively. The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≀ a_{i} ≀ 10^9) β€” saturation of color of each pencil. -----Output----- Print "YES" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print "NO". -----Examples----- Input 6 3 10 7 2 7 7 4 2 Output YES Input 6 2 3 4 5 3 13 4 10 Output YES Input 3 2 5 10 16 22 Output NO -----Note----- In the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10. In the second example you can split pencils of saturations [4, 5, 3, 4] into 2 boxes of size 2 and put the remaining ones into another box. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an array a. Some element of this array a_{i} is a local minimum iff it is strictly less than both of its neighbours (that is, a_{i} < a_{i} - 1 and a_{i} < a_{i} + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, a_{i} > a_{i} - 1 and a_{i} > a_{i} + 1). Since a_1 and a_{n} have only one neighbour each, they are neither local minima nor local maxima. An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array. -----Input----- The first line contains one integer n (1 ≀ n ≀ 1000) β€” the number of elements in array a. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≀ a_{i} ≀ 1000) β€” the elements of array a. -----Output----- Print the number of local extrema in the given array. -----Examples----- Input 3 1 2 3 Output 0 Input 4 1 5 2 5 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are playing one famous sandbox game with the three-dimensional world. The map of the world can be represented as a matrix of size n Γ— m, where the height of the cell (i, j) is a_{i, j}. You are in the cell (1, 1) right now and want to get in the cell (n, m). You can move only down (from the cell (i, j) to the cell (i + 1, j)) or right (from the cell (i, j) to the cell (i, j + 1)). There is an additional restriction: if the height of the current cell is x then you can move only to the cell with height x+1. Before the first move you can perform several operations. During one operation, you can decrease the height of any cell by one. I.e. you choose some cell (i, j) and assign (set) a_{i, j} := a_{i, j} - 1. Note that you can make heights less than or equal to zero. Also note that you can decrease the height of the cell (1, 1). Your task is to find the minimum number of operations you have to perform to obtain at least one suitable path from the cell (1, 1) to the cell (n, m). It is guaranteed that the answer exists. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. The first line of the test case contains two integers n and m (1 ≀ n, m ≀ 100) β€” the number of rows and the number of columns in the map of the world. The next n lines contain m integers each, where the j-th integer in the i-th line is a_{i, j} (1 ≀ a_{i, j} ≀ 10^{15}) β€” the height of the cell (i, j). It is guaranteed that the sum of n (as well as the sum of m) over all test cases does not exceed 100 (βˆ‘ n ≀ 100; βˆ‘ m ≀ 100). Output For each test case, print the answer β€” the minimum number of operations you have to perform to obtain at least one suitable path from the cell (1, 1) to the cell (n, m). It is guaranteed that the answer exists. Example Input 5 3 4 1 2 3 4 5 6 7 8 9 10 11 12 5 5 2 5 4 8 3 9 10 11 5 1 12 8 4 2 5 2 2 5 4 1 6 8 2 4 2 2 2 100 10 10 1 1 2 123456789876543 987654321234567 1 1 42 Output 9 49 111 864197531358023 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. Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible. Omkar currently has $n$ supports arranged in a line, the $i$-th of which has height $a_i$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $1$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $1$ to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide! An array $b$ is a subsegment of an array $c$ if $b$ can be obtained from $c$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end. An array $b_1, b_2, \dots, b_n$ is called nondecreasing if $b_i\le b_{i+1}$ for every $i$ from $1$ to $n-1$. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \leq t \leq 100$). Description of the test cases follows. The first line of each test case contains an integer $n$ ($1 \leq n \leq 2 \cdot 10^5$)Β β€” the number of supports Omkar has. The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ $(0 \leq a_{i} \leq 10^9)$Β β€” the heights of the supports. It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case, output a single integerΒ β€” the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide. -----Example----- Input 3 4 5 3 2 5 5 1 2 3 5 3 3 1 1 1 Output 3 2 0 -----Note----- The subarray with which Omkar performs the operation is bolded. In the first test case: First operation: $[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$ Second operation: $[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$ Third operation: $[5, \textbf{4}, \textbf{4}, 5] \to [5, \textbf{5}, \textbf{5}, 5]$ In the third test case, the array is already nondecreasing, so Omkar does $0$ operations. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch. Marmot brought Mole n ordered piles of worms such that i-th pile contains a_{i} worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a_1, worms in second pile are labeled with numbers a_1 + 1 to a_1 + a_2 and so on. See the example for a better understanding. Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained. Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers. -----Input----- The first line contains a single integer n (1 ≀ n ≀ 10^5), the number of piles. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≀ a_{i} ≀ 10^3, a_1 + a_2 + ... + a_{n} ≀ 10^6), where a_{i} is the number of worms in the i-th pile. The third line contains single integer m (1 ≀ m ≀ 10^5), the number of juicy worms said by Marmot. The fourth line contains m integers q_1, q_2, ..., q_{m} (1 ≀ q_{i} ≀ a_1 + a_2 + ... + a_{n}), the labels of the juicy worms. -----Output----- Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number q_{i} is. -----Examples----- Input 5 2 7 3 4 9 3 1 25 11 Output 1 5 3 -----Note----- For the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ashish has a tree consisting of $n$ nodes numbered $1$ to $n$ rooted at node $1$. The $i$-th node in the tree has a cost $a_i$, and binary digit $b_i$ is written in it. He wants to have binary digit $c_i$ written in the $i$-th node in the end. To achieve this, he can perform the following operation any number of times: Select any $k$ nodes from the subtree of any node $u$, and shuffle the digits in these nodes as he wishes, incurring a cost of $k \cdot a_u$. Here, he can choose $k$ ranging from $1$ to the size of the subtree of $u$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target. Help him find the minimum total cost he needs to spend so that after all the operations, every node $u$ has digit $c_u$ written in it, or determine that it is impossible. -----Input----- First line contains a single integer $n$ $(1 \le n \le 2 \cdot 10^5)$ denoting the number of nodes in the tree. $i$-th line of the next $n$ lines contains 3 space-separated integers $a_i$, $b_i$, $c_i$ $(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$ Β β€” the cost of the $i$-th node, its initial digit and its goal digit. Each of the next $n - 1$ lines contain two integers $u$, $v$ $(1 \leq u, v \leq n, \text{ } u \ne v)$, meaning that there is an edge between nodes $u$ and $v$ in the tree. -----Output----- Print the minimum total cost to make every node reach its target digit, and $-1$ if it is impossible. -----Examples----- Input 5 1 0 1 20 1 0 300 0 1 4000 0 0 50000 1 0 1 2 2 3 2 4 1 5 Output 4 Input 5 10000 0 1 2000 1 0 300 0 1 40 0 0 1 1 0 1 2 2 3 2 4 1 5 Output 24000 Input 2 109 0 1 205 0 1 1 2 Output -1 -----Note----- The tree corresponding to samples $1$ and $2$ are: [Image] In sample $1$, we can choose node $1$ and $k = 4$ for a cost of $4 \cdot 1$ = $4$ and select nodes ${1, 2, 3, 5}$, shuffle their digits and get the desired digits in every node. In sample $2$, we can choose node $1$ and $k = 2$ for a cost of $10000 \cdot 2$, select nodes ${1, 5}$ and exchange their digits, and similarly, choose node $2$ and $k = 2$ for a cost of $2000 \cdot 2$, select nodes ${2, 3}$ and exchange their digits to get the desired digits in every node. In sample $3$, it is impossible to get the desired digits, because there is no node with digit $1$ initially. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 job is to change the given string `s` using a non-negative integer `n`. Each bit in `n` will specify whether or not to swap the case for each alphabetic character in `s`: if the bit is `1`, swap the case; if its `0`, leave it as is. When you finished with the last bit of `n`, start again with the first bit. You should skip the checking of bits when a non-alphabetic character is encountered, but they should be preserved in their original positions. ## Examples ``` swap('Hello world!', 11) --> 'heLLO wORLd!' ``` ...because `11` is `1011` in binary, so the 1st, 3rd, 4th, 5th, 7th, 8th and 9th alphabetical characters have to be swapped: ``` H e l l o w o r l d ! 1 0 1 1 1 0 1 1 1 0 ^ ^ ^ ^ ^ ^ ^ ``` More examples: ``` swap("gOOd MOrniNg", 7864) --> "GooD MorNIng" swap('', 11345) --> '' swap('the lord of the rings', 0) --> 'the lord of the rings' ``` Read the inputs from stdin solve the problem and write the answer to stdout (do 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 city has n junctions. There are m one-way roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions. To ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction i can protect junction j if either i = j or the police patrol car can go to j from i and then come back to i. Building checkposts costs some money. As some areas of the city are more expensive than others, building checkpost at some junctions might cost more money than other junctions. You have to determine the minimum possible money needed to ensure the security of all the junctions. Also you have to find the number of ways to ensure the security in minimum price and in addition in minimum number of checkposts. Two ways are different if any of the junctions contains a checkpost in one of them and do not contain in the other. -----Input----- In the first line, you will be given an integer n, number of junctions (1 ≀ n ≀ 10^5). In the next line, n space-separated integers will be given. The i^{th} integer is the cost of building checkpost at the i^{th} junction (costs will be non-negative and will not exceed 10^9). The next line will contain an integer mΒ (0 ≀ m ≀ 3Β·10^5). And each of the next m lines contains two integers u_{i} and v_{i}Β (1 ≀ u_{i}, v_{i} ≀ n;Β u β‰  v). A pair u_{i}, v_{i} means, that there is a one-way road which goes from u_{i} to v_{i}. There will not be more than one road between two nodes in the same direction. -----Output----- Print two integers separated by spaces. The first one is the minimum possible money needed to ensure the security of all the junctions. And the second one is the number of ways you can ensure the security modulo 1000000007 (10^9 + 7). -----Examples----- Input 3 1 2 3 3 1 2 2 3 3 2 Output 3 1 Input 5 2 8 0 6 0 6 1 4 1 3 2 4 3 4 4 5 5 1 Output 8 2 Input 10 1 3 2 2 1 3 1 4 10 10 12 1 2 2 3 3 1 3 4 4 5 5 6 5 7 6 4 7 3 8 9 9 10 10 9 Output 15 6 Input 2 7 91 2 1 2 2 1 Output 7 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read the coordinates of four different points on the plane, $ A (x_A, y_A) $, $ B (x_B, y_B) $, $ C (x_C, y_C) $, $ D (x_D, y_D) $, and straight line $ Create a program that outputs YES if AB $ and $ CD $ are orthogonal, and NO if they are not orthogonal. Here, "straight line" does not mean a line segment. Please refer to the figure below. <image> Input Given multiple datasets. The format of each dataset is as follows. $ x_A $ $ y_A $ $ x_B $ $ y_B $ $ x_C $ $ y_C $ $ x_D $ $ y_D $ $ x_A $, $ y_A $, $ x_B $, $ y_B $, $ x_C $, $ y_C $, $ x_D $, $ y_D $ are each -100 or more and 100 or less, and each value has a maximum of 5 digits after the decimal point. It is given as a real number including the number of. The number of datasets does not exceed 100. Output Print YES or NO on one line for each dataset. Example Input 1.0 1.0 2.0 2.0 0.0 0.0 1.0 -1.0 0.0 0.0 2.0 0.0 -1.0 2.0 2.0 2.0 10.0 6.0 3.4 5.2 6.8 9.5 4.3 2.1 2.5 3.5 2.5 4.5 -3.3 -2.3 6.8 -2.3 Output YES NO NO YES Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke has a string s. From this string, Anuke, Bnuke, and Cnuke obtained strings a, b, and c, respectively, as follows: * Choose a non-empty (contiguous) substring of s (possibly s itself). Then, replace some characters (possibly all or none) in it with `?`s. For example, if s is `mississippi`, we can choose the substring `ssissip` and replace its 1-st and 3-rd characters with `?` to obtain `?s?ssip`. You are given the strings a, b, and c. Find the minimum possible length of s. Constraints * 1 \leq |a|, |b|, |c| \leq 2000 * a, b, and c consists of lowercase English letters and `?`s. Input Input is given from Standard Input in the following format: a b c Output Print the minimum possible length of s. Examples Input a?c der cod Output 7 Input atcoder atcoder ??????? Output 7 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Problem A: Swap crypto A 2D enthusiast at R University, he often writes embarrassing sentences that blush when seen by people. Therefore, in order for a third party to not be able to see the text he is writing, he encrypts the text using a method called swap encryption that he devised independently. In swap encryption, the following steps are repeated N times to perform encryption. 1. Swap the ai and bi of the string 2. Return these two characters in alphabetical order by the difference between ai and bi However, in alphabetical order, "z" is used before "a". For example, if the character string "aojwo" is encrypted with a1 = 1 and b1 = 4, it will be as follows. 1. Swap the 1st and 4th ("aojwo" β†’ "wojao") 2. Return these two letters'w'and'a' in alphabetical order by the difference between 1 and 4 = 3 ("wojao"-> "tojxo") * If'w'is returned by 3 in alphabetical order, it becomes'w' β†’'v' β†’'u' β†’'t'. * If'a'is returned by 3 in alphabetical order, it becomes'a' β†’'z' β†’'y' β†’'x'. Therefore, "aojwo" is encrypted as "tojxo". This encryption should have allowed him to encrypt his text without knowing the original text, but perhaps he leaked the swap operation process he used to encrypt it. Your job is to create a program that "decrypts" given the encrypted strings and the swap operation used for encryption, and dismisses him as a 2D enthusiast. Input The input consists of multiple datasets. The total number of datasets is 20 or less. Each dataset has the following format: N message a1 b1 ... ai bi ... aN bN N (0 <N ≀ 100) is an integer that indicates the number of swap operations when encrypting. message indicates encrypted data. Cryptographic data is a character string consisting of only lowercase letters of the alphabet. If the length of the message is len, we can assume that 2 ≀ len ≀ 100. ai and bi represent two indexes that have been swapped in encryption. You can assume that 1 ≀ ai <bi ≀ len. For encryption, it is assumed that the swap operations are performed in the order in which they are entered. The end of the input is indicated by a single line consisting of only 0s. This data does not need to be processed. Output Output the decrypted string on one line for each dataset. Sample Input 1 tojxo 14 Five uhcqmlmkv 4 5 6 9 3 6 1 7 3 6 Five shzxadexonr 8 9 3 9 5 8 4 9 10 11 0 Output for Sample Input aojwo shinryaku shitadegeso Example Input 1 tojxo 1 4 5 uhcqmlmkv 4 5 6 9 3 6 1 7 3 6 5 shzxadexonr 8 9 3 9 5 8 4 9 10 11 0 Output aojwo shinryaku shitadegeso Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones. -----Input----- The first line contains four space-separated x_1, y_1, x_2, y_2 ( - 100 ≀ x_1, y_1, x_2, y_2 ≀ 100) integers, where x_1 and y_1 are coordinates of the first tree and x_2 and y_2 are coordinates of the second tree. It's guaranteed that the given points are distinct. -----Output----- If there is no solution to the problem, print -1. Otherwise print four space-separated integers x_3, y_3, x_4, y_4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them. Note that x_3, y_3, x_4, y_4 must be in the range ( - 1000 ≀ x_3, y_3, x_4, y_4 ≀ 1000). -----Examples----- Input 0 0 0 1 Output 1 0 1 1 Input 0 0 1 1 Output 0 1 1 0 Input 0 0 1 2 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. You know combinations: for example, if you take 5 cards from a 52 cards deck you have 2,598,960 different combinations. In mathematics the number of x combinations you can take from a set of n elements is called the binomial coefficient of n and x, or more often `n choose x`. The formula to compute `m = n choose x` is: `m = n! / (x! * (n - x)!)` where ! is the factorial operator. You are a renowned poster designer and painter. You are asked to provide 6 posters all having the same design each in 2 colors. Posters must all have a different color combination and you have the choice of 4 colors: red, blue, yellow, green. How many colors can you choose for each poster? The answer is two since `4 choose 2 = 6`. The combinations will be: {red, blue}, {red, yellow}, {red, green}, {blue, yellow}, {blue, green}, {yellow, green}. Now same question but you have 35 posters to provide and 7 colors available. How many colors for each poster? If you take combinations `7 choose 2` you will get 21 with the above formula. But 21 schemes aren't enough for 35 posters. If you take `7 choose 5` combinations you will get 21 too. Fortunately if you take `7 choose 3` or `7 choose 4` combinations you get 35 and so each poster will have a different combination of 3 colors or 5 colors. You will take 3 colors because it's less expensive. Hence the problem is: knowing `m` (number of posters to design), knowing `n` (total number of available colors), let us search `x` (number of colors for each poster so that each poster has a unique combination of colors and the number of combinations is exactly the same as the number of posters). In other words we must find **x** such as `n choose x = m (1)` for a given m and a given n; `m >= 0 and n > 0`. If many x are solutions give as result the smallest x. It can happen that when m is given at random there are no x satisfying `equation (1)` then return -1. Examples: ``` checkchoose(6, 4) --> 2 checkchoose(4, 4) --> 1 checkchoose(4, 2) --> -1 checkchoose(35, 7) --> 3 checkchoose(36, 7) --> -1 a = 47129212243960 checkchoose(a, 50) --> 20 checkchoose(a + 1, 50) --> -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. problem There are the following two-player card games. * This game uses a total of 2n cards with each integer from 1 to 2n written on it. Here, n is an integer between 1 and 100. * Deal n cards to each of the two. * Put cards into play alternately one by one according to the following rules. * If there are no cards in play, you can play any card you like. * If there are cards in play, you can play a larger number of written cards than the last card in play. * If you can play a card, you must put it into play. * If there is no card that can be issued, it will be a pass and it will be the opponent's turn. At this time, there are no cards in play. * The game starts with no cards in play. * The game ends when either card is exhausted. * The number of cards the opponent has at the end of the game will be scored. Taro and Hanako will play in this game. The game starts with Taro's turn. Both of them always issue the card with the smallest number of cards that can be issued. Create a program that outputs the scores of Taro and Hanako when the cards dealt to Taro are input. input The input consists of multiple datasets. Each dataset is given in the following format. The input is n + 1 lines. The integer n is written on the first line. Each line from the 2nd line to the n + 1th line has one integer written on it, which represents the integer written on the card dealt to Taro. When n is 0, it indicates the end of input. The number of data sets does not exceed 5. output For each dataset, print Taro's score on the first line and Hanako's score on the second line. Examples Input 5 1 7 9 6 10 10 8 7 14 18 4 11 3 17 5 19 0 Output 3 0 2 0 Input None Output None Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Scenario **_Several people_** are standing in *a row divided into two teams*. The **_first person_** goes into **_team 1_**, **_the second_** goes into **_team 2_**, **_the third_** goes into **_team 1_**, and so on. ___ # Task **_Given_** *an array of positive integers (the weights of the people)*, **_return_** *a new array/tuple of two integers*, **_where_** **_the first_** one is the **_total weight of team 1_**, and **_the second_** one is the **_total weight of team 2_**. ___ # Notes * **_Array size_** is *at least 1*. * **_All numbers_** will be **positive**. ___ # Input >> Output Examples ``` rowWeights([13, 27, 49]) ==> return (62, 27) ``` ## **_Explanation_**: **_The first element_** `62` is *the total weight of team 1*, and **_the second element_** `27` is *the total weight of team 2*. ___ ``` rowWeights([50, 60, 70, 80]) ==> return (120, 140) ``` ## **_Explanation_**: **_The first element_** `120` is *the total weight of team 1*, and **_the second element_** `140` is *the total weight of team 2*. ___ ``` rowWeights([80]) ==> return (80, 0) ``` ## **_Explanation_**: **_The first element_** `80` is *the total weight of team 1*, and **_the second element_** `0` is *the total weight of team 2*. ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a1, a2, ..., an, where ai denotes the distance of the i-th mark from the origin (a1 = 0, an = l). Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1 ≀ i ≀ j ≀ n), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, aj - ai = d). Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (x < y) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y. Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler. Input The first line contains four positive space-separated integers n, l, x, y (2 ≀ n ≀ 105, 2 ≀ l ≀ 109, 1 ≀ x < y ≀ l) β€” the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly. The second line contains a sequence of n integers a1, a2, ..., an (0 = a1 < a2 < ... < an = l), where ai shows the distance from the i-th mark to the origin. Output In the first line print a single non-negative integer v β€” the minimum number of marks that you need to add on the ruler. In the second line print v space-separated integers p1, p2, ..., pv (0 ≀ pi ≀ l). Number pi means that the i-th mark should be at the distance of pi centimeters from the origin. Print the marks in any order. If there are multiple solutions, print any of them. Examples Input 3 250 185 230 0 185 250 Output 1 230 Input 4 250 185 230 0 20 185 250 Output 0 Input 2 300 185 230 0 300 Output 2 185 230 Note In the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark. In the second sample you already can use the ruler to measure the distances of 185 and 230 centimeters, so you don't have to add new marks. In the third sample the ruler only contains the initial and the final marks. We will need to add two marks to be able to test the children's skills. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game. Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding n cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has). The aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints. A color hint goes like that: a player names some color and points at all the cards of this color. Similarly goes the value hint. A player names some value and points at all the cards that contain the value. Determine what minimum number of hints the other players should make for Borya to be certain about each card's color and value. -----Input----- The first line contains integer n (1 ≀ n ≀ 100) β€” the number of Borya's cards. The next line contains the descriptions of n cards. The description of each card consists of exactly two characters. The first character shows the color (overall this position can contain five distinct letters β€” R, G, B, Y, W). The second character shows the card's value (a digit from 1 to 5). Borya doesn't know exact order of the cards they lie in. -----Output----- Print a single integer β€” the minimum number of hints that the other players should make. -----Examples----- Input 2 G3 G3 Output 0 Input 4 G4 R4 R3 B3 Output 2 Input 5 B1 Y1 W1 G1 R1 Output 4 -----Note----- In the first sample Borya already knows for each card that it is a green three. In the second sample we can show all fours and all red cards. In the third sample you need to make hints about any four colors. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following: Add the integer x_{i} to the first a_{i} elements of the sequence. Append an integer k_{i} to the end of the sequence. (And hence the size of the sequence increases by 1) Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them! -----Input----- The first line contains a single integer nΒ (1 ≀ n ≀ 2Β·10^5) β€” the number of operations. The next n lines describe the operations. Each line will start with an integer t_{i} (1 ≀ t_{i} ≀ 3), denoting the type of the operation (see above). If t_{i} = 1, it will be followed by two integers a_{i}, x_{i} (|x_{i}| ≀ 10^3;Β 1 ≀ a_{i}). If t_{i} = 2, it will be followed by a single integer k_{i} (|k_{i}| ≀ 10^3). If t_{i} = 3, it will not be followed by anything. It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence. -----Output----- Output n lines each containing the average of the numbers in the sequence after the corresponding operation. The answer will be considered correct if its absolute or relative error doesn't exceed 10^{ - 6}. -----Examples----- Input 5 2 1 3 2 3 2 1 3 Output 0.500000 0.000000 1.500000 1.333333 1.500000 Input 6 2 1 1 2 20 2 2 1 2 -3 3 3 Output 0.500000 20.500000 14.333333 12.333333 17.500000 17.000000 -----Note----- In the second sample, the sequence becomes $\{0 \} \rightarrow \{0,1 \} \rightarrow \{20,21 \} \rightarrow \{20,21,2 \} \rightarrow \{17,18,2 \} \rightarrow \{17,18 \} \rightarrow \{17 \}$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Welcome to PC Koshien, players. At PC Koshien, competitions are currently being held in a total of three categories: programming category, mobile category, and Ichimai's picture CG category. Given the number of participants in each department, create a program that calculates the total number of participants. Input The input is given in the following format. p m c The input is one line, the number of participants in the programming department p (0 ≀ p ≀ 10000), the number of participants in the mobile department m (0 ≀ m ≀ 10000), the number of participants in the Ichimai picture CG department c (0) ≀ c ≀ 10000) is given. Output Output the total number of participants on one line. Examples Input 10 10 20 Output 40 Input 100 0 0 Output 100 Input 1000 1000 1000 Output 3000 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits. Input The first line contains integer n (2 ≀ n ≀ 100) β€” amount of digits in the phone number. The second line contains n digits β€” the phone number to divide into groups. Output Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any. Examples Input 6 549871 Output 54-98-71 Input 7 1198733 Output 11-987-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. Given is a string S, where each character is `0`, `1`, or `?`. Consider making a string S' by replacing each occurrence of `?` with `0` or `1` (we can choose the character for each `?` independently). Let us define the unbalancedness of S' as follows: * (The unbalancedness of S') = \max \\{ The absolute difference between the number of occurrences of `0` and `1` between the l-th and r-th character of S (inclusive) :\ 1 \leq l \leq r \leq |S|\\} Find the minimum possible unbalancedness of S'. Constraints * 1 \leq |S| \leq 10^6 * Each character of S is `0`, `1`, or `?`. Input Input is given from Standard Input in the following format: S Output Print the minimum possible unbalancedness of S'. Examples Input 0?? Output 1 Input 0??0 Output 2 Input ??00????0??0????0?0??00??1???11?1?1???1?11?111???1 Output 4 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points. Input The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide. Output The only line of output should contain the required sum of squares of distances between all pairs of points. Examples Input 4 1 1 -1 -1 1 -1 -1 1 Output 32 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Implement `String#to_cents`, which should parse prices expressed as `$1.23` and return number of cents, or in case of bad format return `nil`. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's call a sequence $b_1, b_2, b_3 \dots, b_{k - 1}, b_k$ almost increasing if $$\min(b_1, b_2) \le \min(b_2, b_3) \le \dots \le \min(b_{k - 1}, b_k).$$ In particular, any sequence with no more than two elements is almost increasing. You are given a sequence of integers $a_1, a_2, \dots, a_n$. Calculate the length of its longest almost increasing subsequence. You'll be given $t$ test cases. Solve each test case independently. Reminder: a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 1000$) β€” the number of independent test cases. The first line of each test case contains a single integer $n$ ($2 \le n \le 5 \cdot 10^5$) β€” the length of the sequence $a$. The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) β€” the sequence itself. It's guaranteed that the total sum of $n$ over all test cases doesn't exceed $5 \cdot 10^5$. -----Output----- For each test case, print one integer β€” the length of the longest almost increasing subsequence. -----Examples----- Input 3 8 1 2 7 3 2 1 2 3 2 2 1 7 4 1 5 2 6 3 7 Output 6 2 7 -----Note----- In the first test case, one of the optimal answers is subsequence $1, 2, 7, 2, 2, 3$. In the second and third test cases, the whole sequence $a$ is already almost increasing. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Many years ago Berland was a small country where only $n$ people lived. Each person had some savings: the $i$-th one had $a_i$ burles. The government considered a person as wealthy if he had at least $x$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that: the government chooses some subset of people (maybe all of them); the government takes all savings from the chosen people and redistributes the savings among the chosen people equally. For example, consider the savings as list $[5, 1, 2, 1]$: if the government chose the $1$-st and the $3$-rd persons then it, at first, will take all $5 + 2 = 7$ burles and after that will return $3.5$ burles to the chosen people. As a result, the savings will become $[3.5, 1, 3.5, 1]$. A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms. -----Input----- The first line contains single integer $T$ ($1 \le T \le 1000$) β€” the number of test cases. Next $2T$ lines contain the test cases β€” two lines per test case. The first line contains two integers $n$ and $x$ ($1 \le n \le 10^5$, $1 \le x \le 10^9$) β€” the number of people and the minimum amount of money to be considered as wealthy. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) β€” the initial savings of each person. It's guaranteed that the total sum of $n$ doesn't exceed $10^5$. -----Output----- Print $T$ integers β€” one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms. -----Example----- Input 4 4 3 5 1 2 1 4 10 11 9 11 9 2 5 4 3 3 7 9 4 9 Output 2 4 0 3 -----Note----- The first test case is described in the statement. In the second test case, the government, for example, could carry out two reforms: $[\underline{11}, \underline{9}, 11, 9] \rightarrow [10, 10, \underline{11}, \underline{9}] \rightarrow [10, 10, 10, 10]$. In the third test case, the government couldn't make even one person wealthy. In the fourth test case, the government could choose all people to carry out a reform: $[\underline{9}, \underline{4}, \underline{9}] \rightarrow [7\frac{1}{3}, 7\frac{1}{3}, 7\frac{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. A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≀ k1 < k2 < ... < k|x| ≀ |s|). You've got two strings β€” s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1 ≀ i ≀ |s|), there is such subsequence x = sk1sk2... sk|x| of string s, that x = t and for some j (1 ≀ j ≀ |x|) kj = i. Input The first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2Β·105. Output Print "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise. Examples Input abab ab Output Yes Input abacaba aba Output No Input abc ba Output No Note In the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once. In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t. In the third sample there is no occurrence of string t in string s. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Lord Omkar would like to have a tree with n nodes (3 ≀ n ≀ 10^5) and has asked his disciples to construct the tree. However, Lord Omkar has created m (1 ≀ m < n) restrictions to ensure that the tree will be as heavenly as possible. A tree with n nodes is an connected undirected graph with n nodes and n-1 edges. Note that for any two nodes, there is exactly one simple path between them, where a simple path is a path between two nodes that does not contain any node more than once. Here is an example of a tree: <image> A restriction consists of 3 pairwise distinct integers, a, b, and c (1 ≀ a,b,c ≀ n). It signifies that node b cannot lie on the simple path between node a and node c. Can you help Lord Omkar and become his most trusted disciple? You will need to find heavenly trees for multiple sets of restrictions. It can be shown that a heavenly tree will always exist for any set of restrictions under the given constraints. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers, n and m (3 ≀ n ≀ 10^5, 1 ≀ m < n), representing the size of the tree and the number of restrictions. The i-th of the next m lines contains three integers a_i, b_i, c_i (1 ≀ a_i, b_i, c_i ≀ n, a, b, c are distinct), signifying that node b_i cannot lie on the simple path between nodes a_i and c_i. It is guaranteed that the sum of n across all test cases will not exceed 10^5. Output For each test case, output n-1 lines representing the n-1 edges in the tree. On each line, output two integers u and v (1 ≀ u, v ≀ n, u β‰  v) signifying that there is an edge between nodes u and v. Given edges have to form a tree that satisfies Omkar's restrictions. Example Input 2 7 4 1 2 3 3 4 5 5 6 7 6 5 4 5 3 1 2 3 2 3 4 3 4 5 Output 1 2 1 3 3 5 3 4 2 7 7 6 5 1 1 3 3 2 2 4 Note The output of the first sample case corresponds to the following tree: <image> For the first restriction, the simple path between 1 and 3 is 1, 3, which doesn't contain 2. The simple path between 3 and 5 is 3, 5, which doesn't contain 4. The simple path between 5 and 7 is 5, 3, 1, 2, 7, which doesn't contain 6. The simple path between 6 and 4 is 6, 7, 2, 1, 3, 4, which doesn't contain 5. Thus, this tree meets all of the restrictions. The output of the second sample case corresponds to the following tree: <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. Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them. He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (iβ‰ j), he has to pay the cost separately for transforming each of them (See Sample 2). Find the minimum total cost to achieve his objective. -----Constraints----- - 1≦N≦100 - -100≦a_i≦100 -----Input----- The input is given from Standard Input in the following format: N a_1 a_2 ... a_N -----Output----- Print the minimum total cost to achieve Evi's objective. -----Sample Input----- 2 4 8 -----Sample Output----- 8 Transforming the both into 6s will cost (4-6)^2+(8-6)^2=8 dollars, which is the minimum. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K. The order of a,b,c does matter, and some of them can be the same. -----Constraints----- - 1 \leq N,K \leq 2\times 10^5 - N and K are integers. -----Input----- Input is given from Standard Input in the following format: N K -----Output----- Print the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K. -----Sample Input----- 3 2 -----Sample Output----- 9 (1,1,1),(1,1,3),(1,3,1),(1,3,3),(2,2,2),(3,1,1),(3,1,3),(3,3,1) and (3,3,3) 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. Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations: multiply the current number by 2 (that is, replace the number x by 2Β·x); append the digit 1 to the right of current number (that is, replace the number x by 10Β·x + 1). You need to help Vasily to transform the number a into the number b using only the operations described above, or find that it is impossible. Note that in this task you are not required to minimize the number of operations. It suffices to find any way to transform a into b. -----Input----- The first line contains two positive integers a and b (1 ≀ a < b ≀ 10^9)Β β€” the number which Vasily has and the number he wants to have. -----Output----- If there is no way to get b from a, print "NO" (without quotes). Otherwise print three lines. On the first line print "YES" (without quotes). The second line should contain single integer kΒ β€” the length of the transformation sequence. On the third line print the sequence of transformations x_1, x_2, ..., x_{k}, where: x_1 should be equal to a, x_{k} should be equal to b, x_{i} should be obtained from x_{i} - 1 using any of two described operations (1 < i ≀ k). If there are multiple answers, print any of them. -----Examples----- Input 2 162 Output YES 5 2 4 8 81 162 Input 4 42 Output NO Input 100 40021 Output YES 5 100 200 2001 4002 40021 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. <image> Input The input contains two integers a, b (1 ≀ a ≀ 10, 0 ≀ b ≀ 22Β·a - 1) separated by a single space. Output Output two integers separated by a single space. Examples Input 1 0 Output 0 0 Input 2 15 Output 3 0 Input 4 160 Output 12 12 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil"). However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere. For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities. Output Print the answer on a single line β€” the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes). Examples Input 2 7 4 Output 2 Input 7 7 4 47 100 4 9 12 Output Still Rozdil Note In the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one β€” 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2. In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a string s consisting of `A`, `B` and `C`. Snuke wants to perform the following operation on s as many times as possible: * Choose a contiguous substring of s that reads `ABC` and replace it with `BCA`. Find the maximum possible number of operations. Constraints * 1 \leq |s| \leq 200000 * Each character of s is `A`, `B` and `C`. Input Input is given from Standard Input in the following format: s Output Find the maximum possible number of operations. Examples Input ABCABC Output 3 Input C Output 0 Input ABCACCBABCBCAABCB Output 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. Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number. One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment. Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so. Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted β€” that is, one call connects exactly two people. -----Input----- The first line contains integer n (1 ≀ n ≀ 10^3) β€” the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id_1, id_2, ..., id_{n} (0 ≀ id_{i} ≀ 10^9). Number id_{i} equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise. Consider the secretaries indexed from 1 to n in some way. -----Output----- Print a single integer β€” the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place. -----Examples----- Input 6 0 1 7 1 7 10 Output 2 Input 3 1 1 1 Output -1 Input 1 0 Output 0 -----Note----- In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5. In the second test sample the described situation is impossible as conferences aren't allowed. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. While doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute $1 + 3$ using the calculator, he gets $2$ instead of $4$. But when he tries computing $1 + 4$, he gets the correct answer, $5$. Puzzled by this mystery, he opened up his calculator and found the answer to the riddle: the full adders became half adders! So, when he tries to compute the sum $a + b$ using the calculator, he instead gets the xorsum $a \oplus b$ (read the definition by the link: https://en.wikipedia.org/wiki/Exclusive_or). As he saw earlier, the calculator sometimes gives the correct answer. And so, he wonders, given integers $l$ and $r$, how many pairs of integers $(a, b)$ satisfy the following conditions: $$a + b = a \oplus b$$ $$l \leq a \leq r$$ $$l \leq b \leq r$$ However, Daniel the Barman is going to the bar and will return in two hours. He tells you to solve the problem before he returns, or else you will have to enjoy being blocked. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 100$) β€” the number of testcases. Then, $t$ lines follow, each containing two space-separated integers $l$ and $r$ ($0 \le l \le r \le 10^9$). -----Output----- Print $t$ integers, the $i$-th integer should be the answer to the $i$-th testcase. -----Example----- Input 3 1 4 323 323 1 1000000 Output 8 0 3439863766 -----Note----- $a \oplus b$ denotes the bitwise XOR of $a$ and $b$. For the first testcase, the pairs are: $(1, 2)$, $(1, 4)$, $(2, 1)$, $(2, 4)$, $(3, 4)$, $(4, 1)$, $(4, 2)$, and $(4, 3)$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia. The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing $N$ gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves: Take one gold coin from the chest. Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even. Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally. -----Input----- The first line contains a single integer $T$ $(1 \le T \le 10^5)$ denotes the number of test cases. The next $T$ lines each contain a single integer $N$ $(1 \le N \le 10^{18})$. -----Output----- $T$ lines, each line is the answer requested by Mr. Chanek. -----Example----- Input 2 5 6 Output 2 4 -----Note----- For the first case, the game is as follows: Mr. Chanek takes one coin. The opponent takes two coins. Mr. Chanek takes one coin. The opponent takes one coin. For the second case, the game is as follows: Mr. Chanek takes three coins. The opponent takes one coin. Mr. Chanek takes one coin. The opponent takes one coin. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better. It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string. After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious. Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights. Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” the number of test cases. The first line of each test case contains two integers n,q (1 ≀ n ≀ 2 β‹… 10^5, 0 ≀ q ≀ 2 β‹… 10^5). The second line of each test case contains a binary string s of length n. The third line of each test case contains a binary string f of length n. Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≀ l_i ≀ r_i ≀ n) β€” bounds of the segment, that Nanako will inspect on the i-th day. It is guaranteed that the sum of n for all test cases doesn't exceed 2 β‹… 10^5, and the sum of q for all test cases doesn't exceed 2 β‹… 10^5. Output For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO". You can print each letter in any case (upper or lower). Example Input 4 5 2 00000 00111 1 5 1 3 2 1 00 01 1 2 10 6 1111111111 0110001110 1 10 5 9 7 10 1 7 3 5 6 10 5 2 10000 11000 2 5 1 3 Output YES NO YES NO Note In the first test case, \underline{00000} β†’ \underline{000}11 β†’ 00111 is one of the possible sequences of string changes. In the second test case, it can be shown that it is impossible to have the string f at the end. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a sequence a_1, a_2, ..., a_n, consisting of integers. You can apply the following operation to this sequence: choose some integer x and move all elements equal to x either to the beginning, or to the end of a. Note that you have to move all these elements in one direction in one operation. For example, if a = [2, 1, 3, 1, 1, 3, 2], you can get the following sequences in one operation (for convenience, denote elements equal to x as x-elements): * [1, 1, 1, 2, 3, 3, 2] if you move all 1-elements to the beginning; * [2, 3, 3, 2, 1, 1, 1] if you move all 1-elements to the end; * [2, 2, 1, 3, 1, 1, 3] if you move all 2-elements to the beginning; * [1, 3, 1, 1, 3, 2, 2] if you move all 2-elements to the end; * [3, 3, 2, 1, 1, 1, 2] if you move all 3-elements to the beginning; * [2, 1, 1, 1, 2, 3, 3] if you move all 3-elements to the end; You have to determine the minimum number of such operations so that the sequence a becomes sorted in non-descending order. Non-descending order means that for all i from 2 to n, the condition a_{i-1} ≀ a_i is satisfied. Note that you have to answer q independent queries. Input The first line contains one integer q (1 ≀ q ≀ 3 β‹… 10^5) β€” the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer n (1 ≀ n ≀ 3 β‹… 10^5) β€” the number of elements. The second line of each query contains n integers a_1, a_2, ... , a_n (1 ≀ a_i ≀ n) β€” the elements. It is guaranteed that the sum of all n does not exceed 3 β‹… 10^5. Output For each query print one integer β€” the minimum number of operation for sorting sequence a in non-descending order. Example Input 3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7 Output 2 0 1 Note In the first query, you can move all 1-elements to the beginning (after that sequence turn into [1, 1, 1, 3, 6, 6, 3]) and then move all 6-elements to the end. In the second query, the sequence is sorted initially, so the answer is zero. In the third query, you have to move all 2-elements to the beginning. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 positive integer n, let us define f(n) as the number of digits in base 10. You are given an integer S. Count the number of the pairs of positive integers (l, r) (l \leq r) such that f(l) + f(l + 1) + ... + f(r) = S, and find the count modulo 10^9 + 7. -----Constraints----- - 1 \leq S \leq 10^8 -----Input----- Input is given from Standard Input in the following format: S -----Output----- Print the answer. -----Sample Input----- 1 -----Sample Output----- 9 There are nine pairs (l, r) that satisfies the condition: (1, 1), (2, 2), ..., (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. You are given a chessboard consisting of $n$ rows and $n$ columns. Rows are numbered from bottom to top from $1$ to $n$. Columns are numbered from left to right from $1$ to $n$. The cell at the intersection of the $x$-th column and the $y$-th row is denoted as $(x, y)$. Furthermore, the $k$-th column is a special column. Initially, the board is empty. There are $m$ changes to the board. During the $i$-th change one pawn is added or removed from the board. The current board is good if we can move all pawns to the special column by the followings rules: Pawn in the cell $(x, y)$ can be moved to the cell $(x, y + 1)$, $(x - 1, y + 1)$ or $(x + 1, y + 1)$; You can make as many such moves as you like; Pawns can not be moved outside the chessboard; Each cell can not contain more than one pawn. The current board may not always be good. To fix it, you can add new rows to the board. New rows are added at the top, i. e. they will have numbers $n+1, n+2, n+3, \dots$. After each of $m$ changes, print one integer β€” the minimum number of rows which you have to add to make the board good. -----Input----- The first line contains three integers $n$, $k$ and $m$ ($1 \le n, m \le 2 \cdot 10^5; 1 \le k \le n$) β€” the size of the board, the index of the special column and the number of changes respectively. Then $m$ lines follow. The $i$-th line contains two integers $x$ and $y$ ($1 \le x, y \le n$) β€” the index of the column and the index of the row respectively. If there is no pawn in the cell $(x, y)$, then you add a pawn to this cell, otherwise β€” you remove the pawn from this cell. -----Output----- After each change print one integer β€” the minimum number of rows which you have to add to make the board good. -----Example----- Input 5 3 5 4 4 3 5 2 4 3 4 3 5 Output 0 1 2 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. Please notice the unusual memory limit of this problem. Orac likes games. Recently he came up with the new game, "Game of Life". You should play this game on a black and white grid with $n$ rows and $m$ columns. Each cell is either black or white. For each iteration of the game (the initial iteration is $0$), the color of each cell will change under the following rules: If there are no adjacent cells with the same color as this cell on the current iteration, the color of it on the next iteration will be the same. Otherwise, the color of the cell on the next iteration will be different. Two cells are adjacent if they have a mutual edge. Now Orac has set an initial situation, and he wants to know for the cell $(i,j)$ (in $i$-th row and $j$-th column), what will be its color at the iteration $p$. He may ask you these questions several times. -----Input----- The first line contains three integers $n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000)$, representing the number of rows, columns, and the number of Orac queries. Each of the following $n$ lines contains a binary string of length $m$, the $j$-th character in $i$-th line represents the initial color of cell $(i,j)$. '0' stands for white, '1' stands for black. Each of the following $t$ lines contains three integers $i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18})$, representing a query from Orac. -----Output----- Print $t$ lines, in $i$-th line you should print the answer to the $i$-th query by Orac. If the color of this cell is black, you should print '1'; otherwise, you should write '0'. -----Examples----- Input 3 3 3 000 111 000 1 1 1 2 2 2 3 3 3 Output 1 1 1 Input 5 2 2 01 10 01 10 01 1 1 4 5 1 4 Output 0 0 Input 5 5 3 01011 10110 01101 11010 10101 1 1 4 1 2 3 5 5 3 Output 1 0 1 Input 1 1 3 0 1 1 1 1 1 2 1 1 3 Output 0 0 0 -----Note----- [Image] For the first example, the picture above shows the initial situation and the color of cells at the iteration $1$, $2$, and $3$. We can see that the color of $(1,1)$ at the iteration $1$ is black, the color of $(2,2)$ at the iteration $2$ is black, and the color of $(3,3)$ at the iteration $3$ is also black. For the second example, you can prove that the cells will never change their colors. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 games in a football tournament. Three teams are participating in it. Currently k games had already been played. You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d_1 and that of between second and third team will be d_2. You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament? Note that outcome of a match can not be a draw, it has to be either win or loss. -----Input----- The first line of the input contains a single integer corresponding to number of test cases t (1 ≀ t ≀ 10^5). Each of the next t lines will contain four space-separated integers n, k, d_1, d_2 (1 ≀ n ≀ 10^12;Β 0 ≀ k ≀ n;Β 0 ≀ d_1, d_2 ≀ k) β€” data for the current test case. -----Output----- For each test case, output a single line containing either "yes" if it is possible to have no winner of tournament, or "no" otherwise (without quotes). -----Examples----- Input 5 3 0 0 0 3 3 0 0 6 4 1 0 6 3 3 0 3 3 3 2 Output yes yes yes no no -----Note----- Sample 1. There has not been any match up to now (k = 0, d_1 = 0, d_2 = 0). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win. Sample 2. You missed all the games (k = 3). As d_1 = 0 and d_2 = 0, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is "yes". Sample 3. You missed 4 matches, and d_1 = 1, d_2 = 0. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Amugae has a hotel consisting of $10$ rooms. The rooms are numbered from $0$ to $9$ from left to right. The hotel has two entrances β€” one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance. One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory. -----Input----- The first line consists of an integer $n$ ($1 \le n \le 10^5$), the number of events in Amugae's memory. The second line consists of a string of length $n$ describing the events in chronological order. Each character represents: 'L': A customer arrives from the left entrance. 'R': A customer arrives from the right entrance. '0', '1', ..., '9': The customer in room $x$ ($0$, $1$, ..., $9$ respectively) leaves. It is guaranteed that there is at least one empty room when a customer arrives, and there is a customer in the room $x$ when $x$ ($0$, $1$, ..., $9$) is given. Also, all the rooms are initially empty. -----Output----- In the only line, output the hotel room's assignment status, from room $0$ to room $9$. Represent an empty room as '0', and an occupied room as '1', without spaces. -----Examples----- Input 8 LLRL1RL1 Output 1010000011 Input 9 L0L0LLRR9 Output 1100000010 -----Note----- In the first example, hotel room's assignment status after each action is as follows. First of all, all rooms are empty. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. L: one more customer from the left entrance. Assignment status is 1110000001. 1: the customer in room $1$ leaves. Assignment status is 1010000001. R: one more customer from the right entrance. Assignment status is 1010000011. L: one more customer from the left entrance. Assignment status is 1110000011. 1: the customer in room $1$ leaves. Assignment status is 1010000011. So after all, hotel room's final assignment status is 1010000011. In the second example, hotel room's assignment status after each action is as follows. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. 0: the customer in room $0$ leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000 again. 0: the customer in room $0$ leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. R: one more customer from the right entrance. Assignment status is 1100000011. 9: the customer in room $9$ leaves. Assignment status is 1100000010. So after all, hotel room's final assignment status is 1100000010. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Menger Sponge is a three-dimensional fractal, first described by Karl Menger in 1926. ![Mengers Sponge (Level 0-3)](http://i.imgur.com/V6Rb4Za.jpg) ###### _An illustration of the iterative construction of a Menger sponge_ A method of constructing a Menger Sponge can be visualized as follows: 1. Start from a cube (first part of image). 2. Scale down the cube so that side length is 1/3 of its original, and make 20 copies of it. 3. Place the copies so that they measure the same size as the original cube but without its central parts (next part of image) 4. Repeat the process from step 2 for the new smaller cubes from the previous step. 5. In each iteration (e.g. repeating the last three steps), the effect will be that parts of the cube will be removed, they'll never be added. Menger sponge will always consist of parts will never be removed, regardless of how many iterations you do. ___ An alternative explanation: 1. Start from a cube (first part of image). 2. Devide each cube into 27 equal sized cubes. 3. Remove the middle-cube and the six cubes on each side of the group of 27 cubes (second part of image). 4. Repeat the process from step 2 for the smaller cubes (third and fourth part of image). ## Task In this kata you will create a function that takes non negative integers (from 0 to n) and return the amount of cubes that the Menger Sponge would have in that specific iteration. ## Example ``` calc_ms(0) == 1 calc_ms(1) == 20 calc_ms(2) == 400 calc_ms(3) == 8000 calc_ms(4) == 160000 calc_ms(5) == 3200000 calc_ms(6) == 64000000 ``` Happy coding! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles. At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the height of the i-th castle is equal to h_{i}. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition h_{i} ≀ h_{i} + 1 holds for all i from 1 to n - 1. Squidward suggested the following process of sorting castles: Castles are split into blocksΒ β€” groups of consecutive castles. Therefore the block from i to j will include castles i, i + 1, ..., j. A block may consist of a single castle. The partitioning is chosen in such a way that every castle is a part of exactly one block. Each block is sorted independently from other blocks, that is the sequence h_{i}, h_{i} + 1, ..., h_{j} becomes sorted. The partitioning should satisfy the condition that after each block is sorted, the sequence h_{i} becomes sorted too. This may always be achieved by saying that the whole sequence is a single block. Even Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements. -----Input----- The first line of the input contains a single integer n (1 ≀ n ≀ 100 000)Β β€” the number of castles Spongebob, Patrick and Squidward made from sand during the day. The next line contains n integers h_{i} (1 ≀ h_{i} ≀ 10^9). The i-th of these integers corresponds to the height of the i-th castle. -----Output----- Print the maximum possible number of blocks in a valid partitioning. -----Examples----- Input 3 1 2 3 Output 3 Input 4 2 1 3 2 Output 2 -----Note----- In the first sample the partitioning looks like that: [1][2][3]. [Image] In the second sample the partitioning is: [2, 1][3, 2] [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Problem H: Squid Multiplication Squid Eiko loves mathematics. Especially she loves to think about integer. One day, Eiko found a math problem from a website. "A sequence b ={ai + aj | i < j } is generated from a sequence a ={a0 , ... , an | ai is even if i is 0, otherwise ai is odd}. Given the sequence b , find the sequence a ." This problem is easy for Eiko and she feels boring. So, she made a new problem by modifying this problem . "A sequence b ={ai *aj | i < j } is generated from a sequence a ={ a0, ... , an | ai is even if i is 0, otherwise ai is odd}. Given the sequence b , find the sequence a ." Your task is to solve the problem made by Eiko. Input Input consists of multiple datasets. Each dataset is given by following formats. n b0 b1 ... bn*(n+1)/2-1 n is the number of odd integers in the sequence a. The range of n is 2 ≀ n ≀ 250. bi is separated by a space. Each bi is 1 ≀ bi ≀ 263-1. The end of the input consists of a single 0. Output For each dataset, you should output two lines. First line contains a0, an even number in the sequence a. The second line contains n odd elements separated by a space. The odd elements are sorted by increasing order. You can assume that the result is greater than or equal to 1 and less than or equal to 231-1. Example Input 3 6 10 14 15 21 35 2 30 42 35 0 Output 2 3 5 7 6 5 7 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This is a story of a world somewhere far from the earth. In this world, the land is parted into a number of countries ruled by empires. This world is not very peaceful: they have been involved in army race. They are competing in production of missiles in particular. Nevertheless, no countries have started wars for years. Actually they have a reason they can’t get into wars - they have missiles much more than enough to destroy the entire world. Once a war would begin among countries, none of them could remain. These missiles have given nothing but scare to people. The competition has caused big financial and psychological pressure to countries. People have been tired. Military have been tired. Even empires have been tired. No one wishes to keep on missile production. So empires and diplomats of all countries held meetings quite a few times toward renouncement of missiles and abandon of further production. The meetings were quite difficult as they have different matters. However, they overcame such difficulties and finally came to the agreement of a treaty. The points include: * Each country will dispose all the missiles of their possession by a certain date. * The war potential should not be different by greater than a certain amount d among all countries. Let us describe more details on the second point. Each missile has its capability, which represents how much it can destroy the target. The war potential of each country is measured simply by the sum of capability over missiles possessed by that country. The treaty requires the difference to be not greater than d between the maximum and minimum potential of all the countries. Unfortunately, it is not clear whether this treaty is feasible. Every country is going to dispose their missiles only in the order of time they were produced, from the oldest to the newest. Some missiles have huge capability, and disposal of them may cause unbalance in potential. Your task is to write a program to see this feasibility. Input The input is a sequence of datasets. Each dataset is given in the following format: n d m1 c1,1 ... c1,m1 ... mn cn,1 ... cn,mn The first line contains two positive integers n and d, the number of countries and the tolerated difference of potential (n ≀ 100, d ≀ 1000). Then n lines follow. The i-th line begins with a non-negative integer mi, the number of the missiles possessed by the i-th country. It is followed by a sequence of mi positive integers. The j-th integer ci,j represents the capability of the j-th newest missile of the i-th country (ci,j ≀ 1000). These integers are separated by a single space. Note that the country disposes their missiles in the reverse order of the given sequence. The number of missiles is not greater than 10000. Also, you may assume the difference between the maximum and minimum potential does not exceed d in any dataset. The input is terminated by a line with two zeros. This line should not be processed. Output For each dataset, print a single line. If they can dispose all their missiles according to the treaty, print "Yes" (without quotes). Otherwise, print "No". Note that the judge is performed in a case-sensitive manner. No extra space or character is allowed. Example Input 3 3 3 4 1 1 2 1 5 2 3 3 3 3 3 2 3 1 2 1 5 2 3 3 0 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. Because of budget cuts one IT company established new non-financial reward system instead of bonuses. Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting feature gets "I suggested a new feature" pennant on his table. Because of the limited budget of the new reward system only 5 "I fixed a critical bug" pennants and 3 "I suggested a new feature" pennants were bought. In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded "I fixed a critical bug" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded "I suggested a new feature" pennants is passed on to his table. One man can have several pennants of one type and of course he can have pennants of both types on his table. There are n tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants. -----Input----- The only line of the input contains one integer n (1 ≀ n ≀ 500) β€” the number of tables in the IT company. -----Output----- Output one integer β€” the amount of ways to place the pennants on n tables. -----Examples----- Input 2 Output 24 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind. Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense modifier b_j and is worth cb_j coins. After choosing his equipment Roma can proceed to defeat some monsters. There are p monsters he can try to defeat. Monster k has defense x_k, attack y_k and possesses z_k coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster k can be defeated with a weapon i and an armor set j if a_i > x_k and b_j > y_k. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one. Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins. Help Roma find the maximum profit of the grind. Input The first line contains three integers n, m, and p (1 ≀ n, m, p ≀ 2 β‹… 10^5) β€” the number of available weapons, armor sets and monsters respectively. The following n lines describe available weapons. The i-th of these lines contains two integers a_i and ca_i (1 ≀ a_i ≀ 10^6, 1 ≀ ca_i ≀ 10^9) β€” the attack modifier and the cost of the weapon i. The following m lines describe available armor sets. The j-th of these lines contains two integers b_j and cb_j (1 ≀ b_j ≀ 10^6, 1 ≀ cb_j ≀ 10^9) β€” the defense modifier and the cost of the armor set j. The following p lines describe monsters. The k-th of these lines contains three integers x_k, y_k, z_k (1 ≀ x_k, y_k ≀ 10^6, 1 ≀ z_k ≀ 10^3) β€” defense, attack and the number of coins of the monster k. Output Print a single integer β€” the maximum profit of the grind. Example Input 2 3 3 2 3 4 7 2 4 3 2 5 11 1 2 4 2 1 6 3 4 6 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. We guessed some integer number $x$. You are given a list of almost all its divisors. Almost all means that there are all divisors except $1$ and $x$ in the list. Your task is to find the minimum possible integer $x$ that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number. You have to answer $t$ independent queries. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 25$) β€” the number of queries. Then $t$ queries follow. The first line of the query contains one integer $n$ ($1 \le n \le 300$) β€” the number of divisors in the list. The second line of the query contains $n$ integers $d_1, d_2, \dots, d_n$ ($2 \le d_i \le 10^6$), where $d_i$ is the $i$-th divisor of the guessed number. It is guaranteed that all values $d_i$ are distinct. -----Output----- For each query print the answer to it. If the input data in the query is contradictory and it is impossible to find such number $x$ that the given list of divisors is the list of almost all its divisors, print -1. Otherwise print the minimum possible $x$. -----Example----- Input 2 8 8 2 12 6 4 24 16 3 1 2 Output 48 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. According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment. Ways (1, 2) and (2, 1) should be regarded as different. Input The first line contains two integers n and d (1 ≀ n ≀ 1000, 1 ≀ d ≀ 109) β€” amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers β€” heights of all the soldiers in Bob's detachment. These numbers don't exceed 109. Output Output one number β€” amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d. Examples Input 5 10 10 20 50 60 65 Output 6 Input 5 1 55 30 29 31 55 Output 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. Given are a sequence of N integers A_1, A_2, \ldots, A_N and a positive integer S. For a pair of integers (L, R) such that 1\leq L \leq R \leq N, let us define f(L, R) as follows: - f(L, R) is the number of sequences of integers (x_1, x_2, \ldots , x_k) such that L \leq x_1 < x_2 < \cdots < x_k \leq R and A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S. Find the sum of f(L, R) over all pairs of integers (L, R) such that 1\leq L \leq R\leq N. Since this sum can be enormous, print it modulo 998244353. -----Constraints----- - All values in input are integers. - 1 \leq N \leq 3000 - 1 \leq S \leq 3000 - 1 \leq A_i \leq 3000 -----Input----- Input is given from Standard Input in the following format: N S A_1 A_2 ... A_N -----Output----- Print the sum of f(L, R), modulo 998244353. -----Sample Input----- 3 4 2 2 4 -----Sample Output----- 5 The value of f(L, R) for each pair is as follows, for a total of 5. - f(1,1) = 0 - f(1,2) = 1 (for the sequence (1, 2)) - f(1,3) = 2 (for (1, 2) and (3)) - f(2,2) = 0 - f(2,3) = 1 (for (3)) - f(3,3) = 1 (for (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. Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers l_{i} and r_{i}, and its elements are a[l_{i}], a[l_{i} + 1], ..., a[r_{i}]. Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible. You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible. The mex of a set S is a minimum possible non-negative integer that is not in S. -----Input----- The first line contains two integers n and m (1 ≀ n, m ≀ 10^5). The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers l_{i} and r_{i} (1 ≀ l_{i} ≀ r_{i} ≀ n), that describe the subarray a[l_{i}], a[l_{i} + 1], ..., a[r_{i}]. -----Output----- In the first line print single integerΒ β€” the maximum possible minimum mex. In the second line print n integersΒ β€” the array a. All the elements in a should be between 0 and 10^9. It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 10^9. If there are multiple solutions, print any of them. -----Examples----- Input 5 3 1 3 2 5 4 5 Output 2 1 0 2 1 0 Input 4 2 1 4 2 4 Output 3 5 2 0 1 -----Note----- The first example: the mex of the subarray (1, 3) is equal to 3, the mex of the subarray (2, 5) is equal to 3, the mex of the subarray (4, 5) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona 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. Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items? Input The only line of the input data contains a non-empty string consisting of letters "Π‘" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "Π‘", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo. Output Print the only number β€” the minimum number of times Polycarpus has to visit the closet. Examples Input CPCPCPC Output 7 Input CCCCCCPPPPPP Output 4 Input CCCCCCPPCPPPPPPPPPP Output 6 Input CCCCCCCCCC Output 2 Note In the first sample Polycarpus needs to take one item to the closet 7 times. In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice. In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice. In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go). Read the inputs from stdin solve the problem and write the answer to stdout (do 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 square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (n + 1) meters, he draws a cross (see picture for clarifications). John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw? <image> The figure shows the order in which John draws crosses for a square with side 4. The lower left square has two crosses. Overall John paints 17 crosses. Input The first line contains integer t (1 ≀ t ≀ 104) β€” the number of test cases. The second line contains t space-separated integers ni (1 ≀ ni ≀ 109) β€” the sides of the square for each test sample. Output For each test sample print on a single line the answer to it, that is, the number of crosses John will draw as he will move along the square of the corresponding size. Print the answers to the samples in the order in which the samples are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 4 8 100 Output 17 33 401 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. [INSPION FullBand Master - INSPION](https://www.youtube.com/watch?v=kwsciXm_7sA) [INSPION - IOLITE-SUNSTONE](https://www.youtube.com/watch?v=kwsciXm_7sA) On another floor of the A.R.C. Markland-N, the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world. His target is a network of n small gangs. This network contains exactly n - 1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links. By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 0 to n - 2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass S password layers, with S being defined by the following formula: $$$S = βˆ‘_{1 ≀ u < v ≀ n} mex(u, v)$$$ Here, mex(u, v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang u to gang v. Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of S, so that the AIs can be deployed efficiently. Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible S before he returns? Input The first line contains an integer n (2 ≀ n ≀ 3000), the number of gangs in the network. Each of the next n - 1 lines contains integers u_i and v_i (1 ≀ u_i, v_i ≀ n; u_i β‰  v_i), indicating there's a direct link between gangs u_i and v_i. It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path. Output Print the maximum possible value of S β€” the number of password layers in the gangs' network. Examples Input 3 1 2 2 3 Output 3 Input 5 1 2 1 3 1 4 3 5 Output 10 Note In the first example, one can achieve the maximum S with the following assignment: <image> With this assignment, mex(1, 2) = 0, mex(1, 3) = 2 and mex(2, 3) = 1. Therefore, S = 0 + 2 + 1 = 3. In the second example, one can achieve the maximum S with the following assignment: <image> With this assignment, all non-zero mex value are listed below: * mex(1, 3) = 1 * mex(1, 5) = 2 * mex(2, 3) = 1 * mex(2, 5) = 2 * mex(3, 4) = 1 * mex(4, 5) = 3 Therefore, S = 1 + 2 + 1 + 2 + 1 + 3 = 10. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an array $a$ of $n$ integers and an integer $s$. It is guaranteed that $n$ is odd. In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $s$. The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array $6, 5, 8$ is equal to $6$, since if we sort this array we will get $5, 6, 8$, and $6$ is located on the middle position. -----Input----- The first line contains two integers $n$ and $s$ ($1\le n\le 2\cdot 10^5-1$, $1\le s\le 10^9$)Β β€” the length of the array and the required value of median. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1\le a_i \le 10^9$)Β β€” the elements of the array $a$. It is guaranteed that $n$ is odd. -----Output----- In a single line output the minimum number of operations to make the median being equal to $s$. -----Examples----- Input 3 8 6 5 8 Output 2 Input 7 20 21 15 12 11 20 19 12 Output 6 -----Note----- In the first sample, $6$ can be increased twice. The array will transform to $8, 5, 8$, which becomes $5, 8, 8$ after sorting, hence the median is equal to $8$. In the second sample, $19$ can be increased once and $15$ can be increased five times. The array will become equal to $21, 20, 12, 11, 20, 20, 12$. If we sort this array we get $11, 12, 12, 20, 20, 20, 21$, this way the median is $20$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$. Constraints * $1 \leq n \leq 10,000$ * $0 \leq c_i \leq 100,000$ * $|E| < 500,000$ * All vertices are reachable from vertex $0$ Input In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format: $u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$ Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$). Output For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs. Example Input 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 Output 0 0 1 2 2 2 3 1 4 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm. Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows: <image> You have to write a program that allows you to determine what number will be in the cell with index x (1 ≀ x ≀ n) after Dima's algorithm finishes. Input The first line contains two integers n and q (1 ≀ n ≀ 1018, 1 ≀ q ≀ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer. Next q lines contain integers xi (1 ≀ xi ≀ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes. Output For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes. Examples Input 4 3 2 3 4 Output 3 2 4 Input 13 4 10 5 4 8 Output 13 3 8 9 Note The first example is shown in the picture. In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7]. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given is a three-digit integer N. Does N contain the digit 7? If so, print Yes; otherwise, print No. -----Constraints----- - 100 \leq N \leq 999 -----Input----- Input is given from Standard Input in the following format: N -----Output----- If N contains the digit 7, print Yes; otherwise, print No. -----Sample Input----- 117 -----Sample Output----- Yes 117 contains 7 as its last digit. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 binary strings $x$ and $y$, which are binary representations of some two integers (let's denote these integers as $f(x)$ and $f(y)$). You can choose any integer $k \ge 0$, calculate the expression $s_k = f(x) + f(y) \cdot 2^k$ and write the binary representation of $s_k$ in reverse order (let's denote it as $rev_k$). For example, let $x = 1010$ and $y = 11$; you've chosen $k = 1$ and, since $2^1 = 10_2$, so $s_k = 1010_2 + 11_2 \cdot 10_2 = 10000_2$ and $rev_k = 00001$. For given $x$ and $y$, you need to choose such $k$ that $rev_k$ is lexicographically minimal (read notes if you don't know what does "lexicographically" means). It's guaranteed that, with given constraints, $k$ exists and is finite. -----Input----- The first line contains a single integer $T$ ($1 \le T \le 100$) β€” the number of queries. Next $2T$ lines contain a description of queries: two lines per query. The first line contains one binary string $x$, consisting of no more than $10^5$ characters. Each character is either 0 or 1. The second line contains one binary string $y$, consisting of no more than $10^5$ characters. Each character is either 0 or 1. It's guaranteed, that $1 \le f(y) \le f(x)$ (where $f(x)$ is the integer represented by $x$, and $f(y)$ is the integer represented by $y$), both representations don't have any leading zeroes, the total length of $x$ over all queries doesn't exceed $10^5$, and the total length of $y$ over all queries doesn't exceed $10^5$. -----Output----- Print $T$ integers (one per query). For each query print such $k$ that $rev_k$ is lexicographically minimal. -----Example----- Input 4 1010 11 10001 110 1 1 1010101010101 11110000 Output 1 3 0 0 -----Note----- The first query was described in the legend. In the second query, it's optimal to choose $k = 3$. The $2^3 = 1000_2$ so $s_3 = 10001_2 + 110_2 \cdot 1000_2 = 10001 + 110000 = 1000001$ and $rev_3 = 1000001$. For example, if $k = 0$, then $s_0 = 10111$ and $rev_0 = 11101$, but $rev_3 = 1000001$ is lexicographically smaller than $rev_0 = 11101$. In the third query $s_0 = 10$ and $rev_0 = 01$. For example, $s_2 = 101$ and $rev_2 = 101$. And $01$ is lexicographically smaller than $101$. The quote from Wikipedia: "To determine which of two strings of characters comes when arranging in lexicographical order, their first letters are compared. If they differ, then the string whose first letter comes earlier in the alphabet comes before the other string. If the first letters are the same, then the second letters are compared, and so on. If a position is reached where one string has no more letters to compare while the other does, then the first (shorter) string is deemed to come first in alphabetical order." Read the inputs from stdin solve the problem and write the answer to stdout (do 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 image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into k by k blocks. If n and m are not divisible by k, the image is padded with only zeros on the right and bottom so that they are divisible by k. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some k. More specifically, the steps are to first choose k, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this k. The image must be compressible in that state. -----Input----- The first line of input will contain two integers n, m (2 ≀ n, m ≀ 2 500), the dimensions of the image. The next n lines of input will contain a binary string with exactly m characters, representing the image. -----Output----- Print a single integer, the minimum number of pixels needed to toggle to make the image compressible. -----Example----- Input 3 5 00100 10110 11001 Output 5 -----Note----- We first choose k = 2. The image is padded as follows: 001000 101100 110010 000000 We can toggle the image to look as follows: 001100 001100 000000 000000 We can see that this image is compressible for k = 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. Let's assume that v(n) is the largest prime number, that does not exceed n; u(n) is the smallest prime number strictly greater than n. Find $\sum_{i = 2}^{n} \frac{1}{v(i) u(i)}$. -----Input----- The first line contains integer tΒ (1 ≀ t ≀ 500) β€” the number of testscases. Each of the following t lines of the input contains integer n (2 ≀ n ≀ 10^9). -----Output----- Print t lines: the i-th of them must contain the answer to the i-th test as an irreducible fraction "p/q", where p, q are integers, q > 0. -----Examples----- Input 2 2 3 Output 1/6 7/30 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet β€” the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations: * alloc n β€” to allocate n bytes of the memory and return the allocated block's identifier x; * erase x β€” to erase the block with the identifier x; * defragment β€” to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th. The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL. The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT. The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order. In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration. You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands. Input The first line of the input data contains two positive integers t and m (1 ≀ t ≀ 100;1 ≀ m ≀ 100), where t β€” the amount of operations given to the memory manager for processing, and m β€” the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 ≀ n ≀ 100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment. Output Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks. Examples Input 6 10 alloc 5 alloc 3 erase 1 alloc 6 defragment alloc 6 Output 1 2 NULL 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: `2332, 110011, 54322345` For a given number ```num```, write a function which returns an array of all the numerical palindromes contained within each number. The array should be sorted in ascending order and any duplicates should be removed. In this kata, single digit numbers and numbers which start or end with zeros (such as `010` and `00`) are **NOT** considered valid numerical palindromes. If `num` contains no valid palindromes, return `"No palindromes found"`. Otherwise, return `"Not valid"` if the input is not an integer or is less than `0`. ## Examples ``` palindrome(1221) => [22, 1221] palindrome(34322122) => [22, 212, 343, 22122] palindrome(1001331) => [33, 1001, 1331] palindrome(1294) => "No palindromes found" palindrome("1221") => "Not valid" ``` --- ### Other Kata in this Series: Numerical Palindrome #1 Numerical Palindrome #1.5 Numerical Palindrome #2 Numerical Palindrome #3 Numerical Palindrome #3.5 Numerical Palindrome #4 Numerical Palindrome #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. Read problems statements in Mandarin Chinese, Russian and Vietnamese as well. Arrays have fallen out of Chef's good books, and he plans to destroy all arrays he possesses. He is left with the last array A, consisting of N positive integers. In order to destroy the array, he can perform the following 2 types of operations any number of times. Choose any 2 elements, say X and Y, from the given array A such that X != Y, and remove them, or Choose any 1 element, say X, from A, and remove it. In order to destroy the array as quickly as possible, Chef is interested in knowing the minimum number of operations required to destroy it. Please help him achieve this task. ------ Input ------ The first line of input contains a single integer T denoting the number of test cases. First line of each test case contains a single integer N β€” the number of integers in the array A. Second line of each test case contains N space separated integers denoting the array A. ------ Output ------ For each test case, output the required answer in a new line. ------ Constraints ------ 1 ≀ T ≀ 50000 1 ≀ N ≀ 50000 1 ≀ A_{i} ≀ 10^{9} sum of N over all test cases does not exceed 5 Γ— 10^{5} ----- Sample Input 1 ------ 3 2 1 2 2 1 1 3 1 2 3 ----- Sample Output 1 ------ 1 2 2 ----- explanation 1 ------ Test 1: In an operation, Chef can choose 2 elements X and Y such that X = 1 and Y = 2 and can destroy them as X != Y. Test 2: Chef cannot choose 2 elements X and Y such that X != Y. So, he has to use the second operation twice in order to destroy the array. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Thanos sort is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. -----Input----- The first line of input contains a single number $n$ ($1 \le n \le 16$) β€” the size of the array. $n$ is guaranteed to be a power of 2. The second line of input contains $n$ space-separated integers $a_i$ ($1 \le a_i \le 100$) β€” the elements of the array. -----Output----- Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. -----Examples----- Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 -----Note----- In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a program that takes in a letterclass ID of a ship and display the equivalent string class description of the given ID. Use the table below. Class ID Ship ClassB or bBattleShipC or cCruiserD or dDestroyerF or fFrigate -----Input----- The first line contains an integer T, the total number of testcases. Then T lines follow, each line contains a character. -----Output----- For each test case, display the Ship Class depending on ID, in a new line. -----Constraints----- - 1 ≀ T ≀ 1000 -----Example----- Input 3 B c D Output BattleShip Cruiser Destroyer Read the inputs from stdin solve the problem and write the answer to stdout (do 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 text of single-space separated words, consisting of small and capital Latin letters. Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text. Calculate the volume of the given text. -----Input----- The first line contains one integer number n (1 ≀ n ≀ 200) β€” length of the text. The second line contains text of single-space separated words s_1, s_2, ..., s_{i}, consisting only of small and capital Latin letters. -----Output----- Print one integer number β€” volume of text. -----Examples----- Input 7 NonZERO Output 5 Input 24 this is zero answer text Output 0 Input 24 Harbour Space University Output 1 -----Note----- In the first example there is only one word, there are 5 capital letters in it. In the second example all of the words contain 0 capital letters. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Changu and Mangu are great buddies. Once they found an infinite paper which had 1,2,3,4,5,6,7,8,......... till infinity, written on it. Both of them did not like the sequence and started deleting some numbers in the following way. ``` First they deleted every 2nd number. So remaining numbers on the paper: 1,3,5,7,9,11..........till infinity. Then they deleted every 3rd number. So remaining numbers on the paper: 1,3,7,9,13,15..........till infinity.. Then they deleted every 4th number. So remaining numbers on the paper: 1,3,7,13,15..........till infinity.``` Then kept on doing this (deleting every 5th, then every 6th ...) untill they got old and died. It is obvious that some of the numbers will never get deleted(E.g. 1,3,7,13..) and hence are know to us as survivor numbers. Given a number `n`, check whether its a survivor number or not. # Input/Output - `[input]` integer `n` `0 < n <= 10^8` - `[output]` a boolean value `true` if the number is a survivor else `false`. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.