question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare. The fare is constructed in the following manner. There are three types of tickets: a ticket for one trip costs 20 byteland rubles, a ticket for 90 minutes costs 50 byteland rubles, a ticket for one day (1440 minutes) costs 120 byteland rubles. Note that a ticket for x minutes activated at time t can be used for trips started in time range from t to t + x - 1, inclusive. Assume that all trips take exactly one minute. To simplify the choice for the passenger, the system automatically chooses the optimal tickets. After each trip starts, the system analyses all the previous trips and the current trip and chooses a set of tickets for these trips with a minimum total cost. Let the minimum total cost of tickets to cover all trips from the first to the current is a, and the total sum charged before is b. Then the system charges the passenger the sum a - b. You have to write a program that, for given trips made by a passenger, calculates the sum the passenger is charged after each trip. -----Input----- The first line of input contains integer number n (1 ≤ n ≤ 10^5) — the number of trips made by passenger. Each of the following n lines contains the time of trip t_{i} (0 ≤ t_{i} ≤ 10^9), measured in minutes from the time of starting the system. All t_{i} are different, given in ascending order, i. e. t_{i} + 1 > t_{i} holds for all 1 ≤ i < n. -----Output----- Output n integers. For each trip, print the sum the passenger is charged after it. -----Examples----- Input 3 10 20 30 Output 20 20 10 Input 10 13 45 46 60 103 115 126 150 256 516 Output 20 20 10 0 20 0 0 20 20 10 -----Note----- In the first example, the system works as follows: for the first and second trips it is cheaper to pay for two one-trip tickets, so each time 20 rubles is charged, after the third trip the system understands that it would be cheaper to buy a ticket for 90 minutes. This ticket costs 50 rubles, and the passenger had already paid 40 rubles, so it is necessary to charge 10 rubles only. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals. Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green — one yellow and one blue, and for a blue ball, three blue crystals are enough. Right now there are A yellow and B blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls. -----Input----- The first line features two integers A and B (0 ≤ A, B ≤ 10^9), denoting the number of yellow and blue crystals respectively at Grisha's disposal. The next line contains three integers x, y and z (0 ≤ x, y, z ≤ 10^9) — the respective amounts of yellow, green and blue balls to be obtained. -----Output----- Print a single integer — the minimum number of crystals that Grisha should acquire in addition. -----Examples----- Input 4 3 2 1 1 Output 2 Input 3 9 1 1 3 Output 1 Input 12345678 87654321 43043751 1000000000 53798715 Output 2147483648 -----Note----- In the first sample case, Grisha needs five yellow and four blue crystals to create two yellow balls, one green ball, and one blue ball. To do that, Grisha needs to obtain two additional crystals: one yellow and one blue. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Invitation Most of us played with toy blocks growing up. It was fun and you learned stuff. So what else can you do but rise to the challenge when a 3-year old exclaims, "Look, I made a square!", then pointing to a pile of blocks, "Can _you_ do it?" # These Blocks Just to play along, of course we'll be viewing these blocks in two dimensions. Depth now being disregarded, it turns out the pile has four different sizes of block: `1x1`, `1x2`, `1x3`, and `1x4`. The smallest one represents the area of a square, the other three are rectangular, and all differ by their width. Integers matching these four widths are used to represent the blocks in the input. # This Square Well, the kid made a `4x4` square from this pile, so you'll have to match that. Noticing the way they fit together, you realize the structure must be built in fours rows, one row at a time, where the blocks must be placed horizontally. With the known types of block, there are five types of row you could build: * 1 four-unit block * 1 three-unit block plus 1 one-unit bock (in either order) * 2 two-unit blocks * 1 two-unit block plus 2 one-unit blocks (in any order) * 4 one-unit blocks Amounts for all four of the block sizes in the pile will each vary from `0` to `16`. The total size of the pile will also vary from `0` to `16`. The order of rows is irrelevant. A valid square doesn't have to use up all the given blocks. # Some Examples Given `1, 3, 2, 2, 4, 1, 1, 3, 1, 4, 2` there are many ways you could construct a square. Here are three possibilities, as described by their four rows: * 1 four-unit block * 2 two-unit blocks * 1 four-unit block * 4 one-unit blocks > * 1 three-unit block plus 1 one-unit block * 2 two-unit blocks * 1 four-unit block * 1 one-unit block plus 1 three-unit block > * 2 two-unit blocks * 1 three-unit block plus 1 one-unit block * 1 four-unit block * 2 one-unit blocks plus 1 two-unit block > Given `1, 3, 2, 4, 3, 3, 2` there is no way to complete the task, as you could only build three rows of the correct length. The kid will not be impressed. * 2 two-unit blocks * 1 three-unit block plus 1 one-unit block * 1 four-unit block * (here only sadness) > # Input ```python blocks ~ a random list of integers (1 <= x <= 4) ``` # Output ```python True or False ~ whether you can build a square ``` # Enjoy! If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cb5eb1f03c3ff4778402099) to consider solving. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have a sandglass consisting of two bulbs, bulb A and bulb B. These bulbs contain some amount of sand. When we put the sandglass, either bulb A or B lies on top of the other and becomes the upper bulb. The other bulb becomes the lower bulb. The sand drops from the upper bulb to the lower bulb at a rate of 1 gram per second. When the upper bulb no longer contains any sand, nothing happens. Initially at time 0, bulb A is the upper bulb and contains a grams of sand; bulb B contains X-a grams of sand (for a total of X grams). We will turn over the sandglass at time r_1,r_2,..,r_K. Assume that this is an instantaneous action and takes no time. Here, time t refer to the time t seconds after time 0. You are given Q queries. Each query is in the form of (t_i,a_i). For each query, assume that a=a_i and find the amount of sand that would be contained in bulb A at time t_i. -----Constraints----- - 1≤X≤10^9 - 1≤K≤10^5 - 1≤r_1<r_2< .. <r_K≤10^9 - 1≤Q≤10^5 - 0≤t_1<t_2< .. <t_Q≤10^9 - 0≤a_i≤X (1≤i≤Q) - All input values are integers. -----Input----- The input is given from Standard Input in the following format: X K r_1 r_2 .. r_K Q t_1 a_1 t_2 a_2 : t_Q a_Q -----Output----- For each query, print the answer in its own line. -----Sample Input----- 180 3 60 120 180 3 30 90 61 1 180 180 -----Sample Output----- 60 1 120 In the first query, 30 out of the initial 90 grams of sand will drop from bulb A, resulting in 60 grams. In the second query, the initial 1 gram of sand will drop from bulb A, and nothing will happen for the next 59 seconds. Then, we will turn over the sandglass, and 1 second after this, bulb A contains 1 gram of sand at the time in question. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Encryption System A programmer developed a new encryption system. However, his system has an issue that two or more distinct strings are `encrypted' to the same string. We have a string encrypted by his system. To decode the original string, we want to enumerate all the candidates of the string before the encryption. Your mission is to write a program for this task. The encryption is performed taking the following steps. Given a string that consists only of lowercase letters ('a' to 'z'). 1. Change the first 'b' to 'a'. If there is no 'b', do nothing. 2. Change the first 'c' to 'b'. If there is no 'c', do nothing. ... 3. Change the first 'z' to 'y'. If there is no 'z', do nothing. Input The input consists of at most 100 datasets. Each dataset is a line containing an encrypted string. The encrypted string consists only of lowercase letters, and contains at least 1 and at most 20 characters. The input ends with a line with a single '#' symbol. Output For each dataset, the number of candidates n of the string before encryption should be printed in a line first, followed by lines each containing a candidate of the string before encryption. If n does not exceed 10, print all candidates in dictionary order; otherwise, print the first five and the last five candidates in dictionary order. Here, dictionary order is recursively defined as follows. The empty string comes the first in dictionary order. For two nonempty strings x = x1 ... xk and y = y1 ... yl, the string x precedes the string y in dictionary order if * x1 precedes y1 in alphabetical order ('a' to 'z'), or * x1 and y1 are the same character and x2 ... xk precedes y2 ... yl in dictionary order. Sample Input enw abc abcdefghijklmnopqrst z Output for the Sample Input 1 fox 5 acc acd bbd bcc bcd 17711 acceeggiikkmmooqqssu acceeggiikkmmooqqstt acceeggiikkmmooqqstu acceeggiikkmmooqrrtt acceeggiikkmmooqrrtu bcdefghijklmnopqrrtt bcdefghijklmnopqrrtu bcdefghijklmnopqrssu bcdefghijklmnopqrstt bcdefghijklmnopqrstu 0 Example Input enw abc abcdefghijklmnopqrst z # Output 1 fox 5 acc acd bbd bcc bcd 17711 acceeggiikkmmooqqssu acceeggiikkmmooqqstt acceeggiikkmmooqqstu acceeggiikkmmooqrrtt acceeggiikkmmooqrrtu bcdefghijklmnopqrrtt bcdefghijklmnopqrrtu bcdefghijklmnopqrssu bcdefghijklmnopqrstt bcdefghijklmnopqrstu 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. Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars. There are n banknote denominations on Mars: the value of i-th banknote is a_i. Natasha has an infinite number of banknotes of each denomination. Martians have k fingers on their hands, so they use a number system with base k. In addition, the Martians consider the digit d (in the number system with base k) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base k is d, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet. Determine for which values d Natasha can make the Martians happy. Natasha can use only her banknotes. Martians don't give her change. Input The first line contains two integers n and k (1 ≤ n ≤ 100 000, 2 ≤ k ≤ 100 000) — the number of denominations of banknotes and the base of the number system on Mars. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — denominations of banknotes on Mars. All numbers are given in decimal notation. Output On the first line output the number of values d for which Natasha can make the Martians happy. In the second line, output all these values in increasing order. Print all numbers in decimal notation. Examples Input 2 8 12 20 Output 2 0 4 Input 3 10 10 20 30 Output 1 0 Note Consider the first test case. It uses the octal number system. If you take one banknote with the value of 12, you will get 14_8 in octal system. The last digit is 4_8. If you take one banknote with the value of 12 and one banknote with the value of 20, the total value will be 32. In the octal system, it is 40_8. The last digit is 0_8. If you take two banknotes with the value of 20, the total value will be 40, this is 50_8 in the octal system. The last digit is 0_8. No other digits other than 0_8 and 4_8 can be obtained. Digits 0_8 and 4_8 could also be obtained in other ways. The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have N bags numbered 1 through N and N dishes numbered 1 through N. Bag i contains a_i coins, and each dish has nothing on it initially. Taro the first and Jiro the second will play a game against each other. They will alternately take turns, with Taro the first going first. In each player's turn, the player can make one of the following two moves: - When one or more bags contain coin(s): Choose one bag that contains coin(s) and one dish, then move all coins in the chosen bag onto the chosen dish. (The chosen dish may already have coins on it, or not.) - When no bag contains coins: Choose one dish with coin(s) on it, then remove one or more coins from the chosen dish. The player who first becomes unable to make a move loses. Determine the winner of the game when the two players play optimally. You are given T test cases. Solve each of them. -----Constraints----- - All values in input are integers. - 1 \leq T \leq 10^5 - 1 \leq N \leq 10^{5} - 1 \leq a_i \leq 10^9 - In one input file, the sum of N does not exceed 2 \times 10^5. -----Input----- Input is given from Standard Input in the following format: T \mathrm{case}_1 \vdots \mathrm{case}_T Each case is in the following format: N a_1 a_2 \cdots a_N -----Output----- Print T lines. The i-th line should contain First if Taro the first wins in the i-th test case, and Second if Jiro the second wins in the test case. -----Sample Input----- 3 1 10 2 1 2 21 476523737 103976339 266993 706803678 802362985 892644371 953855359 196462821 817301757 409460796 773943961 488763959 405483423 616934516 710762957 239829390 55474813 818352359 312280585 185800870 255245162 -----Sample Output----- Second First Second - In test case 1, Jiro the second wins. Below is one sequence of moves that results in Jiro's win: - In Taro the first's turn, he can only choose Bag 1 and move the coins onto Dish 1. - In Jiro the second's turn, he can choose Dish 1 and remove all coins from it, making Taro fail to make a move and lose. - Note that when there is a bag that contains coin(s), a player can only make a move in which he chooses a bag that contains coin(s) and moves the coin(s) onto a dish. - Similarly, note that when there is no bag that contains coin(s), a player can only make a move in which he chooses a dish and removes one or more 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. You are given two integers A and B as the input. Output the value of A + B. However, if A + B is 10 or greater, output error instead. -----Constraints----- - A and B are integers. - 1 ≤ A, B ≤ 9 -----Input----- Input is given from Standard Input in the following format: A B -----Output----- If A + B is 10 or greater, print the string error (case-sensitive); otherwise, print the value of A + B. -----Sample Input----- 6 3 -----Sample Output----- 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 have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times): choose two indexes, i and j (1 ≤ i < j ≤ n; (j - i + 1) is a prime number); swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments: tmp = a[i], a[i] = a[j], a[j] = tmp (tmp is a temporary variable). You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5). The next line contains n distinct integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ n). -----Output----- In the first line, print integer k (0 ≤ k ≤ 5n) — the number of used operations. Next, print the operations. Each operation must be printed as "i j" (1 ≤ i < j ≤ n; (j - i + 1) is a prime). If there are multiple answers, you can print any of them. -----Examples----- Input 3 3 2 1 Output 1 1 3 Input 2 1 2 Output 0 Input 4 4 2 3 1 Output 3 2 4 1 2 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. You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW". Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to $\frac{n}{2}$. In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied. Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made). -----Input----- The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard. The second line of the input contains $\frac{n}{2}$ integer numbers $p_{1}, p_{2}, \ldots, p_{\frac{n}{2}}$ (1 ≤ p_{i} ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct. -----Output----- Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color. -----Examples----- Input 6 1 2 6 Output 2 Input 10 1 2 3 4 5 Output 10 -----Note----- In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3. In the second example the possible strategy is to move $5 \rightarrow 9$ in 4 moves, then $4 \rightarrow 7$ in 3 moves, $3 \rightarrow 5$ in 2 moves and $2 \rightarrow 3$ in 1 move. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Two players are playing a game. The game is played on a sequence of positive integer pairs. The players make their moves alternatively. During his move the player chooses a pair and decreases the larger integer in the pair by a positive multiple of the smaller integer in the pair in such a way that both integers in the pair remain positive. If two numbers in some pair become equal then the pair is removed from the sequence. The player who can not make any move loses (or in another words the player who encounters an empty sequence loses). Given the sequence of positive integer pairs determine whether the first player can win or not (assuming that both players are playing optimally). -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. Each test starts with an integer N denoting the number of pairs. Each of the next N lines contains a pair of positive integers. -----Output----- For each test case, output a single line containing "YES" if the first player can win and "NO" otherwise. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 100 - All other integers are between 1 to 108 - The integers in each pair will be different -----Example----- Input: 3 1 2 3 2 4 5 5 6 2 2 3 3 5 Output: NO NO YES -----Explanation----- Example case 1. The first player don't have any choice other subtracting 2 from 3. So during the turn of the second player integer pair will be (2,1). The second player will win by subtracting 1 from 2. Example case 2. If the first player choose to move (4,5) to (4,1) the second player will make it to (1,1). If the first player choose to move (5,6) to (5,1) the second player will make it to (1,1). So regardless of the move of the first player, the second will always win. Example case 3. The first player will select pair (3,5) and make it to (3,2). Now both pairs are equal. So whatever the move of second player he will just mirror that move in another pair. This will ensure his win. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Your task is to find the number couple with the greatest difference from a given array of number-couples. All number couples will be given as strings and all numbers in them will be positive integers. For instance: ['56-23','1-100']; in this case, you should identify '1-100' as the number couple with the greatest difference and return it. In case there are more than one option, for instance ['1-3','5-7','2-3'], you should identify whichever is first, so in this case '1-3'. If there is no difference, like so ['11-11', '344-344'], return false. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Assume that a, b, and n are all positive integers. Let f (i) be the i-th fraction of the fraction a / b (0 ≤ f (i) ≤ 9). At this time, let s be the sum of f (i) from i = 1 to n. s = f (1) + f (2) + ... + f (n) Create a program that reads a, b, n, outputs s, and exits. Input The input consists of multiple datasets. For each dataset, three integers a (1 ≤ a ≤ 1000), b (1 ≤ b ≤ 10000), n (1 ≤ n ≤ 100) are given on one line, separated by blanks. The number of datasets does not exceed 100. Output Prints s on one line for each dataset. Example Input 1 2 3 2 3 4 5 4 3 4 3 2 Output 5 24 7 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. A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices. Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different. Output Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them. 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 5 2 1 2 2 3 3 4 2 5 Output 4 Input 5 3 1 2 2 3 3 4 4 5 Output 2 Note In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (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. At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn. More formally, the guys take turns giving each other one candy more than they received in the previous turn. This continued until the moment when one of them couldn’t give the right amount of candy. Candies, which guys got from each other, they don’t consider as their own. You need to know, who is the first who can’t give the right amount of candy. -----Input----- Single line of input data contains two space-separated integers a, b (1 ≤ a, b ≤ 10^9) — number of Vladik and Valera candies respectively. -----Output----- Pring a single line "Vladik’’ in case, if Vladik first who can’t give right amount of candy, or "Valera’’ otherwise. -----Examples----- Input 1 1 Output Valera Input 7 6 Output Vladik -----Note----- Illustration for first test case: [Image] Illustration for second test case: [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. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked $p^{k_i}$ problems from $i$-th category ($p$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given $n$ numbers $p^{k_i}$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $10^{9}+7$. -----Input----- Input consists of multiple test cases. The first line contains one integer $t$ $(1 \leq t \leq 10^5)$ — the number of test cases. Each test case is described as follows: The first line contains two integers $n$ and $p$ $(1 \leq n, p \leq 10^6)$. The second line contains $n$ integers $k_i$ $(0 \leq k_i \leq 10^6)$. The sum of $n$ over all test cases doesn't exceed $10^6$. -----Output----- Output one integer — the reminder of division the answer by $1\,000\,000\,007$. -----Example----- Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 -----Note----- You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $2$, but there is also a distribution where the difference is $10^9 + 8$, then the answer is $2$, not $1$. In the first test case of the example, there're the following numbers: $4$, $8$, $16$, $16$, and $8$. We can divide them into such two sets: ${4, 8, 16}$ and ${8, 16}$. Then the difference between the sums of numbers in sets would be $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 will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above. The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner? -----Constraints----- - -40 \leq X \leq 40 - X is an integer. -----Input----- Input is given from Standard Input in the following format: X -----Output----- Print Yes if you will turn on the air conditioner; print No otherwise. -----Sample Input----- 25 -----Sample 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. Two beavers, Timur and Marsel, play the following game. There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins. Timur makes the first move. The players play in the optimal way. Determine the winner. Input The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 109). Output Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes. Examples Input 1 15 4 Output Timur Input 4 9 5 Output Marsel Note In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur. In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers. The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence a_1, a_2, ..., a_m, where a_i is an integer that denotes the type of flower at the position i. This year the liana is very long (m ≥ n ⋅ k), and that means every citizen will get a wreath. Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts k flowers from the beginning of the liana, then another k flowers and so on. Each such piece of k flowers is called a workpiece. The machine works until there are less than k flowers on the liana. Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, k flowers must contain flowers of types b_1, b_2, ..., b_s, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter. Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least n workpieces? Input The first line contains four integers m, k, n and s (1 ≤ n, k, m ≤ 5 ⋅ 10^5, k ⋅ n ≤ m, 1 ≤ s ≤ k): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively. The second line contains m integers a_1, a_2, ..., a_m (1 ≤ a_i ≤ 5 ⋅ 10^5) — types of flowers on the liana. The third line contains s integers b_1, b_2, ..., b_s (1 ≤ b_i ≤ 5 ⋅ 10^5) — the sequence in Diana's schematic. Output If it's impossible to remove some of the flowers so that there would be at least n workpieces and at least one of them fullfills Diana's schematic requirements, output -1. Otherwise in the first line output one integer d — the number of flowers to be removed by Diana. In the next line output d different integers — the positions of the flowers to be removed. If there are multiple answers, print any. Examples Input 7 3 2 2 1 2 3 3 2 1 2 2 2 Output 1 4 Input 13 4 3 3 3 2 6 4 1 4 4 7 1 3 3 2 4 4 3 4 Output -1 Input 13 4 1 3 3 2 6 4 1 4 4 7 1 3 3 2 4 4 3 4 Output 9 1 2 3 4 5 9 11 12 13 Note In the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types [1, 2, 3] and [3, 2, 1]. Those workpieces don't fit Diana's schematic. But if you remove flower on 4-th place, the machine would output workpieces [1, 2, 3] and [2, 1, 2]. The second workpiece fits Diana's schematic. In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic. In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Bakry faced a problem, but since he's lazy to solve it, he asks for your help. You are given a tree of $n$ nodes, the $i$-th node has value $a_i$ assigned to it for each $i$ from $1$ to $n$. As a reminder, a tree on $n$ nodes is a connected graph with $n-1$ edges. You want to delete at least $1$, but at most $k-1$ edges from the tree, so that the following condition would hold: For every connected component calculate the bitwise XOR of the values of the nodes in it. Then, these values have to be the same for all connected components. Is it possible to achieve this condition? -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ $(1 \leq t \leq 5 \cdot 10^4)$. Description of the test cases follows. The first line of each test case contains two integers $n$ and $k$ $(2 \leq k \leq n \leq 10^5)$. The second line of each test case contains $n$ integers $a_1, a_2, ..., a_n$ $(1 \leq a_i \leq 10^9)$. The $i$-th of the next $n-1$ lines contains two integers $u_i$ and $v_i$ ($1 \leq u_i, v_i \leq n$, $u_i\neq v_i$), which means that there's an edge between nodes $u_i$ and $v_i$. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$. -----Output----- For each test case, you should output a single string. If you can delete the edges according to the conditions written above, output "YES" (without quotes). Otherwise, output "NO" (without quotes). You can print each letter of "YES" and "NO" in any case (upper or lower). -----Examples----- Input 5 2 2 1 3 1 2 5 5 3 3 3 3 3 1 2 2 3 1 4 4 5 5 2 1 7 2 3 5 1 2 2 3 1 4 4 5 5 3 1 6 4 1 2 1 2 2 3 1 4 4 5 3 3 1 7 4 1 2 2 3 Output NO YES NO YES NO -----Note----- It can be shown that the objection is not achievable for first, third, and fifth test cases. In the second test case, you can just remove all the edges. There will be $5$ connected components, each containing only one node with value $3$, so the bitwise XORs will be $3$ for all of them. In the fourth test case, this is the tree: . You can remove an edge $(4,5)$ The bitwise XOR of the first component will be, $a_1 \oplus a_2 \oplus a_3 \oplus a_4 = 1 \oplus 6 \oplus 4 \oplus 1 = 2$ (where $\oplus$ denotes the bitwise XOR). The bitwise XOR of the second component will be, $a_5 = 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. On a chessboard with a width of $10^9$ and a height of $10^9$, the rows are numbered from bottom to top from $1$ to $10^9$, and the columns are numbered from left to right from $1$ to $10^9$. Therefore, for each cell of the chessboard you can assign the coordinates $(x,y)$, where $x$ is the column number and $y$ is the row number. Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner — a cell with coordinates $(1,1)$. But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely — on the upper side of the field (that is, in any cell that is in the row with number $10^9$). Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells: Vertical. Each of these is defined by one number $x$. Such spells create an infinite blocking line between the columns $x$ and $x+1$. Horizontal. Each of these is defined by three numbers $x_1$, $x_2$, $y$. Such spells create a blocking segment that passes through the top side of the cells, which are in the row $y$ and in columns from $x_1$ to $x_2$ inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells. [Image] An example of a chessboard. Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell $(r_0,c_0)$ into the cell $(r_1,c_1)$ only under the condition that $r_1 = r_0$ or $c_1 = c_0$ and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples). Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number! -----Input----- The first line contains two integers $n$ and $m$ ($0 \le n,m \le 10^5$) — the number of vertical and horizontal spells. Each of the following $n$ lines contains one integer $x$ ($1 \le x < 10^9$) — the description of the vertical spell. It will create a blocking line between the columns of $x$ and $x+1$. Each of the following $m$ lines contains three integers $x_1$, $x_2$ and $y$ ($1 \le x_{1} \le x_{2} \le 10^9$, $1 \le y < 10^9$) — the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number $y$, in columns from $x_1$ to $x_2$ inclusive. It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points. -----Output----- In a single line print one integer — the minimum number of spells the rook needs to remove so it can get from the cell $(1,1)$ to at least one cell in the row with the number $10^9$ -----Examples----- Input 2 3 6 8 1 5 6 1 9 4 2 4 2 Output 1 Input 1 3 4 1 5 3 1 9 4 4 6 6 Output 1 Input 0 2 1 1000000000 4 1 1000000000 2 Output 2 Input 0 0 Output 0 Input 2 3 4 6 1 4 3 1 5 2 1 6 5 Output 2 -----Note----- In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell. [Image] Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home. In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell. $m$ Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home. In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them. [Image] Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home. In the fourth sample, we have no spells, which means that we do not need to remove anything. In the fifth example, we can remove the first vertical and third horizontal spells. [Image] Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a program which counts and reports the number of each alphabetical letter. Ignore the case of characters. Constraints * The number of characters in the sentence < 1200 Input A sentence in English is given in several lines. Output Prints the number of alphabetical letters in the following format: a : The number of 'a' b : The number of 'b' c : The number of 'c' . . z : The number of 'z' Example Input This is a pen. Output a : 1 b : 0 c : 0 d : 0 e : 1 f : 0 g : 0 h : 1 i : 2 j : 0 k : 0 l : 0 m : 0 n : 1 o : 0 p : 1 q : 0 r : 0 s : 2 t : 1 u : 0 v : 0 w : 0 x : 0 y : 0 z : 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The string $s$ is given, the string length is odd number. The string consists of lowercase letters of the Latin alphabet. As long as the string length is greater than $1$, the following operation can be performed on it: select any two adjacent letters in the string $s$ and delete them from the string. For example, from the string "lemma" in one operation, you can get any of the four strings: "mma", "lma", "lea" or "lem" In particular, in one operation, the length of the string reduces by $2$. Formally, let the string $s$ have the form $s=s_1s_2 \dots s_n$ ($n>1$). During one operation, you choose an arbitrary index $i$ ($1 \le i < n$) and replace $s=s_1s_2 \dots s_{i-1}s_{i+2} \dots s_n$. For the given string $s$ and the letter $c$, determine whether it is possible to make such a sequence of operations that in the end the equality $s=c$ will be true? In other words, is there such a sequence of operations that the process will end with a string of length $1$, which consists of the letter $c$? -----Input----- The first line of input data contains an integer $t$ ($1 \le t \le 10^3$) — the number of input test cases. The descriptions of the $t$ cases follow. Each test case is represented by two lines: string $s$, which has an odd length from $1$ to $49$ inclusive and consists of lowercase letters of the Latin alphabet; is a string containing one letter $c$, where $c$ is a lowercase letter of the Latin alphabet. -----Output----- For each test case in a separate line output: YES, if the string $s$ can be converted so that $s=c$ is true; NO otherwise. You can output YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive response). -----Examples----- Input 5 abcde c abcde b x y aaaaaaaaaaaaaaa a contest t Output YES NO NO YES YES -----Note----- In the first test case, $s$="abcde". You need to get $s$="c". For the first operation, delete the first two letters, we get $s$="cde". In the second operation, we delete the last two letters, so we get the expected value of $s$="c". In the third test case, $s$="x", it is required to get $s$="y". Obviously, this cannot be done. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Andi and Budi were given an assignment to tidy up their bookshelf of $n$ books. Each book is represented by the book title — a string $s_i$ numbered from $1$ to $n$, each with length $m$. Andi really wants to sort the book lexicographically ascending, while Budi wants to sort it lexicographically descending. Settling their fight, they decided to combine their idea and sort it asc-desc-endingly, where the odd-indexed characters will be compared ascendingly, and the even-indexed characters will be compared descendingly. A string $a$ occurs before a string $b$ in asc-desc-ending order if and only if in the first position where $a$ and $b$ differ, the following holds: if it is an odd position, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$; if it is an even position, the string $a$ has a letter that appears later in the alphabet than the corresponding letter in $b$. -----Input----- The first line contains two integers $n$ and $m$ ($1 \leq n \cdot m \leq 10^6$). The $i$-th of the next $n$ lines contains a string $s_i$ consisting of $m$ uppercase Latin letters — the book title. The strings are pairwise distinct. -----Output----- Output $n$ integers — the indices of the strings after they are sorted asc-desc-endingly. -----Examples----- Input 5 2 AA AB BB BA AZ Output 5 2 1 3 4 -----Note----- The following illustrates the first example. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have a grid with H rows and W columns, where all the squares are initially white. You will perform some number of painting operations on the grid. In one operation, you can do one of the following two actions: * Choose one row, then paint all the squares in that row black. * Choose one column, then paint all the squares in that column black. At least how many operations do you need in order to have N or more black squares in the grid? It is guaranteed that, under the conditions in Constraints, having N or more black squares is always possible by performing some number of operations. Constraints * 1 \leq H \leq 100 * 1 \leq W \leq 100 * 1 \leq N \leq H \times W * All values in input are integers. Input Input is given from Standard Input in the following format: H W N Output Print the minimum number of operations needed. Examples Input 3 7 10 Output 2 Input 14 12 112 Output 8 Input 2 100 200 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. Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard. Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules. -----Input----- The first line of the input contains six positive integers x_1, y_1, x_2, y_2, x_3, y_3 (1 ≤ x_1, y_1, x_2, y_2, x_3, y_3 ≤ 100), where x_{i} and y_{i} determine the length and width of the logo of the i-th company respectively. -----Output----- If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement. -----Examples----- Input 5 1 2 5 5 2 Output 5 AAAAA BBBBB BBBBB CCCCC CCCCC Input 4 4 2 6 4 2 Output 6 BBBBBB BBBBBB AAAACC AAAACC AAAACC AAAACC Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Hr0d1y has $q$ queries on a binary string $s$ of length $n$. A binary string is a string containing only characters '0' and '1'. A query is described by a pair of integers $l_i$, $r_i$ $(1 \leq l_i \lt r_i \leq n)$. For each query, he has to determine whether there exists a good subsequence in $s$ that is equal to the substring $s[l_i\ldots r_i]$. A substring $s[i\ldots j]$ of a string $s$ is the string formed by characters $s_i s_{i+1} \ldots s_j$. String $a$ is said to be a subsequence of string $b$ if $a$ can be obtained from $b$ by deleting some characters without changing the order of the remaining characters. A subsequence is said to be good if it is not contiguous and has length $\ge 2$. For example, if $s$ is "1100110", then the subsequences $s_1s_2s_4$ ("1100110") and $s_1s_5s_7$ ("1100110") are good, while $s_1s_2s_3$ ("1100110") is not good. Can you help Hr0d1y answer each query? -----Input----- The first line of the input contains a single integer $t$ ($1\leq t \leq 100$) — the number of test cases. The description of each test case is as follows. The first line contains two integers $n$ ($2 \leq n \leq 100$) and $q$ ($1\leq q \leq 100$) — the length of the string and the number of queries. The second line contains the string $s$. The $i$-th of the next $q$ lines contains two integers $l_i$ and $r_i$ ($1 \leq l_i \lt r_i \leq n$). -----Output----- For each test case, output $q$ lines. The $i$-th line of the output of each test case should contain "YES" if there exists a good subsequence equal to the substring $s[l_i...r_i]$, and "NO" otherwise. You may print each letter in any case (upper or lower). -----Examples----- Input 2 6 3 001000 2 4 1 3 3 5 4 2 1111 1 4 2 3 Output YES NO YES NO YES -----Note----- In the first test case, $s[2\ldots 4] = $ "010". In this case $s_1s_3s_5$ ("001000") and $s_2s_3s_6$ ("001000") are good suitable subsequences, while $s_2s_3s_4$ ("001000") is not good. $s[1\ldots 3] = $ "001". No suitable good subsequence exists. $s[3\ldots 5] = $ "100". Here $s_3s_5s_6$ ("001000") is a suitable good subsequence. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 write a research paper, you should definitely follow the structured format. This format, in many cases, is strictly defined, and students who try to write their papers have a hard time with it. One of such formats is related to citations. If you refer several pages of a material, you should enumerate their page numbers in ascending order. However, enumerating many page numbers waste space, so you should use the following abbreviated notation: When you refer all pages between page a and page b (a < b), you must use the notation "a-b". For example, when you refer pages 1, 2, 3, 4, you must write "1-4" not "1 2 3 4". You must not write, for example, "1-2 3-4", "1-3 4", "1-3 2-4" and so on. When you refer one page and do not refer the previous and the next page of that page, you can write just the number of that page, but you must follow the notation when you refer successive pages (more than or equal to 2). Typically, commas are used to separate page numbers, in this problem we use space to separate the page numbers. You, a kind senior, decided to write a program which generates the abbreviated notation for your junior who struggle with the citation. Constraints * 1 ≤ n ≤ 50 Input Input consists of several datasets. The first line of the dataset indicates the number of pages n. Next line consists of n integers. These integers are arranged in ascending order and they are differ from each other. Input ends when n = 0. Output For each dataset, output the abbreviated notation in a line. Your program should not print extra space. Especially, be careful about the space at the end of line. Example Input 5 1 2 3 5 6 3 7 8 9 0 Output 1-3 5-6 7-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. Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns. The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is .. From a road square, you can move to a horizontally or vertically adjacent road square. You cannot move out of the maze, move to a wall square, or move diagonally. Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki. Aoki will then travel from the starting square to the goal square, in the minimum number of moves required. In this situation, find the maximum possible number of moves Aoki has to make. -----Constraints----- - 1 \leq H,W \leq 20 - S_{ij} is . or #. - S contains at least two occurrences of .. - Any road square can be reached from any road square in zero or more moves. -----Input----- Input is given from Standard Input in the following format: H W S_{11}...S_{1W} : S_{H1}...S_{HW} -----Output----- Print the maximum possible number of moves Aoki has to make. -----Sample Input----- 3 3 ... ... ... -----Sample Output----- 4 If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. For given an integer $n$, print all permutations of $\\{1, 2, ..., n\\}$ in lexicographic order. Constraints * $1 \leq n \leq 9$ Input An integer $n$ is given in a line. Output Print each permutation in a line in order. Separate adjacency elements by a space character. Examples Input 2 Output 1 2 2 1 Input 3 Output 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 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. Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya! Sonya is an owl and she sleeps during the day and stay awake from minute l_1 to minute r_1 inclusive. Also, during the minute k she prinks and is unavailable for Filya. Filya works a lot and he plans to visit Sonya from minute l_2 to minute r_2 inclusive. Calculate the number of minutes they will be able to spend together. -----Input----- The only line of the input contains integers l_1, r_1, l_2, r_2 and k (1 ≤ l_1, r_1, l_2, r_2, k ≤ 10^18, l_1 ≤ r_1, l_2 ≤ r_2), providing the segments of time for Sonya and Filya and the moment of time when Sonya prinks. -----Output----- Print one integer — the number of minutes Sonya and Filya will be able to spend together. -----Examples----- Input 1 10 9 20 1 Output 2 Input 1 100 50 200 75 Output 50 -----Note----- In the first sample, they will be together during minutes 9 and 10. In the second sample, they will be together from minute 50 to minute 74 and from minute 76 to minute 100. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N. Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds: * Choose two distinct integers x and y between 1 and N (inclusive), and swap the values of A_x and A_y. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i,B_i \leq 10^9 Input Input is given from Standard Input in the following format: N A_1 A_2 ... A_N B_1 B_2 ... B_N Output If the objective is achievable, print `Yes`; if it is not, print `No`. Examples Input 3 1 3 2 1 2 3 Output Yes Input 3 1 2 3 2 2 2 Output No Input 6 3 1 2 6 3 4 2 2 8 3 4 3 Output Yes Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A special type of prime is generated by the formula `p = 2^m * 3^n + 1` where `m` and `n` can be any non-negative integer. The first `5` of these primes are `2, 3, 5, 7, 13`, and are generated as follows: ```Haskell 2 = 2^0 * 3^0 + 1 3 = 2^1 * 3^0 + 1 5 = 2^2 * 3^0 + 1 7 = 2^1 * 3^1 + 1 13 = 2^2 * 3^1 + 1 ..and so on ``` You will be given a range and your task is to return the number of primes that have this property. For example, `solve(0,15) = 5`, because there are only `5` such primes `>= 0 and < 15`; they are `2,3,5,7,13`. The upper limit of the tests will not exceed `1,500,000`. More examples in the test cases. Good luck! If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array. The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements. Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself. Input The first line contains a single integer n (2 ≤ n ≤ 105) — the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, — array a. Note that the elements of the array are not necessarily distinct numbers. Output In a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise. Examples Input 2 1 2 Output YES Input 3 3 2 1 Output YES Input 4 4 3 2 1 Output NO Note In the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES". In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES". In the third sample we can't sort the array in more than one swap operation, so the answer is "NO". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Monocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams. Monocarp has $n$ problems that none of his students have seen yet. The $i$-th problem has a topic $a_i$ (an integer from $1$ to $n$) and a difficulty $b_i$ (an integer from $1$ to $n$). All problems are different, that is, there are no two tasks that have the same topic and difficulty at the same time. Monocarp decided to select exactly $3$ problems from $n$ problems for the problemset. The problems should satisfy at least one of two conditions (possibly, both): the topics of all three selected problems are different; the difficulties of all three selected problems are different. Your task is to determine the number of ways to select three problems for the problemset. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 50000$) — the number of testcases. The first line of each testcase contains an integer $n$ ($3 \le n \le 2 \cdot 10^5$) — the number of problems that Monocarp have. In the $i$-th of the following $n$ lines, there are two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le n$) — the topic and the difficulty of the $i$-th problem. It is guaranteed that there are no two problems that have the same topic and difficulty at the same time. The sum of $n$ over all testcases doesn't exceed $2 \cdot 10^5$. -----Output----- Print the number of ways to select three training problems that meet either of the requirements described in the statement. -----Examples----- Input 2 4 2 4 3 4 2 1 1 3 5 1 5 2 4 3 3 4 2 5 1 Output 3 10 -----Note----- In the first example, you can take the following sets of three problems: problems $1$, $2$, $4$; problems $1$, $3$, $4$; problems $2$, $3$, $4$. Thus, the number of ways is equal to three. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Shortest Common Non-Subsequence A subsequence of a sequence $P$ is a sequence that can be derived from the original sequence $P$ by picking up some or no elements of $P$ preserving the order. For example, "ICPC" is a subsequence of "MICROPROCESSOR". A common subsequence of two sequences is a subsequence of both sequences. The famous longest common subsequence problem is finding the longest of common subsequences of two given sequences. In this problem, conversely, we consider the shortest common non-subsequence problem: Given two sequences consisting of 0 and 1, your task is to find the shortest sequence also consisting of 0 and 1 that is a subsequence of neither of the two sequences. Input The input consists of a single test case with two lines. Both lines are sequences consisting only of 0 and 1. Their lengths are between 1 and 4000, inclusive. Output Output in one line the shortest common non-subsequence of two given sequences. If there are two or more such sequences, you should output the lexicographically smallest one. Here, a sequence $P$ is lexicographically smaller than another sequence $Q$ of the same length if there exists $k$ such that $P_1 = Q_1, ... , P_{k-1} = Q_{k-1}$, and $P_k < Q_k$, where $S_i$ is the $i$-th character of a sequence $S$. Sample Input 1 0101 1100001 Sample Output 1 0010 Sample Input 2 101010101 010101010 Sample Output 2 000000 Sample Input 3 11111111 00000000 Sample Output 3 01 Example Input 0101 1100001 Output 0010 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins. When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins. If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won. -----Input----- The first line contains number n — the number of techniques that the wrestlers have used (1 ≤ n ≤ 2·10^5). The following n lines contain integer numbers a_{i} (|a_{i}| ≤ 10^9, a_{i} ≠ 0). If a_{i} is positive, that means that the first wrestler performed the technique that was awarded with a_{i} points. And if a_{i} is negative, that means that the second wrestler performed the technique that was awarded with ( - a_{i}) points. The techniques are given in chronological order. -----Output----- If the first wrestler wins, print string "first", otherwise print "second" -----Examples----- Input 5 1 2 -3 -4 3 Output second Input 3 -1 -2 3 Output first Input 2 4 -4 Output second -----Note----- Sequence x = x_1x_2... x_{|}x| is lexicographically larger than sequence y = y_1y_2... y_{|}y|, if either |x| > |y| and x_1 = y_1, x_2 = y_2, ... , x_{|}y| = y_{|}y|, or there is such number r (r < |x|, r < |y|), that x_1 = y_1, x_2 = y_2, ... , x_{r} = y_{r} and x_{r} + 1 > y_{r} + 1. We use notation |a| to denote length of sequence a. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a system of equations: <image> You should count, how many there are pairs of integers (a, b) (0 ≤ a, b) which satisfy the system. Input A single line contains two integers n, m (1 ≤ n, m ≤ 1000) — the parameters of the system. The numbers on the line are separated by a space. Output On a single line print the answer to the problem. Examples Input 9 3 Output 1 Input 14 28 Output 1 Input 4 20 Output 0 Note In the first sample the suitable pair is integers (3, 0). In the second sample the suitable pair is integers (3, 5). In the third sample there is no suitable pair. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are a given a list of integers $a_1, a_2, \ldots, a_n$ and $s$ of its segments $[l_j; r_j]$ (where $1 \le l_j \le r_j \le n$). You need to select exactly $m$ segments in such a way that the $k$-th order statistic of the multiset of $a_i$, where $i$ is contained in at least one segment, is the smallest possible. If it's impossible to select a set of $m$ segments in such a way that the multiset contains at least $k$ elements, print -1. The $k$-th order statistic of a multiset is the value of the $k$-th element after sorting the multiset in non-descending order. -----Input----- The first line contains four integers $n$, $s$, $m$ and $k$ ($1 \le m \le s \le 1500$, $1 \le k \le n \le 1500$) — the size of the list, the number of segments, the number of segments to choose and the statistic number. The second line contains $n$ integers $a_i$ ($1 \le a_i \le 10^9$) — the values of the numbers in the list. Each of the next $s$ lines contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le n$) — the endpoints of the segments. It is possible that some segments coincide. -----Output----- Print exactly one integer — the smallest possible $k$-th order statistic, or -1 if it's impossible to choose segments in a way that the multiset contains at least $k$ elements. -----Examples----- Input 4 3 2 2 3 1 3 2 1 2 2 3 4 4 Output 2 Input 5 2 1 1 1 2 3 4 5 2 4 1 5 Output 1 Input 5 3 3 5 5 5 2 1 1 1 2 2 3 3 4 Output -1 -----Note----- In the first example, one possible solution is to choose the first and the third segment. Together they will cover three elements of the list (all, except for the third one). This way the $2$-nd order statistic for the covered elements is $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. Seiji Hayashi had been a professor of the Nisshinkan Samurai School in the domain of Aizu for a long time in the 18th century. In order to reward him for his meritorious career in education, Katanobu Matsudaira, the lord of the domain of Aizu, had decided to grant him a rectangular estate within a large field in the Aizu Basin. Although the size (width and height) of the estate was strictly specified by the lord, he was allowed to choose any location for the estate in the field. Inside the field which had also a rectangular shape, many Japanese persimmon trees, whose fruit was one of the famous products of the Aizu region known as 'Mishirazu Persimmon', were planted. Since persimmon was Hayashi's favorite fruit, he wanted to have as many persimmon trees as possible in the estate given by the lord. For example, in Figure 1, the entire field is a rectangular grid whose width and height are 10 and 8 respectively. Each asterisk (*) represents a place of a persimmon tree. If the specified width and height of the estate are 4 and 3 respectively, the area surrounded by the solid line contains the most persimmon trees. Similarly, if the estate's width is 6 and its height is 4, the area surrounded by the dashed line has the most, and if the estate's width and height are 3 and 4 respectively, the area surrounded by the dotted line contains the most persimmon trees. Note that the width and height cannot be swapped; the sizes 4 by 3 and 3 by 4 are different, as shown in Figure 1. <image> --- Figure 1: Examples of Rectangular Estates Your task is to find the estate of a given size (width and height) that contains the largest number of persimmon trees. Input The input consists of multiple data sets. Each data set is given in the following format. > N > W` `H > x1` `y1 > x2` `y2 > ... > xN` `yN > S` `T > N is the number of persimmon trees, which is a positive integer less than 500. W and H are the width and the height of the entire field respectively. You can assume that both W and H are positive integers whose values are less than 100. For each i (1 <= i <= N), xi and yi are coordinates of the i-th persimmon tree in the grid. Note that the origin of each coordinate is 1. You can assume that 1 <= xi <= W and 1 <= yi <= H, and no two trees have the same positions. But you should not assume that the persimmon trees are sorted in some order according to their positions. Lastly, S and T are positive integers of the width and height respectively of the estate given by the lord. You can also assume that 1 <= S <= W and 1 <= T <= H. The end of the input is indicated by a line that solely contains a zero. Output For each data set, you are requested to print one line containing the maximum possible number of persimmon trees that can be included in an estate of the given size. Example Input 16 10 8 2 2 2 5 2 7 3 3 3 8 4 2 4 5 4 8 6 4 6 7 7 5 7 8 8 1 8 4 9 6 10 3 4 3 8 6 4 1 2 2 1 2 4 3 4 4 2 5 3 6 1 6 2 3 2 0 Output 4 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. problem There are many $ N $ colored balls of different weights in the queue. The queue is in ascending order from the beginning: $ 1,2,3, \ dots, N-1, N, 1,2,3, \ dots, N-1, N, 1,2,3, \ dots $ The balls are lined up, followed by the balls of color $ N $, followed by the balls of color $ 1 $. Balls of the same color weigh the same, and balls of color $ i $ weigh $ A_i $. From this state, take out $ M $ of balls from the beginning of the queue and repeat the process of grouping them. Then stop forming groups when the total number of balls of each color removed from the cue is equal. Please note that the cue contains a sufficient number of balls and the cue will not be empty by the time you stop forming groups. For example, when $ N = 8, M = 2 $, there are 4 groups of {color 1, color 2}, {color 3, color 4}, {color 5, color 6}, {color 7, color 8}. (At this time, there is one ball of each color). When $ N = 4, M = 3 $, {color 1, color 2, color 3}, {color 4, color 1, color 2}, {color 3, color 4, color 1}, {color 2, color There will be a $ 4 $ group of 3, colors 4} (there are 3 balls of each color each). At this time, in each group, the difference between the maximum value and the minimum value of the weight of the balls included is called the weight range of that group. Output the sum of the weight ranges for each group. output Print the answer in one line. Also, output a line break at the end. Example Input 8 2 23 61 57 13 91 41 79 41 Output 170 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n × n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≤ n ≤ 1000, 1 ≤ m ≤ min(n·n, 105)) — the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem — the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The only difference between easy and hard versions is constraints. Nauuo is a girl who loves random picture websites. One day she made a random picture website by herself which includes $n$ pictures. When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The $i$-th picture has a non-negative weight $w_i$, and the probability of the $i$-th picture being displayed is $\frac{w_i}{\sum_{j=1}^nw_j}$. That is to say, the probability of a picture to be displayed is proportional to its weight. However, Nauuo discovered that some pictures she does not like were displayed too often. To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add $1$ to its weight; otherwise, she would subtract $1$ from its weight. Nauuo will visit the website $m$ times. She wants to know the expected weight of each picture after all the $m$ visits modulo $998244353$. Can you help her? The expected weight of the $i$-th picture can be denoted by $\frac {q_i} {p_i}$ where $\gcd(p_i,q_i)=1$, you need to print an integer $r_i$ satisfying $0\le r_i<998244353$ and $r_i\cdot p_i\equiv q_i\pmod{998244353}$. It can be proved that such $r_i$ exists and is unique. -----Input----- The first line contains two integers $n$ and $m$ ($1\le n\le 50$, $1\le m\le 50$) — the number of pictures and the number of visits to the website. The second line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($a_i$ is either $0$ or $1$) — if $a_i=0$ , Nauuo does not like the $i$-th picture; otherwise Nauuo likes the $i$-th picture. It is guaranteed that there is at least one picture which Nauuo likes. The third line contains $n$ integers $w_1,w_2,\ldots,w_n$ ($1\le w_i\le50$) — the initial weights of the pictures. -----Output----- The output contains $n$ integers $r_1,r_2,\ldots,r_n$ — the expected weights modulo $998244353$. -----Examples----- Input 2 1 0 1 2 1 Output 332748119 332748119 Input 1 2 1 1 Output 3 Input 3 3 0 1 1 4 3 5 Output 160955686 185138929 974061117 -----Note----- In the first example, if the only visit shows the first picture with a probability of $\frac 2 3$, the final weights are $(1,1)$; if the only visit shows the second picture with a probability of $\frac1 3$, the final weights are $(2,2)$. So, both expected weights are $\frac2 3\cdot 1+\frac 1 3\cdot 2=\frac4 3$ . Because $332748119\cdot 3\equiv 4\pmod{998244353}$, you need to print $332748119$ instead of $\frac4 3$ or $1.3333333333$. In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, $w_1$ will be increased by $1$. So, the expected weight is $1+2=3$. Nauuo is very naughty so she didn't give you any hint of the third example. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled. Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described. Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). [Image] The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible. Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there. -----Input----- The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 100$; $1 \leq m \leq 200$) — the number of stations and the number of candies, respectively. The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$; $a_i \neq b_i$) — the station that initially contains candy $i$ and the destination station of the candy, respectively. -----Output----- In the first and only line, print $n$ space-separated integers, the $i$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $i$. -----Examples----- Input 5 7 2 4 5 1 2 3 3 4 4 1 5 3 3 5 Output 10 9 10 10 9 Input 2 3 1 2 1 2 1 2 Output 5 6 -----Note----- Consider the second sample. If the train started at station $1$, the optimal strategy is as follows. Load the first candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the first candy. Proceed to station $1$. This step takes $1$ second. Load the second candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the second candy. Proceed to station $1$. This step takes $1$ second. Load the third candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the third candy. Hence, the train needs $5$ seconds to complete the tasks. If the train were to start at station $2$, however, it would need to move to station $1$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $5+1 = 6$ seconds. Read the inputs from stdin solve the problem and write the answer to stdout (do 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. Each character of S is uppercase or lowercase English letter. Determine if S satisfies all of the following conditions: - The initial character of S is an uppercase A. - There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive). - All letters except the A and C mentioned above are lowercase. -----Constraints----- - 4 ≤ |S| ≤ 10 (|S| is the length of the string S.) - Each character of S is uppercase or lowercase English letter. -----Input----- Input is given from Standard Input in the following format: S -----Output----- If S satisfies all of the conditions in the problem statement, print AC; otherwise, print WA. -----Sample Input----- AtCoder -----Sample Output----- AC The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Implement a function which takes a string, and returns its hash value. Algorithm steps: * `a` := sum of the ascii values of the input characters * `b` := sum of every difference between the consecutive characters of the input (second char minus first char, third minus second, ...) * `c` := (`a` OR `b`) AND ((NOT `a`) shift left by 2 bits) * `d` := `c` XOR (32 * (`total_number_of_spaces` + 1)) * return `d` **Note**: OR, AND, NOT, XOR are bitwise operations. ___ ### Examples ``` input = "a" a = 97 b = 0 result = 64 input = "ca" a = 196 b = -2 result = -820 ``` ___ Give an example why this hashing algorithm is bad? Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names. This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method. -----Input----- The first line contains a non-empty string, that contains only lowercase English letters — the user name. This string contains at most 100 letters. -----Output----- If it is a female by our hero's method, print "CHAT WITH HER!" (without the quotes), otherwise, print "IGNORE HIM!" (without the quotes). -----Examples----- Input wjmzbmr Output CHAT WITH HER! Input xiaodao Output IGNORE HIM! Input sevenkplus Output CHAT WITH HER! -----Note----- For the first example. There are 6 distinct characters in "wjmzbmr". These characters are: "w", "j", "m", "z", "b", "r". So wjmzbmr is a female and you should print "CHAT WITH HER!". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are $n$ children numbered from $1$ to $n$ in a kindergarten. Kindergarten teacher gave $a_i$ ($1 \leq a_i \leq n$) candies to the $i$-th child. Children were seated in a row in order from $1$ to $n$ from left to right and started eating candies. While the $i$-th child was eating candies, he calculated two numbers $l_i$ and $r_i$ — the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively. Formally, $l_i$ is the number of indices $j$ ($1 \leq j < i$), such that $a_i < a_j$ and $r_i$ is the number of indices $j$ ($i < j \leq n$), such that $a_i < a_j$. Each child told to the kindergarten teacher the numbers $l_i$ and $r_i$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $l$ and $r$ determine whether she could have given the candies to the children such that all children correctly calculated their values $l_i$ and $r_i$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it. -----Input----- On the first line there is a single integer $n$ ($1 \leq n \leq 1000$) — the number of children in the kindergarten. On the next line there are $n$ integers $l_1, l_2, \ldots, l_n$ ($0 \leq l_i \leq n$), separated by spaces. On the next line, there are $n$ integer numbers $r_1, r_2, \ldots, r_n$ ($0 \leq r_i \leq n$), separated by spaces. -----Output----- If there is no way to distribute the candies to the children so that all of them calculated their numbers correctly, print «NO» (without quotes). Otherwise, print «YES» (without quotes) on the first line. On the next line, print $n$ integers $a_1, a_2, \ldots, a_n$, separated by spaces — the numbers of candies the children $1, 2, \ldots, n$ received, respectively. Note that some of these numbers can be equal, but all numbers should satisfy the condition $1 \leq a_i \leq n$. The number of children seating to the left of the $i$-th child that got more candies than he should be equal to $l_i$ and the number of children seating to the right of the $i$-th child that got more candies than he should be equal to $r_i$. If there is more than one solution, find any of them. -----Examples----- Input 5 0 0 1 1 2 2 0 1 0 0 Output YES 1 3 1 2 1 Input 4 0 0 2 0 1 1 1 1 Output NO Input 3 0 0 0 0 0 0 Output YES 1 1 1 -----Note----- In the first example, if the teacher distributed $1$, $3$, $1$, $2$, $1$ candies to $1$-st, $2$-nd, $3$-rd, $4$-th, $5$-th child, respectively, then all the values calculated by the children are correct. For example, the $5$-th child was given $1$ candy, to the left of him $2$ children were given $1$ candy, $1$ child was given $2$ candies and $1$ child — $3$ candies, so there are $2$ children to the left of him that were given more candies than him. In the second example it is impossible to distribute the candies, because the $4$-th child made a mistake in calculating the value of $r_4$, because there are no children to the right of him, so $r_4$ should be equal to $0$. In the last example all children may have got the same number of candies, that's why all the numbers are $0$. Note that each child should receive at least one candy. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Simple interest on a loan is calculated by simply taking the initial amount (the principal, p) and multiplying it by a rate of interest (r) and the number of time periods (n). Compound interest is calculated by adding the interest after each time period to the amount owed, then calculating the next interest payment based on the principal PLUS the interest from all previous periods. Given a principal *p*, interest rate *r*, and a number of periods *n*, return an array [total owed under simple interest, total owed under compound interest]. ``` EXAMPLES: interest(100,0.1,1) = [110,110] interest(100,0.1,2) = [120,121] interest(100,0.1,10) = [200,259] ``` Round all answers to the nearest integer. Principal will always be an integer between 0 and 9999; interest rate will be a decimal between 0 and 1; number of time periods will be an integer between 0 and 49. --- More on [Simple interest, compound interest and continuous interest](https://betterexplained.com/articles/a-visual-guide-to-simple-compound-and-continuous-interest-rates/) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. *Based on this Numberphile video: https://www.youtube.com/watch?v=Wim9WJeDTHQ* --- Multiply all the digits of a nonnegative integer `n` by each other, repeating with the product until a single digit is obtained. The number of steps required is known as the **multiplicative persistence**. Create a function that calculates the individual results of each step, not including the original number, but including the single digit, and outputs the result as a list/array. If the input is a single digit, return an empty list/array. ## Examples ``` per(1) = [] per(10) = [0] // 1*0 = 0 per(69) = [54, 20, 0] // 6*9 = 54 --> 5*4 = 20 --> 2*0 = 0 per(277777788888899) = [4996238671872, 438939648, 4478976, 338688, 27648, 2688, 768, 336, 54, 20, 0] // 2*7*7*7*7*7*7*8*8*8*8*8*8*9*9 = 4996238671872 --> 4*9*9*6*2*3*8*6*7*1*8*7*2 = 4478976 --> ... ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Chefs from all over the globe gather each year for an international convention. Each chef represents some country. Please, note that more than one chef can represent a country. Each of them presents their best dish to the audience. The audience then sends emails to a secret and secure mail server, with the subject being the name of the chef whom they wish to elect as the "Chef of the Year". You will be given the list of the subjects of all the emails. Find the country whose chefs got the most number of votes, and also the chef who got elected as the "Chef of the Year" (the chef who got the most number of votes). Note 1 If several countries got the maximal number of votes, consider the country with the lexicographically smaller name among them to be a winner. Similarly if several chefs got the maximal number of votes, consider the chef with the lexicographically smaller name among them to be a winner. Note 2 The string A = a1a2...an is called lexicographically smaller then the string B = b1b2...bm in the following two cases: - there exists index i ≤ min{n, m} such that aj = bj for 1 ≤ j < i and ai < bi; - A is a proper prefix of B, that is, n < m and aj = bj for 1 ≤ j ≤ n. The characters in strings are compared by their ASCII codes. Refer to function strcmp in C or to standard comparator < for string data structure in C++ for details. -----Input----- The first line of the input contains two space-separated integers N and M denoting the number of chefs and the number of emails respectively. Each of the following N lines contains two space-separated strings, denoting the name of the chef and his country respectively. Each of the following M lines contains one string denoting the subject of the email. -----Output----- Output should consist of two lines. The first line should contain the name of the country whose chefs got the most number of votes. The second line should contain the name of the chef who is elected as the "Chef of the Year". -----Constraints----- - 1 ≤ N ≤ 10000 (104) - 1 ≤ M ≤ 100000 (105) - Each string in the input contains only letters of English alphabets (uppercase or lowercase) - Each string in the input has length not exceeding 10 - All chef names will be distinct - Subject of each email will coincide with the name of one of the chefs -----Example 1----- Input: 1 3 Leibniz Germany Leibniz Leibniz Leibniz Output: Germany Leibniz -----Example 2----- Input: 4 5 Ramanujan India Torricelli Italy Gauss Germany Lagrange Italy Ramanujan Torricelli Torricelli Ramanujan Lagrange Output: Italy Ramanujan -----Example 3----- Input: 2 2 Newton England Euclid Greece Newton Euclid Output: England Euclid -----Explanation----- Example 1. Here we have only one chef Leibniz and he is from Germany. Clearly, all votes are for him. So Germany is the country-winner and Leibniz is the "Chef of the Year". Example 2. Here we have chefs Torricelli and Lagrange from Italy, chef Ramanujan from India and chef Gauss from Germany. Torricelli got 2 votes, while Lagrange got one vote. Hence the Italy got 3 votes in all. Ramanujan got also 2 votes. And so India got 2 votes in all. Finally Gauss got no votes leaving Germany without votes. So the country-winner is Italy without any ties. But we have two chefs with 2 votes: Torricelli and Ramanujan. But since the string "Ramanujan" is lexicographically smaller than "Torricelli", then Ramanujan is the "Chef of the Year". Example 3. Here we have two countries with 1 vote: England and Greece. Since the string "England" is lexicographically smaller than "Greece", then England is the country-winner. Next, we have two chefs with 1 vote: Newton and Euclid. Since the string "Euclid" is lexicographically smaller than "Newton", then Euclid is the "Chef of the Year". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Beaches are filled with sand, water, fish, and sun. Given a string, calculate how many times the words `"Sand"`, `"Water"`, `"Fish"`, and `"Sun"` appear without overlapping (regardless of the case). ## Examples ```python sum_of_a_beach("WAtErSlIde") ==> 1 sum_of_a_beach("GolDeNSanDyWateRyBeaChSuNN") ==> 3 sum_of_a_beach("gOfIshsunesunFiSh") ==> 4 sum_of_a_beach("cItYTowNcARShoW") ==> 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. Maksim walks on a Cartesian plane. Initially, he stands at the point $(0, 0)$ and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point $(0, 0)$, he can go to any of the following points in one move: $(1, 0)$; $(0, 1)$; $(-1, 0)$; $(0, -1)$. There are also $n$ distinct key points at this plane. The $i$-th point is $p_i = (x_i, y_i)$. It is guaranteed that $0 \le x_i$ and $0 \le y_i$ and there is no key point $(0, 0)$. Let the first level points be such points that $max(x_i, y_i) = 1$, the second level points be such points that $max(x_i, y_i) = 2$ and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level $i + 1$ if he does not visit all the points of level $i$. He starts visiting the points from the minimum level of point from the given set. The distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$ where $|v|$ is the absolute value of $v$. Maksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance. If you are Python programmer, consider using PyPy instead of Python when you submit your code. -----Input----- The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of key points. Each of the next $n$ lines contains two integers $x_i$, $y_i$ ($0 \le x_i, y_i \le 10^9$) — $x$-coordinate of the key point $p_i$ and $y$-coordinate of the key point $p_i$. It is guaranteed that all the points are distinct and the point $(0, 0)$ is not in this set. -----Output----- Print one integer — the minimum possible total distance Maksim has to travel if he needs to visit all key points in a way described above. -----Examples----- Input 8 2 2 1 4 2 3 3 1 3 4 1 1 4 3 1 2 Output 15 Input 5 2 1 1 0 2 0 3 2 0 3 Output 9 -----Note----- The picture corresponding to the first example: [Image] There is one of the possible answers of length $15$. The picture corresponding to the second example: [Image] There is one of the possible answers of length $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. Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid. Each test case consists of an integer $n$ and two arrays $a$ and $b$, of size $n$. If after some (possibly zero) operations described below, array $a$ can be transformed into array $b$, the input is said to be valid. Otherwise, it is invalid. An operation on array $a$ is: select an integer $k$ $(1 \le k \le \lfloor\frac{n}{2}\rfloor)$ swap the prefix of length $k$ with the suffix of length $k$ For example, if array $a$ initially is $\{1, 2, 3, 4, 5, 6\}$, after performing an operation with $k = 2$, it is transformed into $\{5, 6, 3, 4, 1, 2\}$. Given the set of test cases, help them determine if each one is valid or invalid. -----Input----- The first line contains one integer $t$ $(1 \le t \le 500)$ — the number of test cases. The description of each test case is as follows. The first line of each test case contains a single integer $n$ $(1 \le n \le 500)$ — the size of the arrays. The second line of each test case contains $n$ integers $a_1$, $a_2$, ..., $a_n$ $(1 \le a_i \le 10^9)$ — elements of array $a$. The third line of each test case contains $n$ integers $b_1$, $b_2$, ..., $b_n$ $(1 \le b_i \le 10^9)$ — elements of array $b$. -----Output----- For each test case, print "Yes" if the given input is valid. Otherwise print "No". You may print the answer in any case. -----Example----- Input 5 2 1 2 2 1 3 1 2 3 1 2 3 3 1 2 4 1 3 4 4 1 2 3 2 3 1 2 2 3 1 2 3 1 3 2 Output yes yes No yes No -----Note----- For the first test case, we can swap prefix $a[1:1]$ with suffix $a[2:2]$ to get $a=[2, 1]$. For the second test case, $a$ is already equal to $b$. For the third test case, it is impossible since we cannot obtain $3$ in $a$. For the fourth test case, we can first swap prefix $a[1:1]$ with suffix $a[4:4]$ to obtain $a=[2, 2, 3, 1]$. Now we can swap prefix $a[1:2]$ with suffix $a[3:4]$ to obtain $a=[3, 1, 2, 2]$. For the fifth test case, it is impossible to convert $a$ to $b$. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 tree consisting of n nodes. You generate an array from the tree by marking nodes one by one. Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array a is the list of the nodes' labels in order of the time each node was marked. Find the expected number of inversions in the array that is generated by the tree and the aforementioned process. The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4). Input The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree. The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y. It's guaranteed that the given edges form a tree. Output Output the expected number of inversions in the generated array modulo 10^9+7. Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}. Examples Input 3 1 2 1 3 Output 166666669 Input 6 2 1 2 3 6 1 1 4 2 5 Output 500000009 Input 5 1 2 1 3 1 4 2 5 Output 500000007 Note This is the tree from the first sample: <image> For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6. 166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669. This is the tree from the second sample: <image> This is the tree from the third sample: <image> Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke is having a barbeque party. At the party, he will make N servings of Skewer Meal. Example of a serving of Skewer Meal He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i. Also, he has an infinite supply of ingredients. To make a serving of Skewer Meal, he picks 2 skewers and threads ingredients onto those skewers. Let the length of the shorter skewer be x, then the serving can hold the maximum of x ingredients. What is the maximum total number of ingredients that his N servings of Skewer Meal can hold, if he uses the skewers optimally? -----Constraints----- - 1≦N≦100 - 1≦L_i≦100 - For each i, L_i is an integer. -----Input----- The input is given from Standard Input in the following format: N L_1 L_2 ... L_{2N} -----Output----- Print the maximum total number of ingredients that Snuke's N servings of Skewer Meal can hold. -----Sample Input----- 2 1 3 1 2 -----Sample Output----- 3 If he makes a serving using the first and third skewers, and another using the second and fourth skewers, each serving will hold 1 and 2 ingredients, for the total of 3. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has k_{i} people. The j-th person standing in the queue to the i-th cashier has m_{i}, j items in the basket. Vasya knows that: the cashier needs 5 seconds to scan one item; after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers. -----Input----- The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k_1, k_2, ..., k_{n} (1 ≤ k_{i} ≤ 100), where k_{i} is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains k_{i} space-separated integers: m_{i}, 1, m_{i}, 2, ..., m_{i}, k_{i} (1 ≤ m_{i}, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has. -----Output----- Print a single integer — the minimum number of seconds Vasya needs to get to the cashier. -----Examples----- Input 1 1 1 Output 20 Input 4 1 4 3 2 100 1 2 2 3 1 9 1 7 8 Output 100 -----Note----- In the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a ≤ x ≤ b and x is divisible by k. -----Input----- The only line contains three space-separated integers k, a and b (1 ≤ k ≤ 10^18; - 10^18 ≤ a ≤ b ≤ 10^18). -----Output----- Print the required number. -----Examples----- Input 1 1 10 Output 10 Input 2 -4 4 Output 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Fair Nut likes kvass very much. On his birthday parents presented him $n$ kegs of kvass. There are $v_i$ liters of kvass in the $i$-th keg. Each keg has a lever. You can pour your glass by exactly $1$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $s$ liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible. Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by $s$ liters of kvass. -----Input----- The first line contains two integers $n$ and $s$ ($1 \le n \le 10^3$, $1 \le s \le 10^{12}$) — the number of kegs and glass volume. The second line contains $n$ integers $v_1, v_2, \ldots, v_n$ ($1 \le v_i \le 10^9$) — the volume of $i$-th keg. -----Output----- If the Fair Nut cannot pour his glass by $s$ liters of kvass, print $-1$. Otherwise, print a single integer — how much kvass in the least keg can be. -----Examples----- Input 3 3 4 3 5 Output 3 Input 3 4 5 3 4 Output 2 Input 3 7 1 2 3 Output -1 -----Note----- In the first example, the answer is $3$, the Fair Nut can take $1$ liter from the first keg and $2$ liters from the third keg. There are $3$ liters of kvass in each keg. In the second example, the answer is $2$, the Fair Nut can take $3$ liters from the first keg and $1$ liter from the second keg. In the third example, the Fair Nut can't pour his cup by $7$ liters, so the answer is $-1$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out a_{i} people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader. For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and a_{i} = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader. You have to write a program which prints the number of the child to be eliminated on every step. -----Input----- The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1). The next line contains k integer numbers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ 10^9). -----Output----- Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step. -----Examples----- Input 7 5 10 4 11 4 1 Output 4 2 5 6 1 Input 3 2 2 5 Output 3 2 -----Note----- Let's consider first example: In the first step child 4 is eliminated, child 5 becomes the leader. In the second step child 2 is eliminated, child 3 becomes the leader. In the third step child 5 is eliminated, child 6 becomes the leader. In the fourth step child 6 is eliminated, child 7 becomes the leader. In the final step child 1 is eliminated, child 3 becomes the leader. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty. Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram. Input The first line contains a single number n (2 ≤ n ≤ 1000) — the number of the tram's stops. Then n lines follow, each contains two integers ai and bi (0 ≤ ai, bi ≤ 1000) — the number of passengers that exits the tram at the i-th stop, and the number of passengers that enter the tram at the i-th stop. The stops are given from the first to the last stop in the order of tram's movement. * The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, <image>. This particularly means that a1 = 0. * At the last stop, all the passengers exit the tram and it becomes empty. More formally, <image>. * No passenger will enter the train at the last stop. That is, bn = 0. Output Print a single integer denoting the minimum possible capacity of the tram (0 is allowed). Examples Input 4 0 3 2 5 4 2 4 0 Output 6 Note For the first example, a capacity of 6 is sufficient: * At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3. * At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now. * At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now. * Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints. Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Fair Nut is going to travel to the Tree Country, in which there are $n$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $u$ and go by a simple path to city $v$. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex. A filling station is located in every city. Because of strange law, Nut can buy only $w_i$ liters of gasoline in the $i$-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last. He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it. -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 3 \cdot 10^5$) — the number of cities. The second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($0 \leq w_{i} \leq 10^9$) — the maximum amounts of liters of gasoline that Nut can buy in cities. Each of the next $n - 1$ lines describes road and contains three integers $u$, $v$, $c$ ($1 \leq u, v \leq n$, $1 \leq c \leq 10^9$, $u \ne v$), where $u$ and $v$ — cities that are connected by this road and $c$ — its length. It is guaranteed that graph of road connectivity is a tree. -----Output----- Print one number — the maximum amount of gasoline that he can have at the end of the path. -----Examples----- Input 3 1 3 3 1 2 2 1 3 2 Output 3 Input 5 6 3 2 5 0 1 2 10 2 3 3 2 4 1 1 5 1 Output 7 -----Note----- The optimal way in the first example is $2 \to 1 \to 3$. [Image] The optimal way in the second example is $2 \to 4$. [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. For two sequences S and T of length N consisting of 0 and 1, let us define f(S, T) as follows: - Consider repeating the following operation on S so that S will be equal to T. f(S, T) is the minimum possible total cost of those operations. - Change S_i (from 0 to 1 or vice versa). The cost of this operation is D \times C_i, where D is the number of integers j such that S_j \neq T_j (1 \leq j \leq N) just before this change. There are 2^N \times (2^N - 1) pairs (S, T) of different sequences of length N consisting of 0 and 1. Compute the sum of f(S, T) over all of those pairs, modulo (10^9+7). -----Constraints----- - 1 \leq N \leq 2 \times 10^5 - 1 \leq C_i \leq 10^9 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N C_1 C_2 \cdots C_N -----Output----- Print the sum of f(S, T), modulo (10^9+7). -----Sample Input----- 1 1000000000 -----Sample Output----- 999999993 There are two pairs (S, T) of different sequences of length 2 consisting of 0 and 1, as follows: - S = (0), T = (1): by changing S_1 to 1, we can have S = T at the cost of 1000000000, so f(S, T) = 1000000000. - S = (1), T = (0): by changing S_1 to 0, we can have S = T at the cost of 1000000000, so f(S, T) = 1000000000. The sum of these is 2000000000, and we should print it modulo (10^9+7), that is, 999999993. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have $n \times n$ square grid and an integer $k$. Put an integer in each cell while satisfying the conditions below. All numbers in the grid should be between $1$ and $k$ inclusive. Minimum number of the $i$-th row is $1$ ($1 \le i \le n$). Minimum number of the $j$-th column is $1$ ($1 \le j \le n$). Find the number of ways to put integers in the grid. Since the answer can be very large, find the answer modulo $(10^{9} + 7)$. [Image] These are the examples of valid and invalid grid when $n=k=2$. -----Input----- The only line contains two integers $n$ and $k$ ($1 \le n \le 250$, $1 \le k \le 10^{9}$). -----Output----- Print the answer modulo $(10^{9} + 7)$. -----Examples----- Input 2 2 Output 7 Input 123 456789 Output 689974806 -----Note----- In the first example, following $7$ cases are possible. [Image] In the second example, make sure you print the answer modulo $(10^{9} + 7)$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers. To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets. Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options? -----Input----- The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 10^5). The second line contains n space-separated integers a_{i}. If a_{i} = 1, then the i-th serve was won by Petya, if a_{i} = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record. -----Output----- In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers s_{i} and t_{i} — the option for numbers s and t. Print the options in the order of increasing s_{i}, and for equal s_{i} — in the order of increasing t_{i}. -----Examples----- Input 5 1 2 1 2 1 Output 2 1 3 3 1 Input 4 1 1 1 1 Output 3 1 4 2 2 4 1 Input 4 1 2 1 2 Output 0 Input 8 2 1 2 1 1 1 1 1 Output 3 1 6 2 3 6 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. Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance. The park is a rectangular table with $n$ rows and $m$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $1$. For example, park with $n=m=2$ has $12$ streets. You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park). [Image] The park sizes are: $n=4$, $m=5$. The lighted squares are marked yellow. Please note that all streets have length $1$. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit. Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow. Each test case is a line containing two integers $n$, $m$ ($1 \le n, m \le 10^4$) — park sizes. -----Output----- Print $t$ answers to the test cases. Each answer must be a single integer — the minimum number of lanterns that are required to light all the squares. -----Example----- Input 5 1 1 1 3 2 2 3 3 5 3 Output 1 2 2 5 8 -----Note----- Possible optimal arrangement of the lanterns for the $2$-nd test case of input data example: [Image] Possible optimal arrangement of the lanterns for the $3$-rd test case of input data example: [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) — who knows? Every one of them has an integer sequences a and b of length n. Being given a query of the form of pair of integers (l, r), Mike can instantly tell the value of $\operatorname{max}_{i = l}^{r} a_{i}$ while !Mike can instantly tell the value of $\operatorname{min}_{i = l} b_{i}$. Now suppose a robot (you!) asks them all possible different queries of pairs of integers (l, r) (1 ≤ l ≤ r ≤ n) (so he will make exactly n(n + 1) / 2 queries) and counts how many times their answers coincide, thus for how many pairs $\operatorname{max}_{i = l}^{r} a_{i} = \operatorname{min}_{i = l} b_{i}$ is satisfied. How many occasions will the robot count? -----Input----- The first line contains only integer n (1 ≤ n ≤ 200 000). The second line contains n integer numbers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — the sequence a. The third line contains n integer numbers b_1, b_2, ..., b_{n} ( - 10^9 ≤ b_{i} ≤ 10^9) — the sequence b. -----Output----- Print the only integer number — the number of occasions the robot will count, thus for how many pairs $\operatorname{max}_{i = l}^{r} a_{i} = \operatorname{min}_{i = l} b_{i}$ is satisfied. -----Examples----- Input 6 1 2 3 2 1 4 6 7 1 2 3 2 Output 2 Input 3 3 3 3 1 1 1 Output 0 -----Note----- The occasions in the first sample case are: 1.l = 4,r = 4 since max{2} = min{2}. 2.l = 4,r = 5 since max{2, 1} = min{2, 3}. There are no occasions in the second sample case since Mike will answer 3 to any query pair, but !Mike will always answer 1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them. In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease. You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease. -----Input----- The firt line of the input contains integers n, m, s and t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 1000, 1 ≤ s, t ≤ n, s ≠ t) — the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}), meaning that this road connects junctions u_{i} and v_{i} directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions. -----Output----- Print one integer — the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t. -----Examples----- Input 5 4 1 5 1 2 2 3 3 4 4 5 Output 0 Input 5 4 3 5 1 2 2 3 3 4 4 5 Output 5 Input 5 6 1 5 1 2 1 3 1 4 4 5 3 5 2 5 Output 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a_1, a_2, ..., a_{n}, then after we apply the described operation, the sequence transforms into a_1, a_2, ..., a_{n}[, a_1, a_2, ..., a_{l}] (the block in the square brackets must be repeated c times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja. -----Input----- The first line contains integer m (1 ≤ m ≤ 10^5) — the number of stages to build a sequence. Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer x_{i} (1 ≤ x_{i} ≤ 10^5) — the number to add. Type 2 means copying a prefix of length l_{i} to the end c_{i} times, in this case the line further contains two integers l_{i}, c_{i} (1 ≤ l_{i} ≤ 10^5, 1 ≤ c_{i} ≤ 10^4), l_{i} is the length of the prefix, c_{i} is the number of copyings. It is guaranteed that the length of prefix l_{i} is never larger than the current length of the sequence. The next line contains integer n (1 ≤ n ≤ 10^5) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Output----- Print the elements that Sereja is interested in, in the order in which their numbers occur in the input. -----Examples----- Input 6 1 1 1 2 2 2 1 1 3 2 5 2 1 4 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output 1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 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. Ancient Egyptians are known to have used a large set of symbols $\sum$ to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words S_1 and S_2 of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the words were erased. The symbols in the set $\sum$ have equal probability for being in the position of any erased symbol. Fifa challenged Fafa to calculate the probability that S_1 is lexicographically greater than S_2. Can you help Fafa with this task? You know that $|\sum|= m$, i. e. there were m distinct characters in Egyptians' alphabet, in this problem these characters are denoted by integers from 1 to m in alphabet order. A word x is lexicographically greater than a word y of the same length, if the words are same up to some position, and then the word x has a larger character, than the word y. We can prove that the probability equals to some fraction $P / Q$, where P and Q are coprime integers, and $Q \neq 0 \text{mod}(10^{9} + 7)$. Print as the answer the value $R = P \cdot Q^{-1} \operatorname{mod}(10^{9} + 7)$, i. e. such a non-negative integer less than 10^9 + 7, such that $R \cdot Q \equiv P \operatorname{mod}(10^{9} + 7)$, where $a \equiv b \text{mod}(m)$ means that a and b give the same remainders when divided by m. -----Input----- The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of each of the two words and the size of the alphabet $\sum$, respectively. The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ m) — the symbols of S_1. If a_{i} = 0, then the symbol at position i was erased. The third line contains n integers representing S_2 with the same format as S_1. -----Output----- Print the value $P \cdot Q^{-1} \operatorname{mod}(10^{9} + 7)$, where P and Q are coprime and $P / Q$ is the answer to the problem. -----Examples----- Input 1 2 0 1 Output 500000004 Input 1 2 1 0 Output 0 Input 7 26 0 15 12 9 13 0 14 11 1 0 13 15 12 0 Output 230769233 -----Note----- In the first sample, the first word can be converted into (1) or (2). The second option is the only one that will make it lexicographically larger than the second word. So, the answer to the problem will be $\frac{1}{2} \operatorname{mod}(10^{9} + 7)$, that is 500000004, because $(500000004 \cdot 2) \operatorname{mod}(10^{9} + 7) = 1$. In the second example, there is no replacement for the zero in the second word that will make the first one lexicographically larger. So, the answer to the problem is $\frac{0}{1} \operatorname{mod}(10^{9} + 7)$, that is 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. -----Problem Statement----- Sereja has a sequence of n integers a[1], a[2], ..., a[n]. Sereja can do following transformation of the array: - create a new sequence of n integers b[1], b[2], ..., b[n]in this way: (1 ≤ i ≤ n) - Replace the sequence a by b, i.e., a[i] = b[i] for all i in [1, n] Sereja decided to use his transformation k times. Then he computed the value of , where r — the sequence obtained after k transformations of sequence a, as described above. Sereja lost sequence a, but he was left with the numbers q(r) and k. Now Sereja is interested in the question : what is the number of the sequences of the integers с[1], с[2], ..., с[n], such that 1 ≤ c[i] ≤ m and q(d) = q(r), where d — the sequence obtained after k transformations of sequence c, as described above. -----Input----- The first lines contains a single integer T, denoting the number of test cases. Each test case consist of four integers : n, m, q(r), k. -----Output----- In a single line print the remainder of division the answer of the problem on number 10^9 + 7. -----Constraints----- - 1 ≤ T ≤ 10000 - 1 ≤ n, m, q(r), k ≤ 10^9 -----Example----- Input: 3 1 1 1 1 2 2 1 1 2 3 1 1 Output: 0 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. Is the number even? If the numbers is even return `true`. If it's odd, return `false`. Oh yeah... the following symbols/commands have been disabled! use of ```%``` use of ```.even?``` in Ruby use of ```mod``` in Python Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given a random string consisting of numbers, letters, symbols, you need to sum up the numbers in the string. Note: - Consecutive integers should be treated as a single number. eg, `2015` should be treated as a single number `2015`, NOT four numbers - All the numbers should be treaded as positive integer. eg, `11-14` should be treated as two numbers `11` and `14`. Same as `3.14`, should be treated as two numbers `3` and `14` - If no number was given in the string, it should return `0` Example: ``` str = "In 2015, I want to know how much does iPhone 6+ cost?" ``` The numbers are `2015`, `6` Sum is `2021`. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Alice is playing with some stones. Now there are three numbered heaps of stones. The first of them contains $a$ stones, the second of them contains $b$ stones and the third of them contains $c$ stones. Each time she can do one of two operations: take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones); take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones). She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $0$ stones. Can you help her? -----Input----- The first line contains one integer $t$ ($1 \leq t \leq 100$)  — the number of test cases. Next $t$ lines describe test cases in the following format: Line contains three non-negative integers $a$, $b$ and $c$, separated by spaces ($0 \leq a,b,c \leq 100$) — the number of stones in the first, the second and the third heap, respectively. In hacks it is allowed to use only one test case in the input, so $t = 1$ should be satisfied. -----Output----- Print $t$ lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer  — the maximum possible number of stones that Alice can take after making some operations. -----Example----- Input 3 3 4 5 1 0 5 5 3 2 Output 9 0 6 -----Note----- For the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is $9$. It is impossible to make some operations to take more than $9$ stones, so the answer is $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 an integer $n$. In $1$ move, you can do one of the following actions: erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is "empty"); add one digit to the right. The actions may be performed in any order any number of times. Note that if, after deleting some digit from a number, it will contain leading zeroes, they will not be deleted. E.g. if you delete from the number $301$ the digit $3$, the result is the number $01$ (not $1$). You need to perform the minimum number of actions to make the number any power of $2$ (i.e. there's an integer $k$ ($k \ge 0$) such that the resulting number is equal to $2^k$). The resulting number must not have leading zeroes. E.g. consider $n=1052$. The answer is equal to $2$. First, let's add to the right one digit $4$ (the result will be $10524$). Then let's erase the digit $5$, so the result will be $1024$ which is a power of $2$. E.g. consider $n=8888$. The answer is equal to $3$. Let's erase any of the digits $8$ three times. The result will be $8$ which is a power of $2$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow. Each test case consists of one line containing one integer $n$ ($1 \le n \le 10^9$). -----Output----- For each test case, output in a separate line one integer $m$ — the minimum number of moves to transform the number into any power of $2$. -----Examples----- Input 12 1052 8888 6 75 128 1 301 12048 1504 6656 1000000000 687194767 Output 2 3 1 3 0 0 2 1 3 4 9 2 -----Note----- The answer for the first test case was considered above. The answer for the second test case was considered above. In the third test case, it's enough to add to the right the digit $4$ — the number $6$ will turn into $64$. In the fourth test case, let's add to the right the digit $8$ and then erase $7$ and $5$ — the taken number will turn into $8$. The numbers of the fifth and the sixth test cases are already powers of two so there's no need to make any move. In the seventh test case, you can delete first of all the digit $3$ (the result is $01$) and then the digit $0$ (the result is $1$). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes. Some examples of beautiful numbers: 1_2 (1_10); 110_2 (6_10); 1111000_2 (120_10); 111110000_2 (496_10). More formally, the number is beautiful iff there exists some positive integer k such that the number is equal to (2^{k} - 1) * (2^{k} - 1). Luba has got an integer number n, and she wants to find its greatest beautiful divisor. Help her to find it! -----Input----- The only line of input contains one number n (1 ≤ n ≤ 10^5) — the number Luba has got. -----Output----- Output one number — the greatest beautiful divisor of Luba's number. It is obvious that the answer always exists. -----Examples----- Input 3 Output 1 Input 992 Output 496 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given two words and a letter, return a single word that's a combination of both words, merged at the point where the given letter first appears in each word. The returned word should have the beginning of the first word and the ending of the second, with the dividing letter in the middle. You can assume both words will contain the dividing letter. ## Examples ```python string_merge("hello", "world", "l") ==> "held" string_merge("coding", "anywhere", "n") ==> "codinywhere" string_merge("jason", "samson", "s") ==> "jasamson" string_merge("wonderful", "people", "e") ==> "wondeople" ``` Read the inputs from stdin solve the problem and write the answer to stdout (do 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 positive integers N and K. Determine if the 3N integers K, K+1, ..., K+3N-1 can be partitioned into N triples (a_1,b_1,c_1), ..., (a_N,b_N,c_N) so that the condition below is satisfied. Any of the integers K, K+1, ..., K+3N-1 must appear in exactly one of those triples. * For every integer i from 1 to N, a_i + b_i \leq c_i holds. If the answer is yes, construct one such partition. Constraints * 1 \leq N \leq 10^5 * 1 \leq K \leq 10^9 Input Input is given from Standard Input in the following format: N K Output If it is impossible to partition the integers satisfying the condition, print `-1`. If it is possible, print N triples in the following format: a_1 b_1 c_1 : a_N b_N c_N Output If it is impossible to partition the integers satisfying the condition, print `-1`. If it is possible, print N triples in the following format: a_1 b_1 c_1 : a_N b_N c_N Examples Input 1 1 Output 1 2 3 Input 3 3 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. Ridbit starts with an integer $n$. In one move, he can perform one of the following operations: divide $n$ by one of its proper divisors, or subtract $1$ from $n$ if $n$ is greater than $1$. A proper divisor is a divisor of a number, excluding itself. For example, $1$, $2$, $4$, $5$, and $10$ are proper divisors of $20$, but $20$ itself is not. What is the minimum number of moves Ridbit is required to make to reduce $n$ to $1$? -----Input----- The first line contains a single integer $t$ ($1 \leq t \leq 1000$) — the number of test cases. The only line of each test case contains a single integer $n$ ($1 \leq n \leq 10^9$). -----Output----- For each test case, output the minimum number of moves required to reduce $n$ to $1$. -----Examples----- Input 6 1 2 3 4 6 9 Output 0 1 2 2 2 3 -----Note----- For the test cases in the example, $n$ may be reduced to $1$ using the following operations in sequence $1$ $2 \xrightarrow{} 1$ $3 \xrightarrow{} 2 \xrightarrow{} 1$ $4 \xrightarrow{} 2 \xrightarrow{} 1$ $6 \xrightarrow{} 2 \xrightarrow{} 1$ $9 \xrightarrow{} 3 \xrightarrow{} 2\xrightarrow{} 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. Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $n$ problems of distinct difficulty, the difficulties are numbered from $1$ to $n$. To hold a round Arkady needs $n$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from $1$ to $n$ and puts it into the problems pool. At each moment when Arkady can choose a set of $n$ new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it. You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty. -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n, m \le 10^5$) — the number of difficulty levels and the number of problems Arkady created. The second line contains $m$ integers $a_1, a_2, \ldots, a_m$ ($1 \le a_i \le n$) — the problems' difficulties in the order Arkady created them. -----Output----- Print a line containing $m$ digits. The $i$-th digit should be $1$ if Arkady held the round after creation of the $i$-th problem, and $0$ otherwise. -----Examples----- Input 3 11 2 3 1 2 2 2 3 2 2 3 1 Output 00100000001 Input 4 8 4 1 3 3 2 3 3 3 Output 00001000 -----Note----- In the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You're given a list of n strings a_1, a_2, ..., a_{n}. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. -----Input----- The first line contains integer n — the number of strings (1 ≤ n ≤ 5·10^4). Each of the next n lines contains one string a_{i} (1 ≤ |a_{i}| ≤ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5·10^4. -----Output----- Print the only string a — the lexicographically smallest string concatenation. -----Examples----- Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help. A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c. Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps. Help the Beaver to write a program that will encrypt messages in the described manner. Input The first input line contains three integers n, m and c, separated by single spaces. The second input line contains n integers ai (0 ≤ ai < c), separated by single spaces — the original message. The third input line contains m integers bi (0 ≤ bi < c), separated by single spaces — the encryption key. The input limitations for getting 30 points are: * 1 ≤ m ≤ n ≤ 103 * 1 ≤ c ≤ 103 The input limitations for getting 100 points are: * 1 ≤ m ≤ n ≤ 105 * 1 ≤ c ≤ 103 Output Print n space-separated integers — the result of encrypting the original message. Examples Input 4 3 2 1 1 1 1 1 1 1 Output 0 1 1 0 Input 3 1 5 1 2 3 4 Output 0 1 2 Note In the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners:$(0 ; 0),(a_{1} ; a_{1}),(a_{1} + a_{2} ; a_{1} - a_{2}),(a_{1} + a_{2} + a_{3} ; a_{1} - a_{2} + a_{3}), \ldots,(\sum_{i = 1}^{n} a_{i} ; \sum_{i = 1}^{n}(- 1)^{i + 1} a_{i})$ That is, a cardiogram is fully defined by a sequence of positive integers a_1, a_2, ..., a_{n}. Your task is to paint a cardiogram by given sequence a_{i}. -----Input----- The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000). It is guaranteed that the sum of all a_{i} doesn't exceed 1000. -----Output----- Print max |y_{i} - y_{j}| lines (where y_{k} is the y coordinate of the k-th point of the polyline), in each line print $\sum_{i = 1}^{n} a_{i}$ characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram. Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty. -----Examples----- Input 5 3 1 2 5 1 Output / \ / \ / \ / \ / \ \ / Input 3 1 5 1 Output / \ \ \ \ \ / Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number t_{i}: If Petya has visited this room before, he writes down the minute he was in this room last time; Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t_0. At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook? -----Input----- The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — then number of notes in Petya's logbook. The second line contains n non-negative integers t_1, t_2, ..., t_{n} (0 ≤ t_{i} < i) — notes in the logbook. -----Output----- In the only line print a single integer — the minimum possible number of rooms in Paris catacombs. -----Examples----- Input 2 0 0 Output 2 Input 5 0 1 0 1 3 Output 3 -----Note----- In the first sample, sequence of rooms Petya visited could be, for example 1 → 1 → 2, 1 → 2 → 1 or 1 → 2 → 3. The minimum possible number of rooms is 2. In the second sample, the sequence could be 1 → 2 → 3 → 1 → 2 → 1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. One of the oddest traditions of the town of Gameston may be that even the town mayor of the next term is chosen according to the result of a game. When the expiration of the term of the mayor approaches, at least three candidates, including the mayor of the time, play a game of pebbles, and the winner will be the next mayor. The rule of the game of pebbles is as follows. In what follows, n is the number of participating candidates. Requisites A round table, a bowl, and plenty of pebbles. Start of the Game A number of pebbles are put into the bowl; the number is decided by the Administration Commission using some secret stochastic process. All the candidates, numbered from 0 to n-1 sit around the round table, in a counterclockwise order. Initially, the bowl is handed to the serving mayor at the time, who is numbered 0. Game Steps When a candidate is handed the bowl and if any pebbles are in it, one pebble is taken out of the bowl and is kept, together with those already at hand, if any. If no pebbles are left in the bowl, the candidate puts all the kept pebbles, if any, into the bowl. Then, in either case, the bowl is handed to the next candidate to the right. This step is repeated until the winner is decided. End of the Game When a candidate takes the last pebble in the bowl, and no other candidates keep any pebbles, the game ends and that candidate with all the pebbles is the winner. A math teacher of Gameston High, through his analysis, concluded that this game will always end within a finite number of steps, although the number of required steps can be very large. Input The input is a sequence of datasets. Each dataset is a line containing two integers n and p separated by a single space. The integer n is the number of the candidates including the current mayor, and the integer p is the total number of the pebbles initially put in the bowl. You may assume 3 ≤ n ≤ 50 and 2 ≤ p ≤ 50. With the settings given in the input datasets, the game will end within 1000000 (one million) steps. The end of the input is indicated by a line containing two zeros separated by a single space. Output The output should be composed of lines corresponding to input datasets in the same order, each line of which containing the candidate number of the winner. No other characters should appear in the output. Sample Input 3 2 3 3 3 50 10 29 31 32 50 2 50 50 0 0 Output for the Sample Input 1 0 1 5 30 1 13 Example Input 3 2 3 3 3 50 10 29 31 32 50 2 50 50 0 0 Output 1 0 1 5 30 1 13 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a matrix, consisting of n rows and m columns. The rows are numbered top to bottom, the columns are numbered left to right. Each cell of the matrix can be either free or locked. Let's call a path in the matrix a staircase if it: * starts and ends in the free cell; * visits only free cells; * has one of the two following structures: 1. the second cell is 1 to the right from the first one, the third cell is 1 to the bottom from the second one, the fourth cell is 1 to the right from the third one, and so on; 2. the second cell is 1 to the bottom from the first one, the third cell is 1 to the right from the second one, the fourth cell is 1 to the bottom from the third one, and so on. In particular, a path, consisting of a single cell, is considered to be a staircase. Here are some examples of staircases: <image> Initially all the cells of the matrix are free. You have to process q queries, each of them flips the state of a single cell. So, if a cell is currently free, it makes it locked, and if a cell is currently locked, it makes it free. Print the number of different staircases after each query. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path. Input The first line contains three integers n, m and q (1 ≤ n, m ≤ 1000; 1 ≤ q ≤ 10^4) — the sizes of the matrix and the number of queries. Each of the next q lines contains two integers x and y (1 ≤ x ≤ n; 1 ≤ y ≤ m) — the description of each query. Output Print q integers — the i-th value should be equal to the number of different staircases after i queries. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path. Examples Input 2 2 8 1 1 1 1 1 1 2 2 1 1 1 2 2 1 1 1 Output 5 10 5 2 5 3 1 0 Input 3 4 10 1 4 1 2 2 3 1 2 2 3 3 2 1 3 3 4 1 3 3 1 Output 49 35 24 29 49 39 31 23 29 27 Input 1000 1000 2 239 634 239 634 Output 1332632508 1333333000 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Compute A \times B, truncate its fractional part, and print the result as an integer. -----Constraints----- - 0 \leq A \leq 10^{15} - 0 \leq B < 10 - A is an integer. - B is a number with two digits after the decimal point. -----Input----- Input is given from Standard Input in the following format: A B -----Output----- Print the answer as an integer. -----Sample Input----- 198 1.10 -----Sample Output----- 217 We have 198 \times 1.10 = 217.8. After truncating the fractional part, we have the answer: 217. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert. There are $n_1$ different types of first courses Ivan can buy (the $i$-th of them costs $a_i$ coins), $n_2$ different types of second courses (the $i$-th of them costs $b_i$ coins), $n_3$ different types of drinks (the $i$-th of them costs $c_i$ coins) and $n_4$ different types of desserts (the $i$-th of them costs $d_i$ coins). Some dishes don't go well with each other. There are $m_1$ pairs of first courses and second courses that don't go well with each other, $m_2$ pairs of second courses and drinks, and $m_3$ pairs of drinks and desserts that don't go well with each other. Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option! -----Input----- The first line contains four integers $n_1$, $n_2$, $n_3$ and $n_4$ ($1 \le n_i \le 150000$) — the number of types of first courses, second courses, drinks and desserts, respectively. Then four lines follow. The first line contains $n_1$ integers $a_1, a_2, \dots, a_{n_1}$ ($1 \le a_i \le 10^8$), where $a_i$ is the cost of the $i$-th type of first course. Three next lines denote the costs of second courses, drinks, and desserts in the same way ($1 \le b_i, c_i, d_i \le 10^8$). The next line contains one integer $m_1$ ($0 \le m_1 \le 200000$) — the number of pairs of first and second courses that don't go well with each other. Each of the next $m_1$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i \le n_1$; $1 \le y_i \le n_2$) denoting that the first course number $x_i$ doesn't go well with the second course number $y_i$. All these pairs are different. The block of pairs of second dishes and drinks that don't go well with each other is given in the same format. The same for pairs of drinks and desserts that don't go well with each other ($0 \le m_2, m_3 \le 200000$). -----Output----- If it's impossible to choose a first course, a second course, a drink, and a dessert so that they go well with each other, print $-1$. Otherwise, print one integer — the minimum total cost of the dinner. -----Examples----- Input 4 3 2 1 1 2 3 4 5 6 7 8 9 10 2 1 2 1 1 2 3 1 3 2 1 1 1 Output 26 Input 1 1 1 1 1 1 1 1 1 1 1 0 0 Output -1 -----Note----- The best option in the first example is to take the first course $2$, the second course $1$, the drink $2$ and the dessert $1$. In the second example, the only pair of the first course and the second course is bad, so it's impossible to have dinner. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 cities numbered 1 through N, and M bidirectional roads numbered 1 through M. Road i connects City A_i and City B_i. Snuke can perform the following operation zero or more times: * Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities. After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times). What is the minimum number of roads he must build to achieve the goal? Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 100,000 * 1 \leq A_i < B_i \leq N * No two roads connect the same pair of cities. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 : A_M B_M Output Print the answer. Example Input 3 1 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. Dima's got a staircase that consists of n stairs. The first stair is at height a_1, the second one is at a_2, the last one is at a_{n} (1 ≤ a_1 ≤ a_2 ≤ ... ≤ a_{n}). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width w_{i} and height h_{i}. Dima throws each box vertically down on the first w_{i} stairs of the staircase, that is, the box covers stairs with numbers 1, 2, ..., w_{i}. Each thrown box flies vertically down until at least one of the two following events happen: the bottom of the box touches the top of a stair; the bottom of the box touches the top of a box, thrown earlier. We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width w_{i} cannot touch the stair number w_{i} + 1. You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the number of stairs in the staircase. The second line contains a non-decreasing sequence, consisting of n integers, a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9; a_{i} ≤ a_{i} + 1). The next line contains integer m (1 ≤ m ≤ 10^5) — the number of boxes. Each of the following m lines contains a pair of integers w_{i}, h_{i} (1 ≤ w_{i} ≤ n; 1 ≤ h_{i} ≤ 10^9) — the size of the i-th thrown box. The numbers in the lines are separated by spaces. -----Output----- Print m integers — for each box the height, where the bottom of the box will be after landing. Print the answers for the boxes in the order, in which the boxes are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 5 1 2 3 6 6 4 1 1 3 1 1 1 4 3 Output 1 3 4 6 Input 3 1 2 3 2 1 1 3 1 Output 1 3 Input 1 1 5 1 2 1 10 1 10 1 10 1 10 Output 1 3 13 23 33 -----Note----- The first sample are shown on the picture. [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a line of $n$ colored squares in a row, numbered from $1$ to $n$ from left to right. The $i$-th square initially has the color $c_i$. Let's say, that two squares $i$ and $j$ belong to the same connected component if $c_i = c_j$, and $c_i = c_k$ for all $k$ satisfying $i < k < j$. In other words, all squares on the segment from $i$ to $j$ should have the same color. For example, the line $[3, 3, 3]$ has $1$ connected component, while the line $[5, 2, 4, 4]$ has $3$ connected components. The game "flood fill" is played on the given line as follows: At the start of the game you pick any starting square (this is not counted as a turn). Then, in each game turn, change the color of the connected component containing the starting square to any other color. Find the minimum number of turns needed for the entire line to be changed into a single color. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 5000$) — the number of squares. The second line contains integers $c_1, c_2, \ldots, c_n$ ($1 \le c_i \le 5000$) — the initial colors of the squares. -----Output----- Print a single integer — the minimum number of the turns needed. -----Examples----- Input 4 5 2 2 1 Output 2 Input 8 4 5 2 2 1 3 5 5 Output 4 Input 1 4 Output 0 -----Note----- In the first example, a possible way to achieve an optimal answer is to pick square with index $2$ as the starting square and then play as follows: $[5, 2, 2, 1]$ $[5, 5, 5, 1]$ $[1, 1, 1, 1]$ In the second example, a possible way to achieve an optimal answer is to pick square with index $5$ as the starting square and then perform recoloring into colors $2, 3, 5, 4$ in that order. In the third example, the line already consists of one color only. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an integer $x$ of $n$ digits $a_1, a_2, \ldots, a_n$, which make up its decimal notation in order from left to right. Also, you are given a positive integer $k < n$. Let's call integer $b_1, b_2, \ldots, b_m$ beautiful if $b_i = b_{i+k}$ for each $i$, such that $1 \leq i \leq m - k$. You need to find the smallest beautiful integer $y$, such that $y \geq x$. -----Input----- The first line of input contains two integers $n, k$ ($2 \leq n \leq 200\,000, 1 \leq k < n$): the number of digits in $x$ and $k$. The next line of input contains $n$ digits $a_1, a_2, \ldots, a_n$ ($a_1 \neq 0$, $0 \leq a_i \leq 9$): digits of $x$. -----Output----- In the first line print one integer $m$: the number of digits in $y$. In the next line print $m$ digits $b_1, b_2, \ldots, b_m$ ($b_1 \neq 0$, $0 \leq b_i \leq 9$): digits of $y$. -----Examples----- Input 3 2 353 Output 3 353 Input 4 2 1234 Output 4 1313 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Chef's house there are N apples lying in a row on the floor. These apples are numbered from 1 (left most one) to N (right most one). The types of apples are also numbered by positive integers, and the type of apple i is Ti. Chef has recently brought two trained dogs. Both of the dogs are too intelligent to know the smell of each type of apple. If Chef gives a dog an integer x, and releases it at one end of the row of apples, then the dog smells each apple one by one. Once the dog find an apple of type x, the dog picks the apple and back to Chef's room immidiately. If there is no apple of type x, then the dog will back without any apples. Now Chef wants to eat two apples as soon as possible. Here the apples must have distinct types, and the sum of the types must be equal to K. Chef can release the dogs from either of the ends, namely, he can leave (both at left end) or (both at right end) or (one at left end and one at right end) and he can release them at the same time. The dogs take one second to smell each apple. However the dogs can run rapidly, so the time for moving can be ignored. What is the minimum time (in seconds) to get the desired apples from his dogs? -----Input----- The first line of input contains two space-separated integers N and K, denoting the number of apples and the required sum respectively. Then the next line contains N space-separated integers T1, T2, ..., TN, denoting the types of the apples. -----Output----- Print one integer describing the minimum number of seconds that Chef needs to wait till he gets the desired apples. If Chef cannot get the desired apples, then output "-1" without quotes. -----Constraints----- - 2 ≤ N ≤ 500000 (5 × 105) - 1 ≤ K ≤ 1000000 (106) - 1 ≤ Ti ≤ 1000000 (106) -----Example----- Sample Input 1: 5 5 2 4 3 2 1 Sample Output 1: 2 Sample Input 2: 5 5 2 4 9 2 5 Sample Output 2: -1 -----Explanation----- In the first example, if Chef leaves the first dog from left and gives it integer 4, and the second dog from right and gives it integer 1, then the first dog takes 2 seconds and the second dog takes 1 second to get the apples. Thus Chef needs to wait 2 seconds. In any other way, Chef can't get the desired apples in less than 2 seconds. In the second example, Chef cannot get two apples such that the sum of their types is 5 so the answer is "-1". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a string $s$ consisting of lowercase Latin letters. Let the length of $s$ be $|s|$. You may perform several operations on this string. In one operation, you can choose some index $i$ and remove the $i$-th character of $s$ ($s_i$) if at least one of its adjacent characters is the previous letter in the Latin alphabet for $s_i$. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index $i$ should satisfy the condition $1 \le i \le |s|$ during each operation. For the character $s_i$ adjacent characters are $s_{i-1}$ and $s_{i+1}$. The first and the last characters of $s$ both have only one adjacent character (unless $|s| = 1$). Consider the following example. Let $s=$ bacabcab. During the first move, you can remove the first character $s_1=$ b because $s_2=$ a. Then the string becomes $s=$ acabcab. During the second move, you can remove the fifth character $s_5=$ c because $s_4=$ b. Then the string becomes $s=$ acabab. During the third move, you can remove the sixth character $s_6=$'b' because $s_5=$ a. Then the string becomes $s=$ acaba. During the fourth move, the only character you can remove is $s_4=$ b, because $s_3=$ a (or $s_5=$ a). The string becomes $s=$ acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally. -----Input----- The first line of the input contains one integer $|s|$ ($1 \le |s| \le 100$) — the length of $s$. The second line of the input contains one string $s$ consisting of $|s|$ lowercase Latin letters. -----Output----- Print one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally. -----Examples----- Input 8 bacabcab Output 4 Input 4 bcda Output 3 Input 6 abbbbb Output 5 -----Note----- The first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only, but it can be shown that the maximum possible answer to this test is $4$. In the second example, you can remove all but one character of $s$. The only possible answer follows. During the first move, remove the third character $s_3=$ d, $s$ becomes bca. During the second move, remove the second character $s_2=$ c, $s$ becomes ba. And during the third move, remove the first character $s_1=$ b, $s$ becomes a. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations: * find(s, t): report the minimum element in as, as+1, . . . ,at. * update(i, x): change ai to x. Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1. Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 100000 * If comi is 0, then 0 ≤ xi < n, 0 ≤ yi < 231-1. * If comi is 1, then 0 ≤ xi < n, 0 ≤ yi < n. Input n q com0 x0 y0 com1 x1 y1 ... comq−1 xq−1 yq−1 In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes update(xi, yi) and '1' denotes find(xi, yi). Output For each find operation, print the minimum element. Examples Input 3 5 0 0 1 0 1 2 0 2 3 1 0 2 1 1 2 Output 1 2 Input 1 3 1 0 0 0 0 5 1 0 0 Output 2147483647 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The last stage of Football World Cup is played using the play-off system. There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over. Arkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids a and b can meet. -----Input----- The only line contains three integers n, a and b (2 ≤ n ≤ 256, 1 ≤ a, b ≤ n) — the total number of teams, and the ids of the teams that Arkady is interested in. It is guaranteed that n is such that in each round an even number of team advance, and that a and b are not equal. -----Output----- In the only line print "Final!" (without quotes), if teams a and b can meet in the Final. Otherwise, print a single integer — the number of the round in which teams a and b can meet. The round are enumerated from 1. -----Examples----- Input 4 1 2 Output 1 Input 8 2 6 Output Final! Input 8 7 5 Output 2 -----Note----- In the first example teams 1 and 2 meet in the first round. In the second example teams 2 and 6 can only meet in the third round, which is the Final, if they win all their opponents in earlier rounds. In the third example the teams with ids 7 and 5 can meet in the second round, if they win their opponents in the first round. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this kata. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Dr .: Peter, I've finally done it. Peter: See you again? What kind of silly invention is this time? Dr .: I finally came up with a revolutionary way to process mathematical formulas on a computer. Look at this table. Ordinary notation | Dr.'s "breakthrough" notation --- | --- 1 + 2 | 1 2 + 3 * 4 + 7 | 3 4 * 7 + 10 / (2 --12) | 10 2 12-/ (3-4) * (7 + 2 * 3) | 3 4 --7 2 3 * + * Peter: Yeah. Dr .: Fufufu. This alone won't tell you what it means to an inexperienced person. It's important from here. Peter: I mean ... Dr .: You know that computers have a data structure called a stack. Look, that's "first in, then out". Peter: Yes. I know, that ... Dr .: This groundbreaking notation uses that stack. For example, this 10 2 12-/, but process as follows. Processing target | 10 | 2 | 12 |-| / --- | --- | --- | --- | --- | --- | ↓ | ↓ | ↓ | ↓ 2-12 | ↓ 10 / -10 Stack | |. --- .. Ten | .. --- 2 Ten | 12 --- 2 Ten | .. --- -Ten Ten | .. --- .. -1 Dr .: How is it? You don't have to worry about parentheses or operator precedence, right? The word order is also "10 divided by 2 minus 12", which is somewhat similar to his Far Eastern island nation, Japanese. With this epoch-making invention, our laboratory is safe. Fafafa. Peter: I mean, Doctor. I learned this in the basic course at the University of Aizu when I was in Japan. Everyone had a simple program called "Reverse Polish Notation". Dr .: ... So, instead of Peter, I decided to teach this program to the doctor. Create a program that inputs the formula written in "Reverse Polish Notation" and outputs the calculation result. input Given multiple datasets. For each dataset, a formula in Reverse Polish Notation (a string of up to 80 characters with integers and arithmetic symbols separated by one blank character (half-width)) is given on one line. No formula is given that divides a value by 0 or a value that is as close to 0 as possible. The number of datasets does not exceed 50. output Output the calculation result (real number) on one line for each data set. The calculation result may include an error of 0.00001 or less. Example Input 10 2 12 - / 3 4 - 7 2 3 * + * -1 -2 3 + + Output -1.000000 -13.000000 0.000000 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given a string of integers, count how many times that integer repeats itself, then return a string showing the count and the integer. Example: `countMe('1123')` (`count_me` in Ruby) - Here 1 comes twice so `` will be `"21"` - then 2 comes once so `` will be `"12"` - then 3 comes once so `` will be `"13"` hence output string will be `"211213"`. Similarly `countMe('211213')` will return `'1221121113'` (1 time 2, 2 times 1, 1 time 2, 1 time 1, 1 time 3) Return `""` for empty, nil or non numeric strings Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.