question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. A rabbit who came to the fair found that the prize for a game at a store was a carrot cake. The rules for this game are as follows. There is a grid-like field of vertical h squares x horizontal w squares, and each block has at most one block. Each block is a color represented by one of the uppercase letters ('A'-'Z'). When n or more blocks of the same color are lined up in a straight line vertically or horizontally, those blocks disappear. Participants can select two adjacent cells next to each other and switch their states to each other. When blocks are exchanged, disappeared, or dropped and there are no blocks in the cell below the cell with the block, this block At this time, it disappears when n or more blocks of the same color are lined up again. However, the disappearance of the blocks does not occur while the falling blocks exist, and occurs at the same time when all the blocks have finished falling. If you eliminate all the blocks on the field with one operation, this game will be successful and you will get a free gift cake. Rabbit wants to get the cake with one entry fee, can not do it If you don't want to participate. From the state of the field at the beginning of the game, answer if the rabbit should participate in this game. Input The first line of input is given h, w, n separated by spaces. 2 ≀ h, w, n ≀ 30 In the following h lines, the state of the field is given in order from the top. Uppercase letters represent blocks, and'.' Represents an empty space. The state of the given field is n or more consecutive blocks of the same color in the vertical or horizontal direction. No, no blocks are in a falling state. There is one or more blocks. Output Output "YES" if the rabbit should participate in this game, otherwise output "NO" on one line. Examples Input 4 6 3 ...... ...Y.. ...Y.. RRYRYY Output YES Input 4 6 3 ...... ...Y.. ...Y.. RRYRY. Output NO The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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: Flick input A college student who loves 2D, commonly known as 2D, replaced his long-used Galapagos mobile phone with a smartphone. 2D, who operated the smartphone for the first time, noticed that the character input method was a little different from that of old mobile phones. On smartphones, a method called flick input was adopted by taking advantage of the fact that the screen can be touch-flicked (flick means "the operation of sliding and flipping a finger on the screen"). Flick input is a character input method as shown below. In flick input, as shown in Fig. A (a), input is performed using 10 buttons 0-9 (# and * are omitted this time). Each button is assigned one row-row row as shown in the figure. <image> --- Figure A: Smartphone button details One button can be operated by the method shown in Fig. A (b). In other words * If you just "touch" a button, the character "Adan" corresponding to that button will be output. * Press the button "flick to the left" to output "Idan" * When you press the button "flick upward", "Udan" is output. * Press the button "flick to the right" to output "Edan" * Press the button "flick down" to output "step" That's what it means. Figure A (c) shows how to input flicks for all buttons. Note that you flick button 0 upwards to output "n". Your job is to find the string that will be output as a result of a flick input operation, given a string that indicates that operation. Input A character string representing a flick input operation is given on one line (2 to 1000 characters). This character string consists of the numbers '0'-'9', which represent the buttons to be operated, and the five types of characters,'T',' L',' U',' R', and'D', which represent the flick direction. It consists of a combination. The characters that represent the flick direction have the following meanings. *'T': Just touch *'L': Flick left *'U': Flick up *'R': Flick right *'D': Flick down For example, "2D" represents the operation of "flicking the button of 2 downward", so "ko" can be output. In the given character string, one number and one character indicating the flick direction appear alternately. Also, it always starts with one number and ends with one letter indicating the flick direction. Furthermore, in Fig. A (c), flicking is not performed toward a place without characters (there is no input such as "8L"). Output Output the character string representing the result of the flick input operation in Roman characters. For romaji consonants, * Or line:'k' * Sayuki:'s' * Ta line:'t' * Line:'n' * Is the line:'h' * Ma line:'m' * Ya line:'y' * Line:'r' * Wa line:'w' to use. Romaji, which represents one hiragana character, should be output as a set of the consonants and vowels ('a','i','u','e','o') represented above. "shi" and "fu" are wrong because they violate this condition. However, the character "A line" should output only one vowel character, and "n" should output "n" twice in a row as "nn". Output a line break at the end of the character string. Sample Input 1 5R2D Sample Output 1 neko Sample Input 2 8U9U6U0T Sample Output 2 yuruhuwa Sample Input 3 9L4U7R1L2D0U4R3U4D Sample Output 3 ritumeikonntesuto Example Input 5R2D Output neko The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Example Input 7 >> Output 7 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Taro has N character strings, each of which is L in length. Taro loves palindromes, so I want to make palindromes as long as possible by selecting some of the N character strings and arranging them in any order. Find the longest palindrome that Taro can make. If there are more than one, output the smallest one in lexicographical order. If you can't make a palindrome no matter how you choose and arrange them, output a blank line. Constraints The input satisfies the following conditions. * 1 ≀ N ≀ 1000 * 1 ≀ L ≀ 30 * s_i is a character string consisting of lowercase letters. Input The input is given in the following format. N L s1 s2 .. .. .. sN The number N of strings and the length L of strings are given on the first line. From the second line that follows, N & plus; The character string s_i that Taro has is given to the first line. Output Output the longest palindrome with the smallest dictionary order. If you cannot make a palindrome, output a blank line. Examples Input 4 2 oi io rr rr Output iorrrroi Input 5 1 a b c a c Output acbca Input 3 3 uki uku uke Output uku The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 $ acitivities with start times $ \\ {s_i \\} $ and finish times $ \\ {t_i \\} $. Assuming that a person can only work on a single activity at a time, find the maximum number of activities that can be performed by a single person. Constraints * $ 1 \ le n \ le 10 ^ 5 $ * $ 1 \ le s_i \ lt t_i \ le 10 ^ 9 (1 \ le i \ le n) $ Input $ n $ $ s_1 $ $ t_1 $ $ s_2 $ $ t_2 $ :: $ s_n $ $ t_n $ The first line consists of the integer $ n $. In the following $ n $ lines, the start time $ s_i $ and the finish time $ t_i $ of the activity $ i $ are given. output Print the maximum number of activities in a line. Examples Input 5 1 2 3 9 3 5 5 9 6 8 Output 3 Input 3 1 5 3 4 2 5 Output 1 Input 3 1 2 2 3 3 4 Output 2 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 C loves number Β«3Β» very much. He loves all things about it. Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution. Input A single line containing one integer n (3 ≀ n ≀ 10^9) β€” the integer Little C has. Output Print 3 positive integers a,b,c in a single line, such that a+b+c=n and none of them is a multiple of 3. It can be proved that there is at least one solution. If there are multiple solutions, print any of them. Examples Input 3 Output 1 1 1 Input 233 Output 77 77 79 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain. Each colony arrangement can be expressed as a string of even length, where the i-th character of the string represents the type of villain in the i-th hole. Iron Man can destroy a colony only if the colony arrangement is such that all villains of a certain type either live in the first half of the colony or in the second half of the colony. His assistant Jarvis has a special power. It can swap villains of any two holes, i.e. swap any two characters in the string; he can do this operation any number of times. Now Iron Man asks Jarvis q questions. In each question, he gives Jarvis two numbers x and y. Jarvis has to tell Iron Man the number of distinct colony arrangements he can create from the original one using his powers such that all villains having the same type as those originally living in x-th hole or y-th hole live in the same half and the Iron Man can destroy that colony arrangement. Two colony arrangements are considered to be different if there exists a hole such that different types of villains are present in that hole in the arrangements. Input The first line contains a string s (2 ≀ |s| ≀ 10^{5}), representing the initial colony arrangement. String s can have both lowercase and uppercase English letters and its length is even. The second line contains a single integer q (1 ≀ q ≀ 10^{5}) β€” the number of questions. The i-th of the next q lines contains two integers x_i and y_i (1 ≀ x_i, y_i ≀ |s|, x_i β‰  y_i) β€” the two numbers given to the Jarvis for the i-th question. Output For each question output the number of arrangements possible modulo 10^9+7. Examples Input abba 2 1 4 1 2 Output 2 0 Input AAaa 2 1 2 1 3 Output 2 0 Input abcd 1 1 3 Output 8 Note Consider the first example. For the first question, the possible arrangements are "aabb" and "bbaa", and for the second question, index 1 contains 'a' and index 2 contains 'b' and there is no valid arrangement in which all 'a' and 'b' are in the same half. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day β€” it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day. Days go one after another endlessly and Polycarp uses the same schedule for each day. What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day. Input The first line contains n (1 ≀ n ≀ 2β‹…10^5) β€” number of hours per day. The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 1), where a_i=0 if the i-th hour in a day is working and a_i=1 if the i-th hour is resting. It is guaranteed that a_i=0 for at least one i. Output Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day. Examples Input 5 1 0 1 0 1 Output 2 Input 6 0 1 0 1 1 0 Output 2 Input 7 1 0 1 1 1 0 1 Output 3 Input 3 0 0 0 Output 0 Note In the first example, the maximal rest starts in last hour and goes to the first hour of the next day. In the second example, Polycarp has maximal rest from the 4-th to the 5-th hour. In the third example, Polycarp has maximal rest from the 3-rd to the 5-th hour. In the fourth example, Polycarp has no rest at all. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: * Employee A is the immediate manager of employee B * Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager. Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B. What is the minimum number of groups that must be formed? Input The first line contains integer n (1 ≀ n ≀ 2000) β€” the number of employees. The next n lines contain the integers pi (1 ≀ pi ≀ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi β‰  i). Also, there will be no managerial cycles. Output Print a single integer denoting the minimum number of groups that will be formed in the party. Examples Input 5 -1 1 2 1 -1 Output 3 Note For the first example, three groups are sufficient, for example: * Employee 1 * Employees 2 and 4 * Employees 3 and 5 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have a given integer n. Find the number of ways to fill all 3 Γ— n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap. <image> This picture describes when n = 4. The left one is the shape and the right one is 3 Γ— n tiles. Input The only line contains one integer n (1 ≀ n ≀ 60) β€” the length. Output Print the number of ways to fill. Examples Input 4 Output 4 Input 1 Output 0 Note In the first example, there are 4 possible cases of filling. In the second example, you cannot fill the shapes in 3 Γ— 1 tiles. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t. You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasing? Input The first line of the input contains two integer numbers n and d (2 ≀ n ≀ 2000, 1 ≀ d ≀ 106). The second line contains space separated sequence b0, b1, ..., bn - 1 (1 ≀ bi ≀ 106). Output Output the minimal number of moves needed to make the sequence increasing. Examples Input 4 2 1 3 3 2 Output 3 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something! You have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them to the order you chose: * The x\% of the price of each the a-th sold ticket (a-th, 2a-th, 3a-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources. * The y\% of the price of each the b-th sold ticket (b-th, 2b-th, 3b-th and so on) in the order you chose is aimed for pollution abatement. If the ticket is in both programs then the (x + y) \% are used for environmental activities. Also, it's known that all prices are multiples of 100, so there is no need in any rounding. For example, if you'd like to sell tickets with prices [400, 100, 300, 200] and the cinema pays 10\% of each 2-nd sold ticket and 20\% of each 3-rd sold ticket, then arranging them in order [100, 200, 300, 400] will lead to contribution equal to 100 β‹… 0 + 200 β‹… 0.1 + 300 β‹… 0.2 + 400 β‹… 0.1 = 120. But arranging them in order [100, 300, 400, 200] will lead to 100 β‹… 0 + 300 β‹… 0.1 + 400 β‹… 0.2 + 200 β‹… 0.1 = 130. Nature can't wait, so you decided to change the order of tickets in such a way, so that the total contribution to programs will reach at least k in minimum number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least k. Input The first line contains a single integer q (1 ≀ q ≀ 100) β€” the number of independent queries. Each query consists of 5 lines. The first line of each query contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of tickets. The second line contains n integers p_1, p_2, ..., p_n (100 ≀ p_i ≀ 10^9, p_i mod 100 = 0) β€” the corresponding prices of tickets. The third line contains two integers x and a (1 ≀ x ≀ 100, x + y ≀ 100, 1 ≀ a ≀ n) β€” the parameters of the first program. The fourth line contains two integers y and b (1 ≀ y ≀ 100, x + y ≀ 100, 1 ≀ b ≀ n) β€” the parameters of the second program. The fifth line contains single integer k (1 ≀ k ≀ 10^{14}) β€” the required total contribution. It's guaranteed that the total number of tickets per test doesn't exceed 2 β‹… 10^5. Output Print q integers β€” one per query. For each query, print the minimum number of tickets you need to sell to make the total ecological contribution of at least k if you can sell tickets in any order. If the total contribution can not be achieved selling all the tickets, print -1. Example Input 4 1 100 50 1 49 1 100 8 100 200 100 200 100 200 100 100 10 2 15 3 107 3 1000000000 1000000000 1000000000 50 1 50 1 3000000000 5 200 100 100 100 100 69 5 31 2 90 Output -1 6 3 4 Note In the first query the total contribution is equal to 50 + 49 = 99 < 100, so it's impossible to gather enough money. In the second query you can rearrange tickets in a following way: [100, 100, 200, 200, 100, 200, 100, 100] and the total contribution from the first 6 tickets is equal to 100 β‹… 0 + 100 β‹… 0.1 + 200 β‹… 0.15 + 200 β‹… 0.1 + 100 β‹… 0 + 200 β‹… 0.25 = 10 + 30 + 20 + 50 = 110. In the third query the full price of each ticket goes to the environmental activities. In the fourth query you can rearrange tickets as [100, 200, 100, 100, 100] and the total contribution from the first 4 tickets is 100 β‹… 0 + 200 β‹… 0.31 + 100 β‹… 0 + 100 β‹… 0.31 = 62 + 31 = 93. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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. You may perform any number of operations on them (possibly zero). During each operation you should choose any positive integer x and set a := a - x, b := b - 2x or a := a - 2x, b := b - x. Note that you may choose different values of x in different operations. Is it possible to make a and b equal to 0 simultaneously? Your program should answer t independent test cases. Input The first line contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then the test cases follow, each test case is represented by one line containing two integers a and b for this test case (0 ≀ a, b ≀ 10^9). Output For each test case print the answer to it β€” YES if it is possible to make a and b equal to 0 simultaneously, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). Example Input 3 6 9 1 1 1 2 Output YES NO YES Note In the first test case of the example two operations can be used to make both a and b equal to zero: 1. choose x = 4 and set a := a - x, b := b - 2x. Then a = 6 - 4 = 2, b = 9 - 8 = 1; 2. choose x = 1 and set a := a - 2x, b := b - x. Then a = 2 - 2 = 0, b = 1 - 1 = 0. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This is the hard version of this problem. The only difference is the constraint on k β€” the number of gifts in the offer. In this version: 2 ≀ k ≀ n. Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky β€” today the offer "k of goods for the price of one" is held in store. Using this offer, Vasya can buy exactly k of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has. More formally, for each good, its price is determined by a_i β€” the number of coins it costs. Initially, Vasya has p coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: * Vasya can buy one good with the index i if he currently has enough coins (i.e p β‰₯ a_i). After buying this good, the number of Vasya's coins will decrease by a_i, (i.e it becomes p := p - a_i). * Vasya can buy a good with the index i, and also choose exactly k-1 goods, the price of which does not exceed a_i, if he currently has enough coins (i.e p β‰₯ a_i). Thus, he buys all these k goods, and his number of coins decreases by a_i (i.e it becomes p := p - a_i). Please note that each good can be bought no more than once. For example, if the store now has n=5 goods worth a_1=2, a_2=4, a_3=3, a_4=5, a_5=7, respectively, k=2, and Vasya has 6 coins, then he can buy 3 goods. A good with the index 1 will be bought by Vasya without using the offer and he will pay 2 coins. Goods with the indices 2 and 3 Vasya will buy using the offer and he will pay 4 coins. It can be proved that Vasya can not buy more goods with six coins. Help Vasya to find out the maximum number of goods he can buy. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases in the test. The next lines contain a description of t test cases. The first line of each test case contains three integers n, p, k (2 ≀ n ≀ 2 β‹… 10^5, 1 ≀ p ≀ 2β‹…10^9, 2 ≀ k ≀ n) β€” the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them. The second line of each test case contains n integers a_i (1 ≀ a_i ≀ 10^4) β€” the prices of goods. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case in a separate line print one integer m β€” the maximum number of goods that Vasya can buy. Example Input 8 5 6 2 2 4 3 5 7 5 11 2 2 4 3 5 7 3 2 3 4 2 6 5 2 3 10 1 3 9 2 2 10000 2 10000 10000 2 9999 2 10000 10000 4 6 4 3 2 3 2 5 5 3 1 2 2 1 2 Output 3 4 1 1 2 0 4 5 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a permutation p_1, p_2, …, p_n of integers from 1 to n and an integer k, such that 1 ≀ k ≀ n. A permutation means that every number from 1 to n is contained in p exactly once. Let's consider all partitions of this permutation into k disjoint segments. Formally, a partition is a set of segments \{[l_1, r_1], [l_2, r_2], …, [l_k, r_k]\}, such that: * 1 ≀ l_i ≀ r_i ≀ n for all 1 ≀ i ≀ k; * For all 1 ≀ j ≀ n there exists exactly one segment [l_i, r_i], such that l_i ≀ j ≀ r_i. Two partitions are different if there exists a segment that lies in one partition but not the other. Let's calculate the partition value, defined as βˆ‘_{i=1}^{k} {max_{l_i ≀ j ≀ r_i} {p_j}}, for all possible partitions of the permutation into k disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by 998 244 353. Input The first line contains two integers, n and k (1 ≀ k ≀ n ≀ 200 000) β€” the size of the given permutation and the number of segments in a partition. The second line contains n different integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) β€” the given permutation. Output Print two integers β€” the maximum possible partition value over all partitions of the permutation into k disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo 998 244 353. Please note that you should only find the second value modulo 998 244 353. Examples Input 3 2 2 1 3 Output 5 2 Input 5 5 2 1 5 3 4 Output 15 1 Input 7 3 2 7 3 1 5 4 6 Output 18 6 Note In the first test, for k = 2, there exists only two valid partitions: \{[1, 1], [2, 3]\} and \{[1, 2], [3, 3]\}. For each partition, the partition value is equal to 2 + 3 = 5. So, the maximum possible value is 5 and the number of partitions is 2. In the third test, for k = 3, the partitions with the maximum possible partition value are \{[1, 2], [3, 5], [6, 7]\}, \{[1, 3], [4, 5], [6, 7]\}, \{[1, 4], [5, 5], [6, 7]\}, \{[1, 2], [3, 6], [7, 7]\}, \{[1, 3], [4, 6], [7, 7]\}, \{[1, 4], [5, 6], [7, 7]\}. For all of them, the partition value is equal to 7 + 5 + 6 = 18. The partition \{[1, 2], [3, 4], [5, 7]\}, however, has the partition value 7 + 3 + 6 = 16. This is not the maximum possible value, so we don't count it. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows: <image> You start with n cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed? Input Each test consists of multiple test cases. The first line contains a single integer t (1≀ t≀ 1000) β€” the number of test cases. Next t lines contain descriptions of test cases. Each test case contains a single integer n (1≀ n≀ 10^9) β€” the number of cards. It is guaranteed that the sum of n over all test cases does not exceed 10^9. Output For each test case output a single integer β€” the number of pyramids you will have constructed in the end. Example Input 5 3 14 15 24 1 Output 1 2 1 3 0 Note In the first test, you construct a pyramid of height 1 with 2 cards. There is 1 card remaining, which is not enough to build a pyramid. In the second test, you build two pyramids, each of height 2, with no cards remaining. In the third test, you build one pyramid of height 3, with no cards remaining. In the fourth test, you build one pyramid of height 3 with 9 cards remaining. Then you build a pyramid of height 2 with 2 cards remaining. Then you build a final pyramid of height 1 with no cards remaining. In the fifth test, one card is not enough to build any pyramids. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a as follows: he writes all the substrings of length 2 of the string a in the order from left to right, and then joins them in the same order into the string b. For example, if Bob came up with the string a="abac", then all the substrings of length 2 of the string a are: "ab", "ba", "ac". Therefore, the string b="abbaac". You are given the string b. Help Alice to guess the string a that Bob came up with. It is guaranteed that b was built according to the algorithm given above. It can be proved that the answer to the problem is unique. Input The first line contains a single positive integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the test. Then t test cases follow. Each test case consists of one line in which the string b is written, consisting of lowercase English letters (2 ≀ |b| ≀ 100) β€” the string Bob came up with, where |b| is the length of the string b. It is guaranteed that b was built according to the algorithm given above. Output Output t answers to test cases. Each answer is the secret string a, consisting of lowercase English letters, that Bob came up with. Example Input 4 abbaac ac bccddaaf zzzzzzzzzz Output abac ac bcdaf zzzzzz Note The first test case is explained in the statement. In the second test case, Bob came up with the string a="ac", the string a has a length 2, so the string b is equal to the string a. In the third test case, Bob came up with the string a="bcdaf", substrings of length 2 of string a are: "bc", "cd", "da", "af", so the string b="bccddaaf". The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task. Recently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer x as nearly prime if it can be represented as p β‹… q, where 1 < p < q and p and q are prime numbers. For example, integers 6 and 10 are nearly primes (since 2 β‹… 3 = 6 and 2 β‹… 5 = 10), but integers 1, 3, 4, 16, 17 or 44 are not. Captain Flint guessed an integer n and asked you: can you represent it as the sum of 4 different positive integers where at least 3 of them should be nearly prime. Uncle Bogdan easily solved the task and joined the crew. Can you do the same? Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Next t lines contain test cases β€” one per line. The first and only line of each test case contains the single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number Flint guessed. Output For each test case print: * YES and 4 different positive integers such that at least 3 of them are nearly prime and their sum is equal to n (if there are multiple answers print any of them); * NO if there is no way to represent n as the sum of 4 different positive integers where at least 3 of them are nearly prime. You can print each character of YES or NO in any case. Example Input 7 7 23 31 36 44 100 258 Output NO NO YES 14 10 6 1 YES 5 6 10 15 YES 6 7 10 21 YES 2 10 33 55 YES 10 21 221 6 Note In the first and second test cases, it can be proven that there are no four different positive integers such that at least three of them are nearly prime. In the third test case, n=31=2 β‹… 7 + 2 β‹… 5 + 2 β‹… 3 + 1: integers 14, 10, 6 are nearly prime. In the fourth test case, n=36=5 + 2 β‹… 3 + 2 β‹… 5 + 3 β‹… 5: integers 6, 10, 15 are nearly prime. In the fifth test case, n=44=2 β‹… 3 + 7 + 2 β‹… 5 + 3 β‹… 7: integers 6, 10, 21 are nearly prime. In the sixth test case, n=100=2 + 2 β‹… 5 + 3 β‹… 11 + 5 β‹… 11: integers 10, 33, 55 are nearly prime. In the seventh test case, n=258=2 β‹… 5 + 3 β‹… 7 + 13 β‹… 17 + 2 β‹… 3: integers 10, 21, 221, 6 are nearly prime. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot had a major argument with the Fairy Godmother (there were rumors that the argument occurred after the general spoke badly of the Godmother's flying techniques. That seemed to hurt the Fairy Godmother very deeply). As the result of the argument, the Godmother put a rather strange curse upon the general. It sounded all complicated and quite harmless: "If the squared distance between some two soldiers equals to 5, then those soldiers will conflict with each other!" The drill exercises are held on a rectangular n Γ— m field, split into nm square 1 Γ— 1 segments for each soldier. Thus, the square of the distance between the soldiers that stand on squares (x1, y1) and (x2, y2) equals exactly (x1 - x2)2 + (y1 - y2)2. Now not all nm squad soldiers can participate in the drill exercises as it was before the Fairy Godmother's curse. Unless, of course, the general wants the soldiers to fight with each other or even worse... For example, if he puts a soldier in the square (2, 2), then he cannot put soldiers in the squares (1, 4), (3, 4), (4, 1) and (4, 3) β€” each of them will conflict with the soldier in the square (2, 2). Your task is to help the general. You are given the size of the drill exercise field. You are asked to calculate the maximum number of soldiers that can be simultaneously positioned on this field, so that no two soldiers fall under the Fairy Godmother's curse. Input The single line contains space-separated integers n and m (1 ≀ n, m ≀ 1000) that represent the size of the drill exercise field. Output Print the desired maximum number of warriors. Examples Input 2 4 Output 4 Input 3 4 Output 6 Note In the first sample test Sir Lancelot can place his 4 soldiers on the 2 Γ— 4 court as follows (the soldiers' locations are marked with gray circles on the scheme): <image> In the second sample test he can place 6 soldiers on the 3 Γ— 4 site in the following manner: <image> The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 + 1 cities, numbered from 0 to n. n roads connect these cities, the i-th road connects cities i - 1 and i (i ∈ [1, n]). Each road has a direction. The directions are given by a string of n characters such that each character is either L or R. If the i-th character is L, it means that the i-th road initially goes from the city i to the city i - 1; otherwise it goes from the city i - 1 to the city i. A traveler would like to visit as many cities of this country as possible. Initially, they will choose some city to start their journey from. Each day, the traveler must go from the city where they currently are to a neighboring city using one of the roads, and they can go along a road only if it is directed in the same direction they are going; i. e., if a road is directed from city i to the city i + 1, it is possible to travel from i to i + 1, but not from i + 1 to i. After the traveler moves to a neighboring city, all roads change their directions to the opposite ones. If the traveler cannot go from their current city to a neighboring city, their journey ends; it is also possible to end the journey whenever the traveler wants to. The goal of the traveler is to visit as many different cities as possible (they can visit a city multiple times, but only the first visit is counted). For each city i, calculate the maximum number of different cities the traveler can visit during exactly one journey if they start in the city i. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Each test case consists of two lines. The first line contains one integer n (1 ≀ n ≀ 3 β‹… 10^5). The second line contains the string s consisting of exactly n characters, each character is either L or R. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print n + 1 integers. The i-th integer should be equal to the maximum number of different cities the traveler can visit during one journey if this journey starts in the i-th city. Example Input 2 6 LRRRLL 3 LRL Output 1 3 2 3 1 3 2 1 4 1 4 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array. More formally, given a suffix array of length n and having an alphabet size k, count the number of strings that produce such a suffix array. Let s be a string of length n. Then the i-th suffix of s is the substring s[i … n-1]. A suffix array is the array of integers that represent the starting indexes of all the suffixes of a given string, after the suffixes are sorted in the lexicographic order. For example, the suffix array of oolimry is [3,2,4,1,0,5,6] as the array of sorted suffixes is [imry,limry,mry,olimry,oolimry,ry,y]. A string x is lexicographically smaller than string y, if either x is a prefix of y (and xβ‰  y), or there exists such i that x_i < y_i, and for any 1≀ j < i , x_j = y_j. Input The first line contain 2 integers n and k (1 ≀ n ≀ 200000,1 ≀ k ≀ 200000) β€” the length of the suffix array and the alphabet size respectively. The second line contains n integers s_0, s_1, s_2, …, s_{n-1} (0 ≀ s_i ≀ n-1) where s_i is the i-th element of the suffix array i.e. the starting position of the i-th lexicographically smallest suffix. It is guaranteed that for all 0 ≀ i< j ≀ n-1, s_i β‰  s_j. Output Print how many strings produce such a suffix array. Since the number can be very large, print the answer modulo 998244353. Examples Input 3 2 0 2 1 Output 1 Input 5 1 0 1 2 3 4 Output 0 Input 6 200000 0 1 2 3 4 5 Output 822243495 Input 7 6 3 2 4 1 0 5 6 Output 36 Note In the first test case, "abb" is the only possible solution. In the second test case, it can be easily shown no possible strings exist as all the letters have to be equal. In the fourth test case, one possible string is "ddbacef". Please remember to print your answers modulo 998244353. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory). Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name β€” a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory β€” the one that contains the given directory. It is denoted as "..". The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. Β«..Β» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one. The command pwd should display the absolute path to the current directory. This path must not contain "..". Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory. Input The first line of the input data contains the single integer n (1 ≀ n ≀ 50) β€” the number of commands. Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter. The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive. Directories in the file system can have the same names. Output For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots. Examples Input 7 pwd cd /home/vasya pwd cd .. pwd cd vasya/../petya pwd Output / /home/vasya/ /home/ /home/petya/ Input 4 cd /a/b pwd cd ../a/b pwd Output /a/b/ /a/a/b/ The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again. The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): <image> Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut. To understand the problem better please read the notes to the test samples. Input The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise. Output Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled. Examples Input -++- Output Yes Input +- Output No Input ++ Output Yes Input - Output No Note The first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses. In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: <image> In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: <image> In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself: <image> The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much. A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at volume v (1 ≀ v ≀ ai; v is an integer) both on the piano and the guitar. They should retain harmony, so the total volume with which the i-th note was played on the guitar and the piano must equal bi. If Dima and Inna cannot play a note by the described rules, they skip it and Sereja's joy drops by 1. But if Inna and Dima play the i-th note at volumes xi and yi (xi + yi = bi) correspondingly, Sereja's joy rises by xiΒ·yi. Sereja has just returned home from the university and his current joy is 0. Help Dima and Inna play the song so as to maximize Sereja's total joy after listening to the whole song! Input The first line of the input contains integer n (1 ≀ n ≀ 105) β€” the number of notes in the song. The second line contains n integers ai (1 ≀ ai ≀ 106). The third line contains n integers bi (1 ≀ bi ≀ 106). Output In a single line print an integer β€” the maximum possible joy Sereja feels after he listens to a song. Examples Input 3 1 1 2 2 2 3 Output 4 Input 1 2 5 Output -1 Note In the first sample, Dima and Inna play the first two notes at volume 1 (1 + 1 = 2, the condition holds), they should play the last note at volumes 1 and 2. Sereja's total joy equals: 1Β·1 + 1Β·1 + 1Β·2 = 4. In the second sample, there is no such pair (x, y), that 1 ≀ x, y ≀ 2, x + y = 5, so Dima and Inna skip a note. Sereja's total joy equals -1. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building. The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on. Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left. Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan! Input The first line contains two integers, n and k (1 ≀ k ≀ n ≀ 100) β€” the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'. Output In t lines, print the actions the programmers need to make. In the i-th line print: * "LEFT" (without the quotes), if the i-th action was "move the ladder to the left"; * "RIGHT" (without the quotes), if the i-th action was "move the ladder to the right"; * "PRINT x" (without the quotes), if the i-th action was to "go up the ladder, paint character x, go down the ladder". The painting time (variable t) must be minimum possible. If there are multiple optimal painting plans, you can print any of them. Examples Input 2 2 R1 Output PRINT 1 LEFT PRINT R Input 2 1 R1 Output PRINT R RIGHT PRINT 1 Input 6 4 GO?GO! Output RIGHT RIGHT PRINT ! LEFT PRINT O LEFT PRINT G LEFT PRINT ? LEFT PRINT O LEFT PRINT G Note Note that the ladder cannot be shifted by less than one meter. The ladder can only stand in front of some square of the poster. For example, you cannot shift a ladder by half a meter and position it between two squares. Then go up and paint the first character and the second character. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper. Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct. Input The first line contains integer n (1 ≀ n ≀ 2Β·105), the number of three-letter substrings Tanya got. Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit. Output If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO". If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option. Examples Input 5 aca aba aba cab bac Output YES abacaba Input 4 abc bCb cb1 b13 Output NO Input 7 aaa aaa aaa aaa aaa aaa aaa Output YES aaaaaaaaa The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 GCD table G of size n Γ— n for an array of positive integers a of length n is defined by formula <image> Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as <image>. For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: <image> Given all the numbers of the GCD table G, restore array a. Input The first line contains number n (1 ≀ n ≀ 500) β€” the length of array a. The second line contains n2 space-separated numbers β€” the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a. Output In the single line print n positive integers β€” the elements of array a. If there are multiple possible solutions, you are allowed to print any of them. Examples Input 4 2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2 Output 4 3 6 2 Input 1 42 Output 42 Input 2 1 1 1 1 Output 1 1 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site. He has suggestions to work on n distinct projects. Mikhail has already evaluated that the participation in the i-th project will increase his experience by ai per day and bring bi dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time. Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true. For example, suppose Mikhail is suggested to work on three projects and a1 = 6, b1 = 2, a2 = 1, b2 = 3, a3 = 2, b3 = 6. Also, p = 20 and q = 20. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, a1Β·2.5 + a2Β·0 + a3Β·2.5 = 6Β·2.5 + 1Β·0 + 2Β·2.5 = 20 and b1Β·2.5 + b2Β·0 + b3Β·2.5 = 2Β·2.5 + 3Β·0 + 6Β·2.5 = 20. Input The first line of the input contains three integers n, p and q (1 ≀ n ≀ 100 000, 1 ≀ p, q ≀ 1 000 000) β€” the number of projects and the required number of experience and money. Each of the next n lines contains two integers ai and bi (1 ≀ ai, bi ≀ 1 000 000) β€” the daily increase in experience and daily income for working on the i-th project. Output Print a real value β€” the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 20 20 6 2 1 3 2 6 Output 5.000000000000000 Input 4 1 1 2 3 3 2 2 3 3 2 Output 0.400000000000000 Note First sample corresponds to the example in the problem statement. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent. For each photo it is known which orientation is intended for it β€” horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo. Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos. Help Vasya find the maximum number of photos he is able to watch during T seconds. Input The first line of the input contains 4 integers n, a, b, T (1 ≀ n ≀ 5Β·105, 1 ≀ a, b ≀ 1000, 1 ≀ T ≀ 109) β€” the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo. Second line of the input contains a string of length n containing symbols 'w' and 'h'. If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation. If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation. Output Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds. Examples Input 4 2 3 10 wwhw Output 2 Input 5 2 4 13 hhwhh Output 4 Input 5 2 4 1000 hhwhh Output 5 Input 3 1 100 10 whw Output 0 Note In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds. Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato. Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens: 1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece. 2. Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed. Input The first line of the input contains integers n, h and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ h ≀ 109) β€” the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1 ≀ ai ≀ h) β€” the heights of the pieces. Output Print a single integer β€” the number of seconds required to smash all the potatoes following the process described in the problem statement. Examples Input 5 6 3 5 4 3 2 1 Output 5 Input 5 6 3 5 5 5 5 5 Output 10 Input 5 6 3 1 2 1 1 1 Output 2 Note Consider the first sample. 1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside. 2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining. 3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second. 4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3. 5. During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds. In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length. The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell. Input The first line contains two separated by a space integer numbers n, m (1 ≀ n, m ≀ 100) β€” the length and the width of the office-room, and c character β€” the President's desk colour. The following n lines contain m characters each β€” the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters. Output Print the only number β€” the amount of President's deputies. Examples Input 3 4 R G.B. .RR. TTT. Output 2 Input 3 3 Z ... .H. ..Z Output 0 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≀ i ≀ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position. Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that. Input The first line of the input contains three integers n, k and x (1 ≀ n, k ≀ 200 000, 1 ≀ x ≀ 109) β€” the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an (<image>) β€” the elements of the array found by Maxim. Output Print n integers b1, b2, ..., bn in the only line β€” the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 ≀ i ≀ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them. Examples Input 5 3 1 5 4 3 5 2 Output 5 4 3 5 -1 Input 5 3 1 5 4 3 5 5 Output 5 4 0 5 5 Input 5 3 1 5 4 4 5 5 Output 5 1 4 5 5 Input 3 2 7 5 4 2 Output 5 11 -5 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step. The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps. Please help Chloe to solve the problem! Input The only line contains two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 2n - 1). Output Print single integer β€” the integer at the k-th position in the obtained sequence. Examples Input 3 2 Output 2 Input 4 8 Output 4 Note In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2. In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words. He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on. Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time. After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations. After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help. Input The first line of input contains three integers n, m and q (2 ≀ n ≀ 105, 1 ≀ m, q ≀ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations. The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary. Then m lines follow, each of them contains an integer t (1 ≀ t ≀ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi. Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered. All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different. Output First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes). After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3. See the samples for better understanding. Examples Input 3 3 4 hate love like 1 love like 2 love hate 1 hate like love like love hate like hate hate like Output YES YES NO 1 2 2 2 Input 8 6 5 hi welcome hello ihateyou goaway dog cat rat 1 hi welcome 1 ihateyou goaway 2 hello ihateyou 2 hi goaway 2 hi hello 1 hi hello dog cat dog hi hi hello ihateyou goaway welcome ihateyou Output YES YES YES YES NO YES 3 3 1 1 2 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 flag of Berland is such rectangular field n Γ— m that satisfies following conditions: * Flag consists of three colors which correspond to letters 'R', 'G' and 'B'. * Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color. * Each color should be used in exactly one stripe. You are given a field n Γ— m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes). Input The first line contains two integer numbers n and m (1 ≀ n, m ≀ 100) β€” the sizes of the field. Each of the following n lines consisting of m characters 'R', 'G' and 'B' β€” the description of the field. Output Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes). Examples Input 6 5 RRRRR RRRRR BBBBB BBBBB GGGGG GGGGG Output YES Input 4 3 BRG BRG BRG BRG Output YES Input 6 7 RRRGGGG RRRGGGG RRRGGGG RRRBBBB RRRBBBB RRRBBBB Output NO Input 4 4 RRRR RRRR BBBB GGGG Output NO Note The field in the third example doesn't have three parralel stripes. Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β€” 2, 1 and 1. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sum of p rubles is charged from Arkady's mobile phone account every day in the morning. Among the following m days, there are n days when Arkady will top up the account: in the day di he will deposit ti rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following m days. Determine the number of days starting from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment (i. e. in evening). Initially the account's balance is zero rubles. Input The first line contains three integers n, p and m (1 ≀ n ≀ 100 000, 1 ≀ p ≀ 109, 1 ≀ m ≀ 109, n ≀ m) β€” the number of days Arkady will top up the account, the amount of the daily payment, and the number of days you should check. The i-th of the following n lines contains two integers di and ti (1 ≀ di ≀ m, 1 ≀ ti ≀ 109) β€” the index of the day when Arkady will make the i-th top up, and the amount he will deposit on this day. It is guaranteed that the indices of the days are distinct and are given in increasing order, i. e. di > di - 1 for all i from 2 to n. Output Print the number of days from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment. Examples Input 3 6 7 2 13 4 20 7 9 Output 3 Input 5 4 100 10 70 15 76 21 12 30 100 67 85 Output 26 Note In the first example the balance will change as following (remember, initially the balance is zero): 1. in the first day 6 rubles will be charged, the balance in the evening will be equal to - 6; 2. in the second day Arkady will deposit 13 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 1; 3. in the third day 6 rubles will be charged, the balance in the evening will be equal to - 5; 4. in the fourth day Arkady will deposit 20 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 9; 5. in the fifth day 6 rubles will be charged, the balance in the evening will be equal to 3; 6. in the sixth day 6 rubles will be charged, the balance in the evening will be equal to - 3; 7. in the seventh day Arkady will deposit 9 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 0. Thus, in the end of the first, third and sixth days the balance will be negative in the end of the day. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 decides to challenge Bob to a problem. She gives him a number. Bob can rearrange the digits of this number by applying pair-wise swaps between any 2 digits in the number as many times as he wants. Now Alice asks him to write down all the distinct numbers that he can form and sort them. Of these she wants him to tell her the 3^rd Smallest and the 3^rd Largest possible number(numerically). Now the number itself might be quite large having up to 10^5 digits and it is also known that the number will have only 1-9 as digits(Alice does not like 0 for some reason). Help Bob with this task! Input: First line contains T which is the number of test cases. T lines follow each containing an integer N . Output: For each input N, output one line containing the 3^rd Smallest Number and the 3^rd Largest number separated by a space. If it doesn't exist, instead print "Not possible!"(without the quotes) Constraints: 1 ≀ T ≀ 10 1 ≀ No \, of \, digits \, in \, N ≀ 10^5 Scoring: 1 ≀ T ≀ 10, 1 ≀ No \, of \, digits \, in \, N ≀ 10 (20 pts) 1 ≀ T ≀ 10, 10 ≀ No \, of \, digits \, in \, N ≀ 10^3 (30 pts) 1 ≀ T ≀ 10, 1000 ≀ No \, of \, digits \, in \, N ≀ 10^5 (50 pts) SAMPLE INPUT 3 123 4 1232 SAMPLE OUTPUT 213 231 Not possible! 1322 3122 Explanation Case 1: We can make these numbers from 123 {123,132,213,231,312,321}. Of these the 3rd from the front is 213 and from back is 231. Case 2: We can only make 4 from this. Hence it is not possible! Case 3: We can make 12 distinct numbers from this number. The smallest 3 are 1223, 1232, 1322. The largest 3 are 3221,3212,3122. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This problem of Oz is very straight forward. You are given N distinct prime integers i.e p1, p2,..., pN and an interval [L,R]. Calculate number of integers in this interval that are divisible by at least one of the given primes. Input : First line of input contain an integer T β€” the number of test cases. T tests follow. First line of each test case contain 3 integers β€” N, L, R. and the next line contains N distinct prime integers - p1, p2,..., pN. Output : For each test case output a single number β€” number of integers in [L,R], that are divisible by at least one of the given primes. Constraints : 1 ≀ T ≀ 10 1 ≀ N ≀ 10 1 < pi < 1000 where i=1,2..N 1 ≀ L ≀ R ≀ 10^18 SAMPLE INPUT 2 1 1 10 3 2 1 10 2 3 SAMPLE OUTPUT 3 7 Explanation For second sample : Numbers in the interval [1,10] which are divisible by at least one prime from (2,3) are as follow : 2, 3, 4, 6, 8, 9, 10 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 be given a set of distinct numbers. Your task is to find that even length subset which will give you a maximum value of P % (10^9 + 7). This value of P for a subset of length N is defined as below : P = (product of N/2 maximum values) / (product of N/2 minimum values) Now suppose we have a subset S = {A1 , A3 , A4 , A5} where A1 < A3 < A4 < A5 , then P = (A4 * A5) / (A1 * A3) Note : Subset should be of even length and should be non-empty and you have to output the maximum value of P % (10^9 + 7) i.e. that value which should be maximum after taking this mod. Input First line of the input will contian T (number of test cases). Then for every test case first line will contain N (size of the set) and the next line will contain N space separated integers (elements of the set). Output For every test case print the required maximum value. Constraints 1 ≀ T ≀ 5 2 ≀ N ≀ 16 1 ≀ S[i] ≀ 10^9 SAMPLE INPUT 2 2 2 4 3 2 4 8 SAMPLE OUTPUT 2 4 Explanation In the first test case the only subset of even length is { 2, 4} , so ans is 4/2 = 2. In the second test case the ans will be {2, 8} i.e. 8/2 = 4. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Campus Ambassador has organized a Coding Contest in his college. Contest has multiple rounds, in each round a participant may gain or lose few points. At the end, there is only one participant with the maximum points. In the course of the contest, the number of points is written in the line as "name points", where name is the participant's name and points is, the number of points is gained. If the point is negative, this means the participant has lost in the round. If two partcipants have the maximum number of points, then winners is the one who scored at least m points first. Intially each participant has 0 points. It's guranteed that at the end of the game at least one participant has a positive number of points. Input The first line contains an integer N, total number of rounds. Then follow N lines, containing information about the rounds in "name points" format in chronological order. Output Print the Name of the winner of the Contest. Constraints 1 ≀ N ≀ 1000 'name' is the string of lower case letter 1 ≀ |name| ≀ 32 -1000 ≀points ≀ 1000 SAMPLE INPUT 3 mini 3 rini 5 mini 2 SAMPLE OUTPUT rini Explanation After the contest both rini and mini have scored same points that is 5 , but rini scored 5 points first, hence the winner. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Do you remember the game of Snakes and Ladders ? We have removed all the snakes from the board. However to compensate for the loss of trouble, we have enlarged the board from a maximum limit (Target Square) of 100 to a maximum limit (Target Square) of N β‰₯ 100, N being a perfect square. Rani has a match with Nandu on this new kind of board next week. Now Rani is practising alone on the board. Suddenly Rani starts wondering : "Suppose I have total control over both my dice (each die being a standard 1-6 die) and I am the only player playing all the turns such that in each turn I throw both the dice, what is the minimum number of turns in which I can reach the Target Square N ? " Given the configuration of the board ie. given all the information about the location of Ladders on the board, find the answer to Rani's question. Note (to player) : You start from Square Number 1. If you reach a square which contains the base of a ladder, you have to climb up that ladder in the same turn itself (it is compulsory to climb the ladder). Note that you can only climb up ladders, not climb down. Say you are at square number N-2. The only way you can complete the game is by getting a 2 by throwing both your dice. If you throw a 4 or a 5 or anything else, your turn goes wasted. Input : First line consisits of T denoting the number of test cases. The first line of each test case consists of 2 space-separated integers N an L denoting the Target Square and number of ladders respectively. The next L lines are such that each line consists of 2-space separated integers B and U denoting the squares where the bottom and upper parts of each ladder lie. Ouptut: Print a single integer per test case on a new line, the answer to Rani's question. Constraints : 1 ≀ T ≀ 3 100 ≀ N ≀ 160000, N being a perfect square 0 ≀ L ≀ SquareRoot(N) 1 ≀ B<U ≀ N Author : Shreyans Tester : Sandeep (By IIT Kgp HackerEarth Programming Club) SAMPLE INPUT 1 100 1 5 97 SAMPLE OUTPUT 2 Explanation In the first turn, Rani will drop 4 using both her dice. So, 1 -> 5. Now there is a ladder going from 5 to 97. So, now Rani's piece will climb the ladder and reach 97. In her second turn, Rani will drop a 3 using both her dice. So, 97 -> 100. Hence Rani reaches the Target Square in 2 turns. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given is an integer S. Find how many sequences there are whose terms are all integers greater than or equal to 3, and whose sum is equal to S. The answer can be very large, so output it modulo 10^9 + 7. Constraints * 1 \leq S \leq 2000 * All values in input are integers. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input 7 Output 3 Input 2 Output 0 Input 1729 Output 294867501 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 bracket sequence is a string that is one of the following: 1. An empty string; 2. The concatenation of `(`, A, and `)` in this order, for some bracket sequence A ; 3. The concatenation of A and B in this order, for some non-empty bracket sequences A and B / Given are N strings S_i. Can a bracket sequence be formed by concatenating all the N strings in some order? Constraints * 1 \leq N \leq 10^6 * The total length of the strings S_i is at most 10^6. * S_i is a non-empty string consisting of `(` and `)`. Input Input is given from Standard Input in the following format: N S_1 : S_N Output If a bracket sequence can be formed by concatenating all the N strings in some order, print `Yes`; otherwise, print `No`. Examples Input 2 ) (() Output Yes Input 2 )( () Output No Input 4 ((())) (((((( )))))) ()()() Output Yes Input 3 ((( ) ) Output No The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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). Examples Input 1 1000000000 Output 999999993 Input 2 5 8 Output 124 Input 5 52 67 72 25 79 Output 269312 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 two bottles for holding water. Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water. Bottle 2 contains C milliliters of water. We will transfer water from Bottle 2 to Bottle 1 as much as possible. How much amount of water will remain in Bottle 2? Constraints * All values in input are integers. * 1 \leq B \leq A \leq 20 * 1 \leq C \leq 20 Input Input is given from Standard Input in the following format: A B C Output Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2. Examples Input 6 4 3 Output 1 Input 8 3 9 Output 4 Input 12 3 7 Output 0 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 of length N consisting of `A`, `C`, `G` and `T`. Answer the following Q queries: * Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does `AC` occurs as a substring? Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * S is a string of length N. * Each character in S is `A`, `C`, `G` or `T`. * 1 \leq l_i < r_i \leq N Input Input is given from Standard Input in the following format: N Q S l_1 r_1 : l_Q r_Q Output Print Q lines. The i-th line should contain the answer to the i-th query. Example Input 8 3 ACACTACG 3 7 2 3 1 8 Output 2 0 3 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 programming, hexadecimal notation is often used. In hexadecimal notation, besides the ten digits 0, 1, ..., 9, the six letters `A`, `B`, `C`, `D`, `E` and `F` are used to represent the values 10, 11, 12, 13, 14 and 15, respectively. In this problem, you are given two letters X and Y. Each X and Y is `A`, `B`, `C`, `D`, `E` or `F`. When X and Y are seen as hexadecimal numbers, which is larger? Constraints * Each X and Y is `A`, `B`, `C`, `D`, `E` or `F`. Input Input is given from Standard Input in the following format: X Y Output If X is smaller, print `<`; if Y is smaller, print `>`; if they are equal, print `=`. Examples Input A B Output < Input E C Output > Input F F Output = The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sequence of length N, a = {a_1, a_2, …, a_N}, and an integer K. a has N(N+1)/2 non-empty contiguous subsequences, {a_l, a_{l+1}, …, a_r} (1 ≀ l ≀ r ≀ N). Among them, how many have an arithmetic mean that is greater than or equal to K? Constraints * All input values are integers. * 1 ≀ N ≀ 2 \times 10^5 * 1 ≀ K ≀ 10^9 * 1 ≀ a_i ≀ 10^9 Input Input is given from Standard Input in the following format: N K a_1 a_2 : a_N Output Print the number of the non-empty contiguous subsequences with an arithmetic mean that is greater than or equal to K. Examples Input 3 6 7 5 7 Output 5 Input 1 2 1 Output 0 Input 7 26 10 20 30 40 30 20 10 Output 13 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 pinholes on the xy-plane. The i-th pinhole is located at (x_i,y_i). We will denote the Manhattan distance between the i-th and j-th pinholes as d(i,j)(=|x_i-x_j|+|y_i-y_j|). You have a peculiar pair of compasses, called Manhattan Compass. This instrument always points at two of the pinholes. The two legs of the compass are indistinguishable, thus we do not distinguish the following two states: the state where the compass points at the p-th and q-th pinholes, and the state where it points at the q-th and p-th pinholes. When the compass points at the p-th and q-th pinholes and d(p,q)=d(p,r), one of the legs can be moved so that the compass will point at the p-th and r-th pinholes. Initially, the compass points at the a-th and b-th pinholes. Find the number of the pairs of pinholes that can be pointed by the compass. Constraints * 2≦N≦10^5 * 1≦x_i, y_i≦10^9 * 1≦a < b≦N * When i β‰  j, (x_i, y_i) β‰  (x_j, y_j) * x_i and y_i are integers. Input The input is given from Standard Input in the following format: N a b x_1 y_1 : x_N y_N Output Print the number of the pairs of pinholes that can be pointed by the compass. Examples Input 5 1 2 1 1 4 3 6 1 5 5 4 8 Output 4 Input 6 2 3 1 3 5 3 3 5 8 4 4 7 2 5 Output 4 Input 8 1 2 1 5 4 3 8 2 4 7 8 8 3 3 6 6 4 8 Output 7 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 got an integer sequence from his mother, as a birthday present. The sequence has N elements, and the i-th of them is i. Snuke performs the following Q operations on this sequence. The i-th operation, described by a parameter q_i, is as follows: * Take the first q_i elements from the sequence obtained by concatenating infinitely many copy of the current sequence, then replace the current sequence with those q_i elements. After these Q operations, find how many times each of the integers 1 through N appears in the final sequence. Constraints * 1 ≦ N ≦ 10^5 * 0 ≦ Q ≦ 10^5 * 1 ≦ q_i ≦ 10^{18} * All input values are integers. Input The input is given from Standard Input in the following format: N Q q_1 : q_Q Output Print N lines. The i-th line (1 ≦ i ≦ N) should contain the number of times integer i appears in the final sequence after the Q operations. Examples Input 5 3 6 4 11 Output 3 3 3 2 0 Input 10 10 9 13 18 8 10 10 9 19 22 27 Output 7 4 4 3 3 2 2 2 0 0 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. An extension of a complex number is called a quaternion. It is a convenient number that can be used to control the arm of a robot because it is convenient for expressing the rotation of an object. Quaternions are $ using four real numbers $ x $, $ y $, $ z $, $ w $ and special numbers (extended imaginary numbers) $ i $, $ j $, $ k $. It is expressed as x + yi + zj + wk $. The sum of such quaternions is defined as: $ (x_1 + y_1 i + z_1 j + w_1 k) + (x_2 + y_2 i + z_2 j + w_2 k) = (x_1 + x_2) + (y_1 + y_2) i + (z_1 + z_2) j + (w_1 + w_2) k $ On the other hand, the product between 1, $ i $, $ j $, and $ k $ is given as follows. <image> This table represents the product $ AB $ of two special numbers $ A $ and $ B $. For example, the product $ ij $ of $ i $ and $ j $ is $ k $, and the product $ ji $ of $ j $ and $ i $ is $ -k $. The product of common quaternions is calculated to satisfy this relationship. For example, the product of two quaternions, $ 1 + 2i + 3j + 4k $ and $ 7 + 6i + 7j + 8k $, is calculated as follows: $ (1 + 2i + 3j + 4k) \ times (7 + 6i + 7j + 8k) = $ $ 7 + 6i + 7j + 8k $ $ + 14i + 12i ^ 2 + 14ij + 16ik $ $ + 21j + 18ji + 21j ^ 2 + 24jk $ $ + 28k + 24ki + 28kj + 32k ^ 2 $ By applying the table above $ = -58 + 16i + 36j + 32k $ It will be. Two quaternions ($ x_1 + y_1 i + z_1 j + w_1 k $) and ($) where the four coefficients $ x $, $ y $, $ z $, $ w $ are integers and not all zeros x_2 + y_2 i + z_2 j + w_2 k $), and the product is ($ x_3 + y_3 i + z_3 j + w_3 k $), $ x_3 $, $ y_3 $, $ z_3 $, $ Create a program that outputs w_3 $. input Given multiple datasets. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: $ n $ $ data_1 $ $ data_2 $ :: $ data_n $ The first line gives the number of pairs of quaternions to process $ n $ ($ n \ leq 10 $). The following $ n $ line is given the $ i $ th quaternion pair of information $ data_i $ in the following format: $ x_1 $ $ y_1 $ $ z_1 $ $ w_1 $ $ x_2 $ $ y_2 $ $ z_2 $ $ w_2 $ All coefficients given should be -1000 or more and 1000 or less. The number of datasets does not exceed 50. output Prints the product of a given set of quaternions for each dataset. Example Input 2 1 2 3 4 7 6 7 8 5 6 7 8 3 2 3 4 0 Output -58 16 36 32 -50 32 28 48 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Advanced Creative Mobile (ACM) has decided to develop a GUI application to be installed in a new portable computer. As shown in the figure below, the GUI has a nested structure in which it has one main panel, several panels are arranged on it, and some panels are arranged on top of those panels. .. All panels are rectangles or squares whose sides are parallel and perpendicular to the axes. <image> The application is designed to hold the nested structure of the panel in a tag structure. The tag structure that represents a panel has a list of tag values ​​and the tag structure of the panel that is placed on top of that panel. The tag value indicates the upper left coordinate (x1, y1) and the lower right coordinate (x2, y2) of the panel. The syntax rules for the tag structure are shown below. Here, the meanings of the symbols used to describe the syntax are defined as shown in the table below. "<", ">", "," And "/" are lexical elements. Symbol | Meaning --- | --- :: = | Define Repeat 0 or more times for the element enclosed by {} * | {and} Tag structure :: = Start tag Tag value {Tag structure} * End tag Start tag :: = <tag name> End tag :: = </ tag name> Tag name :: = string Tag value :: = integer, integer, integer, integer The tag name is a character string consisting of one or more characters indicating the name of the panel. The tag values ​​are four integers separated by commas, x1, y1, x2, y2, which indicate the coordinates of the panel, respectively. For example, the GUI shown in the above figure is described by the following tag structure (it spans two lines due to space, but the input is given in one line): <main> 10,10,190,150 <menu> 20,20,70,140 </ menu> <primary> 80,20,180,140 <text> 90,30,170,80 </ text> <button> 130,110,170,130 </ button> </ primary> </ main> In this GUI, when the user touches a point, the top panel at that point is selected (including the border). Your job is to create a program that reads the tag structure of the main panel and the list of touched points and outputs the following information. * Name of the selected panel * The number of panels placed directly above that panel (hereinafter referred to as the "number of children") The following may be assumed for the tag structure to be input. * There are no syntax errors in the tag structure. * The panel does not protrude from the panel containing it (hereinafter referred to as the "parent panel") and does not touch the boundaries. * Panels with the same parent panel do not overlap and do not touch. * There is no panel with the same name. Input The input consists of multiple datasets. Each dataset is given in the following format: n Tag structure x1 y1 x2 y2 .. .. .. xn yn n is an integer indicating the number of touched points. The tag structure is a one-line character string that does not include spaces. xi and yi represent the x-coordinate and y-coordinate of the point touched at the i-th (the coordinate axes are defined in the above figure). You can assume that n ≀ 100 and the length of the string in the tag structure ≀ 1000. Also, it may be assumed that the x-coordinate and y-coordinate given by the input are 0 or more and 10,000 or less. When n is 0, it is the end of input. Output For each dataset, print the panel name and the number of children in the order selected. Output each name and the number of children on one line, separated by one space. If nothing is selected (there is no panel at the touched point), output "OUT OF MAIN PANEL 1". Example Input 5 <main>10,10,190,150<menu>20,20,70,140</menu><primary>80,20,180,140</primary></main> 10 10 15 15 40 60 2 3 130 80 0 Output main 2 main 2 menu 0 OUT OF MAIN PANEL 1 primary 0 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 decimal representation of an integer can be transformed to another integer by rearranging the order of digits. Let us make a sequence using this fact. A non-negative integer a0 and the number of digits L are given first. Applying the following rules, we obtain ai+1 from ai. 1. Express the integer ai in decimal notation with L digits. Leading zeros are added if necessary. For example, the decimal notation with six digits of the number 2012 is 002012. 2. Rearranging the digits, find the largest possible integer and the smallest possible integer; In the example above, the largest possible integer is 221000 and the smallest is 000122 = 122. 3. A new integer ai+1 is obtained by subtracting the smallest possible integer from the largest. In the example above, we obtain 220878 subtracting 122 from 221000. When you repeat this calculation, you will get a sequence of integers a0 , a1 , a2 , ... . For example, starting with the integer 83268 and with the number of digits 6, you will get the following sequence of integers a0 , a1 , a2 , ... . > a0 = 083268 > a1 = 886320 βˆ’ 023688 = 862632 > a2 = 866322 βˆ’ 223668 = 642654 > a3 = 665442 βˆ’ 244566 = 420876 > a4 = 876420 βˆ’ 024678 = 851742 > a5 = 875421 βˆ’ 124578 = 750843 > a6 = 875430 βˆ’ 034578 = 840852 > a7 = 885420 βˆ’ 024588 = 860832 > a8 = 886320 βˆ’ 023688 = 862632 > … > Because the number of digits to express integers is fixed, you will encounter occurrences of the same integer in the sequence a0 , a1 , a2 , ... eventually. Therefore you can always find a pair of i and j that satisfies the condition ai = aj (i > j ). In the example above, the pair (i = 8, j = 1) satisfies the condition because a8 = a1 = 862632. Write a program that, given an initial integer a0 and a number of digits L, finds the smallest i that satisfies the condition ai = aj (i > j ). Input The input consists of multiple datasets. A dataset is a line containing two integers a0 and L separated by a space. a0 and L represent the initial integer of the sequence and the number of digits, respectively, where 1 ≀ L ≀ 6 and 0 ≀ a0 < 10L . The end of the input is indicated by a line containing two zeros; it is not a dataset. Output For each dataset, find the smallest number i that satisfies the condition ai = aj (i > j ) and print a line containing three integers, j , ai and i βˆ’ j. Numbers should be separated by a space. Leading zeros should be suppressed. Output lines should not contain extra characters. You can assume that the above i is not greater than 20. Sample Input 2012 4 83268 6 1112 4 0 1 99 2 0 0 Output for the Sample Input 3 6174 1 1 862632 7 5 6174 1 0 0 1 1 0 1 Example Input 2012 4 83268 6 1112 4 0 1 99 2 0 0 Output 3 6174 1 1 862632 7 5 6174 1 0 0 1 1 0 1 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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. Jimbo, an applied mathematician, needs to calculate matrices all day for solving his own problems. In his laboratory, he uses an excellent application program for manipulating matrix expressions, however, he cannot use it outside his laboratory because the software consumes much of resources. He wants to manipulate matrices outside, so he needs a small program similar to the excellent application for his handheld computer. Your job is to provide him a program that computes expressions of matrices. Expressions of matrices are described in a simple language. Its syntax is shown in Table J.1. Note that even a space and a newline have meaningful roles in the syntax. <image> The start symbol of this syntax is program that is defined as a sequence of assignments in Table J.1. Each assignment has a variable on the left hand side of an equal symbol ("=") and an expression of matrices on the right hand side followed by a period and a newline (NL). It denotes an assignment of the value of the expression to the variable. The variable (var in Table J.1) is indicated by an uppercase Roman letter. The value of the expression (expr) is a matrix or a scalar, whose elements are integers. Here, a scalar integer and a 1 Γ— 1 matrix whose only element is the same integer can be used interchangeably. An expression is one or more terms connected by "+" or "-" symbols. A term is one or more factors connected by "*" symbol. These operators ("+", "-", "*") are left associative. A factor is either a primary expression (primary) or a "-" symbol followed by a factor. This unary operator "-" is right associative. The meaning of operators are the same as those in the ordinary arithmetic on matrices: Denoting matrices by A and B, A + B, A - B, A * B, and -A are defined as the matrix sum, difference, product, and negation. The sizes of A and B should be the same for addition and subtraction. The number of columns of A and the number of rows of B should be the same for multiplication. Note that all the operators +, -, * and unary - represent computations of addition, subtraction, multiplication and negation modulo M = 215 = 32768, respectively. Thus all the values are nonnegative integers between 0 and 32767, inclusive. For example, the result of an expression 2 - 3 should be 32767, instead of -1. inum is a non-negative decimal integer less than M. var represents the matrix that is assigned to the variable var in the most recent preceding assignment statement of the same variable. matrix represents a mathematical matrix similar to a 2-dimensional array whose elements are integers. It is denoted by a row-seq with a pair of enclosing square brackets. row-seq represents a sequence of rows, adjacent two of which are separated by a semicolon. row represents a sequence of expressions, adjacent two of which are separated by a space character. For example, [1 2 3;4 5 6] represents a matrix <image>. The first row has three integers separated by two space characters, i.e. "1 2 3". The second row has three integers, i.e. "4 5 6". Here, the row-seq consists of the two rows separated by a semicolon. The matrix is denoted by the row-seq with a pair of square brackets. Note that elements of a row may be matrices again. Thus the nested representation of a matrix may appear. The number of rows of the value of each expression of a row should be the same, and the number of columns of the value of each row of a row-seq should be the same. For example, a matrix represented by [[1 2 3;4 5 6] [7 8;9 10] [11;12];13 14 15 16 17 18] is <image> The sizes of matrices should be consistent, as mentioned above, in order to form a well-formed matrix as the result. For example, [[1 2;3 4] [5;6;7];6 7 8] is not consistent since the first row "[1 2;3 4] [5;6;7]" has two matrices (2 Γ— 2 and 3 Γ— 1) whose numbers of rows are different. [1 2;3 4 5] is not consistent since the number of columns of two rows are different. The multiplication of 1 Γ— 1 matrix and m Γ— n matrix is well-defined for arbitrary m > 0 and n > 0, since a 1 Γ— 1 matrices can be regarded as a scalar integer. For example, 2*[1 2;3 4] and [1 2;3 4]*3 represent the products of a scalar and a matrix <image> and <image>. [2]*[1 2;3 4] and [1 2;3 4]*[3] are also well-defined similarly. An indexed-primary is a primary expression followed by two expressions as indices. The first index is 1 Γ— k integer matrix denoted by (i1 i2 ... ik), and the second index is 1 Γ— l integer matrix denoted by (j1 j2 ... jl). The two indices specify the submatrix extracted from the matrix which is the value of the preceding primary expression. The size of the submatrix is k Γ— l and whose (a, b)-element is the (ia, jb)-element of the value of the preceding primary expression. The way of indexing is one-origin, i.e., the first element is indexed by 1. For example, the value of ([1 2;3 4]+[3 0;0 2])([1],[2]) is equal to 2, since the value of its primary expression is a matrix [4 2;3 6], and the first index [1] and the second [2] indicate the (1, 2)-element of the matrix. The same integer may appear twice or more in an index matrix, e.g., the first index matrix of an expression [1 2;3 4]([2 1 1],[2 1]) is [2 1 1], which has two 1's. Its value is <image>. A transposed-primary is a primary expression followed by a single quote symbol ("'"), which indicates the transpose operation. The transposed matrix of an m Γ— n matrix A = (aij) (i = 1, ..., m and j = 1, ... , n) is the n Γ— m matrix B = (bij) (i = 1, ... , n and j = 1, ... , m), where bij = aji. For example, the value of [1 2;3 4]' is <image>. Input The input consists of multiple datasets, followed by a line containing a zero. Each dataset has the following format. n program n is a positive integer, which is followed by a program that is a sequence of single or multiple lines each of which is an assignment statement whose syntax is defined in Table J.1. n indicates the number of the assignment statements in the program. All the values of vars are undefined at the beginning of a program. You can assume the following: * 1 ≀ n ≀ 10, * the number of characters in a line does not exceed 80 (excluding a newline), * there are no syntax errors and semantic errors (e.g., reference of undefined var), * the number of rows of matrices appearing in the computations does not exceed 100, and * the number of columns of matrices appearing in the computations does not exceed 100. Output For each dataset, the value of the expression of each assignment statement of the program should be printed in the same order. All the values should be printed as non-negative integers less than M. When the value is an m Γ— n matrix A = (aij) (i = 1, ... ,m and j = 1, ... , n), m lines should be printed. In the k-th line (1 ≀ k ≀ m), integers of the k-th row, i.e., ak1, ... , akn, should be printed separated by a space. After the last value of a dataset is printed, a line containing five minus symbols '-----' should be printed for human readability. The output should not contain any other extra characters. Example Input 1 A=[1 2 3;4 5 6]. 1 A=[[1 2 3;4 5 6] [7 8;9 10] [11;12];13 14 15 16 17 18]. 3 B=[3 -2 1;-9 8 7]. C=([1 2 3;4 5 6]+B)(2,3). D=([1 2 3;4 5 6]+B)([1 2],[2 3]). 5 A=2*[1 2;-3 4]'. B=A([2 1 2],[2 1]). A=[1 2;3 4]*3. A=[2]*[1 2;3 4]. A=[1 2;3 4]*[3]. 2 A=[11 12 13;0 22 23;0 0 33]. A=[A A';--A''' A]. 2 A=[1 -1 1;1 1 -1;-1 1 1]*3. A=[A -A+-A;-A'([3 2 1],[3 2 1]) -A']. 1 A=1([1 1 1],[1 1 1 1]). 3 A=[1 2 -3;4 -5 6;-7 8 9]. B=A([3 1 2],[2 1 3]). C=A*B-B*A+-A*-B-B*-A. 3 A=[1 2 3 4 5]. B=A'*A. C=B([1 5],[5 1]). 3 A=[-11 12 13;21 -22 23;31 32 -33]. B=[1 0 0;0 1 0;0 0 1]. C=[(A-B) (A+B)*B (A+B)*(B-A)([1 1 1],[3 2 1]) [1 2 3;2 1 1;-1 2 1]*(A-B)]. 3 A=[11 12 13;0 22 23;0 0 33]. B=[1 2]. C=------A((((B))),B)(B,B)''''''. 2 A=1+[2]+[[3]]+[[[4]]]+2*[[[[5]]]]*3. B=[(-[([(-A)]+-A)])]. 8 A=[1 2;3 4]. B=[A A+[1 1;0 1]*4;A+[1 1;0 1]'*8 A+[1 1;0 1]''*12]. C=B([1],[1]). C=B([1],[1 2 3 4]). C=B([1 2 3 4],[1]). C=B([2 3],[2 3]). A=[1 2;1 2]. D=(A*-A+-A)'(A'(1,[1 2]),A'(2,[1 2])). 0 Output 1 2 3 4 5 6 ----- 1 2 3 7 8 11 4 5 6 9 10 12 13 14 15 16 17 18 ----- 3 32766 1 32759 8 7 13 0 4 13 13 ----- 2 32762 4 8 8 4 32762 2 8 4 3 6 9 12 2 4 6 8 3 6 9 12 ----- 11 12 13 0 22 23 0 0 33 11 12 13 11 0 0 0 22 23 12 22 0 0 0 33 13 23 33 11 0 0 11 12 13 12 22 0 0 22 23 13 23 33 0 0 33 ----- 3 32765 3 3 3 32765 32765 3 3 3 32765 3 32762 6 32762 3 3 32765 32762 32762 6 32765 3 3 6 32762 32762 32765 3 32765 32765 32765 3 32765 32765 3 3 32765 32765 3 32765 32765 32765 3 32765 ----- 1 1 1 1 1 1 1 1 1 1 1 1 ----- 1 2 32765 4 32763 6 32761 8 9 8 32761 9 2 1 32765 32763 4 6 54 32734 32738 32752 32750 174 32598 186 32702 ----- 1 2 3 4 5 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25 5 1 25 5 ----- 32757 12 13 21 32746 23 31 32 32735 1 0 0 0 1 0 0 0 1 32756 12 13 32758 12 13 32573 32588 180 123 62 32725 21 32745 23 21 32747 23 32469 32492 276 28 33 15 31 32 32734 31 32 32736 32365 32396 372 85 32742 32767 ----- 11 12 13 0 22 23 0 0 33 1 2 11 12 0 22 ----- 40 80 ----- 1 2 3 4 1 2 5 6 3 4 3 8 9 2 13 14 11 12 3 16 1 1 2 5 6 1 3 9 11 4 3 2 13 1 2 1 2 32764 32764 32764 32764 ----- The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sales department of Japanese Ancient Giant Corp. is visiting a hot spring resort for their recreational trip. For deepening their friendships, they are staying in one large room of a Japanese-style hotel called a ryokan. In the ryokan, people sleep in Japanese-style beds called futons. They all have put their futons on the floor just as they like. Now they are ready for sleeping but they have one concern: they don’t like to go into their futons with their legs toward heads β€” this is regarded as a bad custom in Japanese tradition. However, it is not obvious whether they can follow a good custom. You are requested to write a program answering their question, as a talented programmer. Here let's model the situation. The room is considered to be a grid on an xy-plane. As usual, x-axis points toward right and y-axis points toward up. Each futon occupies two adjacent cells. People put their pillows on either of the two cells. Their heads come to the pillows; their foots come to the other cells. If the cell of some person's foot becomes adjacent to the cell of another person's head, regardless their directions, then it is considered as a bad case. Otherwise people are all right. Input The input is a sequence of datasets. Each dataset is given in the following format: n x1 y1 dir1 ... xn yn dirn n is the number of futons (1 ≀ n ≀ 20,000); (xi, yi) denotes the coordinates of the left-bottom corner of the i-th futon; diri is either 'x' or 'y' and denotes the direction of the i-th futon, where 'x' means the futon is put horizontally and 'y' means vertically. All coordinate values are non-negative integers not greater than 109 . It is guaranteed that no two futons in the input overlap each other. The input is terminated by a line with a single zero. This is not part of any dataset and thus should not be processed. Output For each dataset, print "Yes" in a line if it is possible to avoid a bad case, or "No" otherwise. Example Input 4 0 0 x 2 0 x 0 1 x 2 1 x 4 1 0 x 0 1 x 2 1 x 1 2 x 4 0 0 x 2 0 y 0 1 y 1 2 x 0 Output Yes No Yes The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 = {a1, a2, . . . , an} with the following operations: * add(i, x): add x to ai. * getSum(s, t): print the sum of as, as+1,...,at. Note that the initial values of ai (i = 1, 2, . . . , n) are 0. Constraints * 1 ≀ n ≀ 100000 * 1 ≀ q ≀ 100000 * If comi is 0, then 1 ≀ xi ≀ n, 0 ≀ yi ≀ 1000. * If comi is 1, then 1 ≀ xi ≀ n, 1 ≀ yi ≀ n. Input n q com1 x1 y1 com2 x2 y2 ... comq xq yq 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 add(xi, yi) and '1' denotes getSum(xi, yi). Output For each getSum operation, print the sum in a line. Example Input 3 5 0 1 1 0 2 2 0 3 3 1 1 2 1 2 2 Output 3 2 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Devu is a class teacher of a class of n students. One day, in the morning prayer of the school, all the students of his class were standing in a line. You are given information of their arrangement by a string s. The string s consists of only letters 'B' and 'G', where 'B' represents a boy and 'G' represents a girl. Devu wants inter-gender interaction among his class should to be maximum. So he does not like seeing two or more boys/girls standing nearby (i.e. continuous) in the line. e.g. he does not like the arrangements BBG and GBB, but he likes BG, GBG etc. Now by seeing the initial arrangement s of students, Devu may get furious and now he wants to change this arrangement into a likable arrangement. For achieving that, he can swap positions of any two students (not necessary continuous). Let the cost of swapping people from position i with position j (i β‰  j) be c(i, j). You are provided an integer variable type, then the cost of the the swap will be defined by c(i, j) = |j βˆ’ i|^type. Please help Devu in finding minimum cost of swaps needed to convert the current arrangement into a likable one. Input The first line of input contains an integer T, denoting the number of test cases. Then T test cases are follow. The first line of each test case contains an integer type, denoting the type of the cost function. Then the next line contains string s of length n, denoting the initial arrangement s of students. Note that the integer n is not given explicitly in input. Output For each test case, print a single line containing the answer of the test case, that is, the minimum cost to convert the current arrangement into a likable one. If it is not possible to convert the current arrangement into a likable one, then print -1 instead of the minimum cost. Constraints and Example Input: 8 0 BB 0 BG 0 BBGG 1 BGG 1 BGGB 1 BBBGG 2 BBGG 2 BGB Output: -1 0 1 1 1 3 1 0 Explanation Note type of the first 3 test cases is 0. So c(i, j) = 1. Hence we just have to count minimum number of swaps needed. Example case 1. There is no way to make sure that both the boys does not stand nearby. So answer is -1. Example case 2. Arrangement is already valid. No swap is needed. So answer is 0. Example case 3. Swap boy at position 1 with girl at position 2. After swap the arrangement will be BGBG which is a valid arrangement. So answer is 1. Now type of the next 3 test cases is 1. So c(i, j) = |j βˆ’ i|, that is, the absolute value of the difference between i and j. Example case 4. Swap boy at position 0 with girl at position 1. After swap the arrangement will be GBG which is a valid arrangement. So answer is |1 - 0| = 1. Example case 5. Swap boy at position 0 with girl at position 1. After swap the arrangement will be GBGB which is a valid arrangement. So answer is |1 - 0| = 1. Example case 6. Swap boy at position 1 with girl at position 4. After swap the arrangement will be BGBGB which is a valid arrangement. So answer is |4 - 1| = 3. Then type of the last 2 test cases is 2. So c(i, j) = (j βˆ’ i)^2 Example case 7. Swap boy at position 1 with girl at position 2. After swap the arrangement will be BGBG which is a valid arrangement. So answer is (2 - 1)^2 = 1. Example case 8. Arrangement is already valid. No swap is needed. So answer is 0. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an interactive problem. Bob lives in a square grid of size n Γ— n, with rows numbered 1 through n from top to bottom, and columns numbered 1 through n from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer n. Bob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move down or right to an adjacent cell, if it is allowed. You can ask at most 4 β‹… n queries of form "? r_1 c_1 r_2 c_2" (1 ≀ r_1 ≀ r_2 ≀ n, 1 ≀ c_1 ≀ c_2 ≀ n). The answer will be "YES" if Bob can get from a cell (r_1, c_1) to a cell (r_2, c_2), and "NO" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is "NO" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least n - 1, i.e. the following condition must be satisfied: (r_2 - r_1) + (c_2 - c_1) β‰₯ n - 1. It's guaranteed that Bob can get from the top-left corner (1, 1) to the bottom-right corner (n, n) and your task is to find a way to do it. You should print the answer in form "! S" where S is a string of length 2 β‹… n - 2 consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by 1, the right move increases the second coordinate by 1. If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution. Input The only line of the input contains an integer n (2 ≀ n ≀ 500) β€” the size of the grid. Output When you are ready to print the answer, print a single line containing "! S" where where S is a string of length 2 β‹… n - 2 consisting of characters 'D' and 'R', denoting moves down and right respectively. The path should be a valid path going from the cell (1, 1) to the cell (n, n) passing only through allowed cells. Interaction You can ask at most 4 β‹… n queries. To ask a query, print a line containing "? r_1 c_1 r_2 c_2" (1 ≀ r_1 ≀ r_2 ≀ n, 1 ≀ c_1 ≀ c_2 ≀ n). After that you should read a single line containing "YES" or "NO" depending on the answer of the query. "YES" means Bob can go from the cell (r_1, c_1) to the cell (r_2, c_2), "NO" means the opposite. Note that the grid is fixed before the start of your solution and does not depend on your queries. After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded or other negative verdict. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Answer "BAD" instead of "YES" or "NO" means that you made an invalid query. Exit immediately after receiving "BAD" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream. Example Input 4 Β  YES Β  NO Β  YES Β  YES Β  Output Β  ? 1 1 4 4 Β  ? 1 2 4 3 Β  ? 4 1 4 4 Β  ? 1 4 4 4 Β  ! RDRRDD Note The first example is shown on the picture below. <image> To hack, use the following input format: The first line should contain a single integer n (2 ≀ n ≀ 500) β€” the size of the grid. Each of the next n lines should contain a string of n characters '#' or '.', where '#' denotes a blocked cell, and '.' denotes an allowed cell. For example, the following text encodes the example shown above: 4 ..#. #... ###. .... The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 German University in Cairo (GUC) dorm houses are numbered from 1 to n. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle). For each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house. In order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap. Input The first line contains two space-separated integers n and p (1 ≀ n ≀ 1000, 0 ≀ p ≀ n) β€” the number of houses and the number of pipes correspondingly. Then p lines follow β€” the description of p pipes. The i-th line contains three integers ai bi di, indicating a pipe of diameter di going from house ai to house bi (1 ≀ ai, bi ≀ n, ai β‰  bi, 1 ≀ di ≀ 106). It is guaranteed that for each house there is at most one pipe going into it and at most one pipe going out of it. Output Print integer t in the first line β€” the number of tank-tap pairs of houses. For the next t lines, print 3 integers per line, separated by spaces: tanki, tapi, and diameteri, where tanki β‰  tapi (1 ≀ i ≀ t). Here tanki and tapi are indexes of tank and tap houses respectively, and diameteri is the maximum amount of water that can be conveyed. All the t lines should be ordered (increasingly) by tanki. Examples Input 3 2 1 2 10 2 3 20 Output 1 1 3 10 Input 3 3 1 2 20 2 3 10 3 1 5 Output 0 Input 4 2 1 2 60 3 4 50 Output 2 1 2 60 3 4 50 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, TharkΓ»n to the Dwarves, OlΓ³rin I was in my youth in the West that is forgotten, in the South IncΓ‘nus, in the North Gandalf; to the East I go not." And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times k, so they got k+1 pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled. In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using 3 cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts. More formally, Sasha wants for the given palindrome s find such minimum k, that you can cut this string into k + 1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. It there is no answer, then print "Impossible" (without quotes). Input The first line contains one string s (1 ≀ |s| ≀ 5 000) β€” the initial name, which consists only of lowercase Latin letters. It is guaranteed that s is a palindrome. Output Print one integer k β€” the minimum number of cuts needed to get a new name, or "Impossible" (without quotes). Examples Input nolon Output 2 Input otto Output 1 Input qqqq Output Impossible Input kinnikkinnik Output 1 Note In the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut. In the second example, you can cut the string right in the middle, and swap peaces, so you get toot. In the third example, you can't make a string, that won't be equal to the initial one. In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's analyze a program written on some strange programming language. The variables in this language have names consisting of 1 to 4 characters, and each character is a lowercase or an uppercase Latin letter, or a digit. There is an extra constraint that the first character should not be a digit. There are four types of operations in the program, each denoted by one of the characters: $, ^, # or &. Each line of the program has one of the following formats: * <lvalue>=<rvalue>, where <lvalue> and <rvalue> are valid variable names; * <lvalue>=<arg1><op><arg2>, where <lvalue>, <arg1> and <arg2> are valid variable names, and <op> is an operation character. The program is executed line-by-line, and the result of execution is stored in a variable having the name res. If res is never assigned in the program, then the result will be equal to the value of res before running the program. Two programs are called equivalent if no matter which operations do characters $, ^, # and & denote (but, obviously, performing the same operation on the same arguments gives the same result) and which values do variables have before execution of program, the value of res after running the first program is equal to the value of res after running the second program (the programs are executed independently). You are given a program consisting of n lines. Your task is to write a program consisting of minimum possible number of lines that is equivalent to the program you are given. Input The first line contains one integer n (1 ≀ n ≀ 1000) β€” the number of lines in the program. Then n lines follow β€” the program itself. Each line corresponds to the format described in the statement and has no extra whitespaces. Output In the first line print k β€” the minimum number of lines in the equivalent program. Then print k lines without any whitespaces β€” an equivalent program having exactly k lines, in the same format it is described in the statement. Examples Input 4 c=aa#bb d12=c res=c^d12 tmp=aa$c Output 2 aaaa=aa#bb res=aaaa^aaaa Input 2 max=aaaa$bbbb min=bbbb^aaaa Output 0 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≀ n ≀ 10^5, 0 ≀ q ≀ 3 β‹… 10^5) β€” the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≀ a_i ≀ 10^9) β€” the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≀ m_j ≀ 10^{18}). Output For each teacher's query, output two numbers A and B β€” the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] β€” on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 β€” to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] β‡’ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] β‡’ A = 5, B = 2. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42]. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. All of us love treasures, right? That's why young Vasya is heading for a Treasure Island. Treasure Island may be represented as a rectangular table n Γ— m which is surrounded by the ocean. Let us number rows of the field with consecutive integers from 1 to n from top to bottom and columns with consecutive integers from 1 to m from left to right. Denote the cell in r-th row and c-th column as (r, c). Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell (n, m). Vasya got off the ship in cell (1, 1). Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell (x, y) he can move only to cells (x+1, y) and (x, y+1). Of course Vasya can't move through cells with impassable forests. Evil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells (1, 1) where Vasya got off his ship and (n, m) where the treasure is hidden. Help Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure. Input First line of input contains two positive integers n, m (3 ≀ n β‹… m ≀ 1 000 000), sizes of the island. Following n lines contains strings s_i of length m describing the island, j-th character of string s_i equals "#" if cell (i, j) contains an impassable forest and "." if the cell is free and passable. Let us remind you that Vasya gets of his ship at the cell (1, 1), i.e. the first cell of the first row, and he wants to reach cell (n, m), i.e. the last cell of the last row. It's guaranteed, that cells (1, 1) and (n, m) are empty. Output Print the only integer k, which is the minimum number of cells Evil Witch has to turn into impassable forest in order to prevent Vasya from reaching the treasure. Examples Input 2 2 .. .. Output 2 Input 4 4 .... #.#. .... .#.. Output 1 Input 3 4 .... .##. .... Output 2 Note The following picture illustrates the island in the third example. Blue arrows show possible paths Vasya may use to go from (1, 1) to (n, m). Red illustrates one possible set of cells for the Witch to turn into impassable forest to make Vasya's trip from (1, 1) to (n, m) impossible. <image> The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This is the harder version of the problem. In this version, 1 ≀ n ≀ 10^6 and 0 ≀ a_i ≀ 10^6. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes of chocolate, numbered from 1 to n. Initially, the i-th box contains a_i chocolate pieces. Since Bob is a typical nice guy, he will not send Alice n empty boxes. In other words, at least one of a_1, a_2, …, a_n is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer k > 1 such that the number of pieces in each box is divisible by k. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box i and put it into either box i-1 or box i+1 (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy. Input The first line contains a single integer n (1 ≀ n ≀ 10^6) β€” the number of chocolate boxes. The second line contains n integers a_1, a_2, …, a_n (0 ≀ a_i ≀ 10^6) β€” the number of chocolate pieces in the i-th box. It is guaranteed that at least one of a_1, a_2, …, a_n is positive. Output If there is no way for Charlie to make Alice happy, print -1. Otherwise, print a single integer x β€” the minimum number of seconds for Charlie to help Bob make Alice happy. Examples Input 3 4 8 5 Output 9 Input 5 3 10 2 1 5 Output 2 Input 4 0 5 15 10 Output 0 Input 1 1 Output -1 Note In the first example, Charlie can move all chocolate pieces to the second box. Each box will be divisible by 17. In the second example, Charlie can move a piece from box 2 to box 3 and a piece from box 4 to box 5. Each box will be divisible by 3. In the third example, each box is already divisible by 5. In the fourth example, since Charlie has no available move, he cannot help Bob make Alice happy. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 Γ— 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains a statue cannot have anything or anyone β€” neither any other statues, nor Anna, nor Maria. Anna is present on the board as a figurant (she stands still and never moves), and Maria has been actively involved in the game. Her goal is β€” to come to Anna's square. Maria and statues move in turn, Maria moves first. During one move Maria can go to any adjacent on the side or diagonal cell in which there is no statue, or she can stay in the cell where she is. The statues during their move must go one square down simultaneously, and those statues that were in the bottom row fall from the board and are no longer appeared. At that moment, when one of the statues is in the cell in which the Maria is, the statues are declared winners. At the moment when Maria comes into the cell where Anna has been waiting, Maria is declared the winner. Obviously, nothing depends on the statues, so it all depends on Maria. Determine who will win, if Maria does not make a strategic error. Input You are given the 8 strings whose length equals 8, describing the initial position on the board. The first line represents the top row of the board, the next one β€” for the second from the top, and so on, the last line represents the bottom row. Each character string matches a single cell board in the appropriate row, and the characters are in the same manner as that of the corresponding cell. If the cell is empty, the corresponding character is ".". If a cell has Maria, then it is represented by character "M". If a cell has Anna, it is represented by the character "A". If a cell has a statue, then the cell is represented by character "S". It is guaranteed that the last character of the first row is always "A", the first character of the last line is always "M". The remaining characters are "." or "S". Output If Maria wins, print string "WIN". If the statues win, print string "LOSE". Examples Input .......A ........ ........ ........ ........ ........ ........ M....... Output WIN Input .......A ........ ........ ........ ........ ........ SS...... M....... Output LOSE Input .......A ........ ........ ........ ........ .S...... S....... MS...... Output LOSE The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light. Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up g seconds green, and then r seconds red, then again g seconds green and so on. Formally, the road can be represented as a segment [0, n]. Initially, Denis is at point 0. His task is to get to point n in the shortest possible time. He knows many different integers d_1, d_2, …, d_m, where 0 ≀ d_i ≀ n β€” are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on. Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: * He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by Β± 1 in 1 second. While doing so, he must always stay inside the segment [0, n]. * He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by +1 and he walked on a safety island, then he can change his position by Β± 1. Otherwise, he can change his position only by +1. Similarly, if in the previous second he changed his position by -1, on a safety island he can change position by Β± 1, and at any other point by -1. * At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to n. This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. Input The first line contains two integers n and m (1 ≀ n ≀ 10^6, 2 ≀ m ≀ min(n + 1, 10^4)) β€” road width and the number of safety islands. The second line contains m distinct integers d_1, d_2, …, d_m (0 ≀ d_i ≀ n) β€” the points where the safety islands are located. It is guaranteed that there are 0 and n among them. The third line contains two integers g, r (1 ≀ g, r ≀ 1000) β€” the time that the green light stays on and the time that the red light stays on. Output Output a single integer β€” the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output -1. Examples Input 15 5 0 3 7 14 15 11 11 Output 45 Input 13 4 0 3 7 13 9 9 Output -1 Note In the first test, the optimal route is: * for the first green light, go to 7 and return to 3. In this case, we will change the direction of movement at the point 7, which is allowed, since there is a safety island at this point. In the end, we will be at the point of 3, where there is also a safety island. The next 11 seconds we have to wait for the red light. * for the second green light reaches 14. Wait for the red light again. * for 1 second go to 15. As a result, Denis is at the end of the road. In total, 45 seconds are obtained. In the second test, it is impossible to cross the road according to all the rules. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ashish has a tree consisting of n nodes numbered 1 to n rooted at node 1. The i-th node in the tree has a cost a_i, and binary digit b_i is written in it. He wants to have binary digit c_i written in the i-th node in the end. To achieve this, he can perform the following operation any number of times: * Select any k nodes from the subtree of any node u, and shuffle the digits in these nodes as he wishes, incurring a cost of k β‹… a_u. Here, he can choose k ranging from 1 to the size of the subtree of u. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target. Help him find the minimum total cost he needs to spend so that after all the operations, every node u has digit c_u written in it, or determine that it is impossible. Input First line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) denoting the number of nodes in the tree. i-th line of the next n lines contains 3 space-separated integers a_i, b_i, c_i (1 ≀ a_i ≀ 10^9, 0 ≀ b_i, c_i ≀ 1) β€” the cost of the i-th node, its initial digit and its goal digit. Each of the next n - 1 lines contain two integers u, v (1 ≀ u, v ≀ n, u β‰  v), meaning that there is an edge between nodes u and v in the tree. Output Print the minimum total cost to make every node reach its target digit, and -1 if it is impossible. Examples Input 5 1 0 1 20 1 0 300 0 1 4000 0 0 50000 1 0 1 2 2 3 2 4 1 5 Output 4 Input 5 10000 0 1 2000 1 0 300 0 1 40 0 0 1 1 0 1 2 2 3 2 4 1 5 Output 24000 Input 2 109 0 1 205 0 1 1 2 Output -1 Note The tree corresponding to samples 1 and 2 are: <image> In sample 1, we can choose node 1 and k = 4 for a cost of 4 β‹… 1 = 4 and select nodes {1, 2, 3, 5}, shuffle their digits and get the desired digits in every node. In sample 2, we can choose node 1 and k = 2 for a cost of 10000 β‹… 2, select nodes {1, 5} and exchange their digits, and similarly, choose node 2 and k = 2 for a cost of 2000 β‹… 2, select nodes {2, 3} and exchange their digits to get the desired digits in every node. In sample 3, it is impossible to get the desired digits, because there is no node with digit 1 initially. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≀ k ≀ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k. Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}. For each i (1 ≀ i ≀ n) she calculated a_i β€” the length of the longest common prefix of s_i and s_{i+1}. Several days later Koa found these numbers, but she couldn't remember the strings. So Koa would like to find some strings s_1, s_2, ..., s_{n+1} which would have generated numbers a_1, a_2, ..., a_n. Can you help her? If there are many answers print any. We can show that answer always exists for the given constraints. Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 100) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer n (1 ≀ n ≀ 100) β€” the number of elements in the list a. The second line of each test case contains n integers a_1, a_2, …, a_n (0 ≀ a_i ≀ 50) β€” the elements of a. It is guaranteed that the sum of n over all test cases does not exceed 100. Output For each test case: Output n+1 lines. In the i-th line print string s_i (1 ≀ |s_i| ≀ 200), consisting of lowercase Latin letters. Length of the longest common prefix of strings s_i and s_{i+1} has to be equal to a_i. If there are many answers print any. We can show that answer always exists for the given constraints. Example Input 4 4 1 2 4 2 2 5 3 3 1 3 1 3 0 0 0 Output aeren ari arousal around ari monogon monogamy monthly kevinvu kuroni kurioni korone anton loves adhoc problems Note In the 1-st test case one of the possible answers is s = [aeren, ari, arousal, around, ari]. Lengths of longest common prefixes are: * Between \color{red}{a}eren and \color{red}{a}ri β†’ 1 * Between \color{red}{ar}i and \color{red}{ar}ousal β†’ 2 * Between \color{red}{arou}sal and \color{red}{arou}nd β†’ 4 * Between \color{red}{ar}ound and \color{red}{ar}i β†’ 2 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an array a of n integers, such that a_1 + a_2 + β‹…β‹…β‹… + a_n = 0. In one operation, you can choose two different indices i and j (1 ≀ i, j ≀ n), decrement a_i by one and increment a_j by one. If i < j this operation is free, otherwise it costs one coin. How many coins do you have to spend in order to make all elements equal to 0? Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 5000). Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 10^5) β€” the number of elements. The next line contains n integers a_1, …, a_n (-10^9 ≀ a_i ≀ 10^9). It is given that βˆ‘_{i=1}^n a_i = 0. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the minimum number of coins we have to spend in order to make all elements equal to 0. Example Input 7 4 -3 5 -3 1 2 1 -1 4 -3 2 -3 4 4 -1 1 1 -1 7 -5 7 -6 -4 17 -13 4 6 -1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000 1 0 Output 3 0 4 1 8 3000000000 0 Note Possible strategy for the first test case: * Do (i=2, j=3) three times (free), a = [-3, 2, 0, 1]. * Do (i=2, j=1) two times (pay two coins), a = [-1, 0, 0, 1]. * Do (i=4, j=1) one time (pay one coin), a = [0, 0, 0, 0]. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not. The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba". You are given a string s, consisting of lowercase Latin letters and characters "?". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the "?" characters by Latin letters. Each "?" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = Β«abaΒ», then the string "a??" is good, and the string Β«?bcΒ» is not. Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times). Input The first line is non-empty string s, consisting of no more than 105 lowercase Latin letters and characters "?". The second line is non-empty string p, consisting of no more than 105 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s. Output Print the single number representing the number of good substrings of string s. Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times. Examples Input bb??x??? aab Output 2 Input ab?c acb Output 2 Note Consider the first sample test. Here the string s has two good substrings: "b??" (after we replace the question marks we get "baa"), "???" (after we replace the question marks we get "baa"). Let's consider the second sample test. Here the string s has two good substrings: "ab?" ("?" can be replaced by "c"), "b?c" ("?" can be replaced by "a"). The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s. Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order. A merge z is produced from a sequence a by the following rules: * if a_i=0, then remove a letter from the beginning of x and append it to the end of z; * if a_i=1, then remove a letter from the beginning of y and append it to the end of z. Two merging sequences a and b are different if there is some position i such that a_i β‰  b_i. Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} β‰  z_i. Let s[l,r] for some 1 ≀ l ≀ r ≀ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive. Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered. Calculate βˆ‘ _{1 ≀ l_1 ≀ r_1 ≀ |x| \\\ 1 ≀ l_2 ≀ r_2 ≀ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353. Input The first line contains a string x (1 ≀ |x| ≀ 1000). The second line contains a string y (1 ≀ |y| ≀ 1000). Both strings consist only of lowercase Latin letters. Output Print a single integer β€” the sum of f(l_1, r_1, l_2, r_2) over 1 ≀ l_1 ≀ r_1 ≀ |x| and 1 ≀ l_2 ≀ r_2 ≀ |y| modulo 998 244 353. Examples Input aaa bb Output 24 Input code forces Output 1574 Input aaaaa aaa Output 0 Input justamassivetesttocheck howwellyouhandlemodulooperations Output 667387032 Note In the first example there are: * 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10"; * 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101"; * 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010"; * 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010"; * 2 pairs of substrings "aaa" and "b", each with no valid merging sequences; * 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010"; Thus, the answer is 6 β‹… 2 + 3 β‹… 1 + 4 β‹… 1 + 2 β‹… 2 + 2 β‹… 0 + 1 β‹… 1 = 24. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an interactive problem! Nastia has a hidden permutation p of length n consisting of integers from 1 to n. You, for some reason, want to figure out the permutation. To do that, you can give her an integer t (1 ≀ t ≀ 2), two different indices i and j (1 ≀ i, j ≀ n, i β‰  j), and an integer x (1 ≀ x ≀ n - 1). Depending on t, she will answer: * t = 1: max{(min{(x, p_i)}, min{(x + 1, p_j)})}; * t = 2: min{(max{(x, p_i)}, max{(x + 1, p_j)})}. You can ask Nastia at most ⌊ \frac {3 β‹… n} { 2} βŒ‹ + 30 times. It is guaranteed that she will not change her permutation depending on your queries. Can you guess the permutation? Input The input consists of several test cases. In the beginning, you receive the integer T (1 ≀ T ≀ 10 000) β€” the number of test cases. At the beginning of each test case, you receive an integer n (3 ≀ n ≀ 10^4) β€” the length of the permutation p. It's guaranteed that the permutation is fixed beforehand and that the sum of n in one test doesn't exceed 2 β‹… 10^4. Interaction To ask a question, print "? t i j x" (t = 1 or t = 2, 1 ≀ i, j ≀ n, i β‰  j, 1 ≀ x ≀ n - 1) Then, you should read the answer. If we answer with βˆ’1 instead of a valid answer, that means you exceeded the number of queries or made an invalid query. Exit immediately after receiving βˆ’1 and you will see the Wrong Answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream. To print the answer, print "! p_1 p_2 … p_{n} (without quotes). Note that answering doesn't count as one of the ⌊ \frac {3 β‹… n} {2} βŒ‹ + 30 queries. After printing a query or printing the answer, do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * See the documentation for other languages. Hacks To hack the solution, use the following test format. The first line should contain a single integer T (1 ≀ T ≀ 10 000) β€” the number of test cases. For each test case in the first line print a single integer n (3 ≀ n ≀ 10^4) β€” the length of the hidden permutation p. In the second line print n space-separated integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n), where p is permutation. Note that the sum of n over all test cases should not exceed 2 β‹… 10^4. Example Input 2 4 3 2 5 3 Output ? 2 4 1 3 ? 1 2 4 2 ! 3 1 4 2 ? 2 3 4 2 ! 2 5 3 4 1 Note Consider the first test case. The hidden permutation is [3, 1, 4, 2]. We print: "? 2 4 1 3" and get back min{(max{(3, p_4}), max{(4, p_1)})} = 3. We print: "? 1 2 4 2" and get back max{(min{(2, p_2)}, min{(3, p_4)})} = 2. Consider the second test case. The hidden permutation is [2, 5, 3, 4, 1]. We print: "? 2 3 4 2" and get back min{(max{(2, p_3}), max{(3, p_4)})} = 3. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly. More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of length n. Also, you've got m queries of two types: 1. Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by + q = ax + q for all integer q (0 ≀ q < k). The given operation is correct β€” both subsegments do not touch unexistent elements. 2. Determine the value in position x of array b, that is, find value bx. For each query of the second type print the result β€” the value of the corresponding element of array b. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1, a2, ..., an (|ai| ≀ 109). The third line contains an array of integers b1, b2, ..., bn (|bi| ≀ 109). Next m lines contain the descriptions of the queries. The i-th line first contains integer ti β€” the type of the i-th query (1 ≀ ti ≀ 2). If ti = 1, then the i-th query means the copying operation. If ti = 2, then the i-th query means taking the value in array b. If ti = 1, then the query type is followed by three integers xi, yi, ki (1 ≀ xi, yi, ki ≀ n) β€” the parameters of the copying query. If ti = 2, then the query type is followed by integer xi (1 ≀ xi ≀ n) β€” the position in array b. All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b. Output For each second type query print the result on a single line. Examples Input 5 10 1 2 0 -1 3 3 1 5 -2 0 2 5 1 3 3 3 2 5 2 4 2 1 1 2 1 4 2 1 2 4 1 4 2 1 2 2 Output 0 3 -1 3 2 3 -1 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≀ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1). A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr. Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≀ l ≀ r ≀ |p|) such that p[l... r] = t. We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] β‰  s[z... w]. Input The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≀ li ≀ ri ≀ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters. The input limits for scoring 30 points are (subproblem G1): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 200. The input limits for scoring 70 points are (subproblems G1+G2): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 50000. Output Print a single integer β€” the number of good substrings of string s. Examples Input aaab 2 aa 0 0 aab 1 1 Output 3 Input ltntlnen 3 n 0 0 ttlneenl 1 4 lelllt 1 1 Output 2 Input a 0 Output 1 Note There are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ». In the second test only substrings Β«eΒ» and Β«tΒ» are good. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria: * The graph doesn't contain any multiple arcs; * There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v). * The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops. However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph. George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 500, 1 ≀ m ≀ 1000) β€” the number of vertices and arcs in the presented graph. Each of the next m lines contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n) β€” the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs. Assume that the grah vertices are numbered 1 through n. Output Print a single integer β€” the answer to George's question. Examples Input 3 7 1 1 2 2 3 1 1 3 3 2 2 3 3 3 Output 0 Input 3 6 1 1 2 2 3 1 3 2 2 3 3 3 Output 1 Input 3 1 2 2 Output 6 Note For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph In the first sample the graph already is interesting, its center is vertex 3. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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: <image> That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an. Your task is to paint a cardiogram by given sequence ai. Input The first line contains integer n (2 ≀ n ≀ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000. Output Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> 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 <span class="tex-span"> / </span><span class="tex-span">\</span> <span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span> <span class="tex-span"> / </span> <span class="tex-span">\</span> <span class="tex-span"> / </span> <span class="tex-span">\</span> <span class="tex-span">\</span><span class="tex-span"> / </span> Input 3 1 5 1 Output <span class="tex-span"> / </span><span class="tex-span">\</span> <span class="tex-span">\</span> <span class="tex-span">\</span> <span class="tex-span">\</span> <span class="tex-span">\</span><span class="tex-span"> / </span> Note Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below. http://assets.codeforces.com/rounds/435/1.txt http://assets.codeforces.com/rounds/435/2.txt The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical. The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification. Help Vasya β€” compose a crossword of the described type using the given six words. It is allowed to use the words in any order. Input Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters. Output If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots. If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages. Examples Input NOD BAA YARD AIRWAY NEWTON BURN Output BAA... U.I... R.R... NEWTON ..A..O ..YARD Input AAA AAA AAAAA AAA AAA AAAAA Output AAA.. A.A.. AAAAA ..A.A ..AAA Input PTC JYNYFDSGI ZGPPC IXEJNDOP JJFS SSXXQOFGJUZ Output JJFS.... Y..S.... N..X.... Y..X.... F..Q.... D..O.... S..F.... G..G.... IXEJNDOP ...U...T ...ZGPPC The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ— h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how. In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments. After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process. Leonid offers to divide the labor β€” he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree? Input The first line contains three integers w, h, n (2 ≀ w, h ≀ 200 000, 1 ≀ n ≀ 200 000). Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≀ y ≀ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≀ x ≀ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts. Output After each cut print on a single line the area of the maximum available glass fragment in mm2. Examples Input 4 3 4 H 2 V 2 V 3 V 1 Output 8 4 4 2 Input 7 6 5 H 4 V 3 V 5 H 2 V 1 Output 28 16 12 6 4 Note Picture for the first sample test: <image> Picture for the second sample test: <image> The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions: * each elements, starting from the second one, is no more than the preceding one * each element, starting from the second one, is no less than the preceding one Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last. Input The single line contains an integer n which is the size of the array (1 ≀ n ≀ 105). Output You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007. Examples Input 2 Output 4 Input 3 Output 17 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 function <image> is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| ≀ KΒ·|x - y| holds for all <image>. We'll deal with a more... discrete version of this term. For an array <image>, we define it's Lipschitz constant <image> as follows: * if n < 2, <image> * if n β‰₯ 2, <image> over all 1 ≀ i < j ≀ n In other words, <image> is the smallest non-negative integer such that |h[i] - h[j]| ≀ LΒ·|i - j| holds for all 1 ≀ i, j ≀ n. You are given an array <image> of size n and q queries of the form [l, r]. For each query, consider the subarray <image>; determine the sum of Lipschitz constants of all subarrays of <image>. Input The first line of the input contains two space-separated integers n and q (2 ≀ n ≀ 100 000 and 1 ≀ q ≀ 100) β€” the number of elements in array <image> and the number of queries respectively. The second line contains n space-separated integers <image> (<image>). The following q lines describe queries. The i-th of those lines contains two space-separated integers li and ri (1 ≀ li < ri ≀ n). Output Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer β€” the sum of Lipschitz constants of all subarrays of <image>. Examples Input 10 4 1 5 2 9 1 3 4 2 1 7 2 4 3 8 7 10 1 9 Output 17 82 23 210 Input 7 6 5 7 7 4 6 6 2 1 2 2 3 2 6 1 7 4 7 3 5 Output 2 0 22 59 16 8 Note In the first query of the first sample, the Lipschitz constants of subarrays of <image> with length at least 2 are: * <image> * <image> * <image> The answer to the query is their sum. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level. Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level. Input The first line of the input consists of two integers, the number of robots n (2 ≀ n ≀ 100 000) and the number of rap battles m (<image>). The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots. It is guaranteed that at least one ordering of the robots satisfies all m relations. Output Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1. Examples Input 4 5 2 1 1 3 2 3 4 2 4 3 Output 4 Input 3 2 1 2 3 2 Output -1 Note In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles. In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba". If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible. Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible. Input The first line of the input contains an integer n (1 ≀ n ≀ 100 000) β€” the length of the string s. The second line contains the string s of length n consisting of only lowercase English letters. Output If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes. Examples Input 2 aa Output 1 Input 4 koko Output 2 Input 5 murat Output 0 Note In the first sample one of the possible solutions is to change the first character to 'b'. In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko". The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads. <image> Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows: let starting_time be an array of length n current_time = 0 dfs(v): current_time = current_time + 1 starting_time[v] = current_time shuffle children[v] randomly (each permutation with equal possibility) // children[v] is vector of children cities of city v for u in children[v]: dfs(u) As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)). Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help. Input The first line of input contains a single integer n (1 ≀ n ≀ 105) β€” the number of cities in USC. The second line contains n - 1 integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC. Output In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i]. Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6. Examples Input 7 1 2 1 1 4 4 Output 1.0 4.0 5.0 3.5 4.5 5.0 5.0 Input 12 1 1 2 2 4 4 3 3 1 10 8 Output 1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game! n racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to n-th (no two racers share the same place) and first m places are awarded. Racer gains bi points for i-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer i is ai points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order. Unfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship. Input The first line contains number n (1 ≀ n ≀ 105) β€” number of racers. Each of the next n lines contains si and ai β€” nick of the racer (nonempty string, which consist of no more than 20 lowercase Latin letters) and the racer's points (0 ≀ ai ≀ 106). Racers are given in the arbitrary order. The next line contains the number m (0 ≀ m ≀ n). Then m nonnegative integer numbers bi follow. i-th number is equal to amount of points for the i-th awarded place (0 ≀ bi ≀ 106). The last line contains Vasya's racer nick. Output Output two numbers β€” the highest and the lowest place Vasya can take up as a result of the championship. Examples Input 3 teama 10 teamb 20 teamc 40 2 10 20 teama Output 2 3 Input 2 teama 10 teamb 10 2 10 10 teamb Output 2 2 The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not. You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year. Input The first line contains integer number n (1 ≀ n ≀ 109) β€” current year in Berland. Output Output amount of years from the current year to the next lucky one. Examples Input 4 Output 1 Input 201 Output 99 Input 4000 Output 1000 Note In the first example next lucky year is 5. In the second one β€” 300. In the third β€” 5000. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one.. There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern. Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not. Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning. A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string. The good letters are given to Petya. All the others are bad. Input The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad. The second line contains the pattern β€” a string s of lowercase English letters, characters "?" and "*" (1 ≀ |s| ≀ 105). It is guaranteed that character "*" occurs in s no more than once. The third line contains integer n (1 ≀ n ≀ 105) β€” the number of query strings. n lines follow, each of them contains single non-empty string consisting of lowercase English letters β€” a query string. It is guaranteed that the total length of all query strings is not greater than 105. Output Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise. You can choose the case (lower or upper) for each letter arbitrary. Examples Input ab a?a 2 aaa aab Output YES NO Input abc a?a?a* 4 abacaba abaca apapa aaaaax Output NO YES NO YES Note In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter. Explanation of the second example. * The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good. * The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide. * The third query: "NO", because characters "?" can't be replaced with bad letters. * The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x". The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks. Formally, her room can be represented as a field of n Γ— m cells, each cell of which is empty or littered with cans. Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells. Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally? It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide. Input The first line contains three integers n, m and k (1 ≀ n, m, k ≀ 1000) β€” the sizes of the room and Olya's speed. Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise. The last line contains four integers x1, y1, x2, y2 (1 ≀ x1, x2 ≀ n, 1 ≀ y1, y2 ≀ m) β€” the coordinates of the first and the last cells. Output Print a single integer β€” the minimum time it will take Olya to get from (x1, y1) to (x2, y2). If it's impossible to get from (x1, y1) to (x2, y2), print -1. Examples Input 3 4 4 .... ###. .... 1 1 3 1 Output 3 Input 3 4 1 .... ###. .... 1 1 3 1 Output 8 Input 2 2 1 .# #. 1 1 2 2 Output -1 Note In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second. In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds. Olya does not recommend drinking energy drinks and generally believes that this is bad. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice. For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17). Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice. Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob. In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7). One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart? Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text? More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο€ such that <image> for every i. Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds. Input The first line contains a single integer N (1 ≀ N ≀ 300000), the length of the message. The second line contains N integers A1, A2, ..., AN (0 ≀ Ai < 230) representing the encrypted message. The third line contains N integers P1, P2, ..., PN (0 ≀ Pi < 230) representing the permuted encryption key. Output Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative. Examples Input 3 8 4 13 17 2 7 Output 10 3 28 Input 5 12 7 87 22 11 18 39 9 12 16 Output 0 14 69 6 44 Input 10 331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951 226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667 Output 128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284 Note In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems. Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro. She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over. Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator. As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem? Input A single line contains one non-negative integer n (0 ≀ n ≀ 10^{18}) β€” the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces. Output A single integer β€” the number of straight cuts Shiro needs. Examples Input 3 Output 2 Input 4 Output 5 Note To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them. To cut the round pizza into five equal parts one has to make five cuts. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A string s of length n can be encrypted by the following algorithm: * iterate over all divisors of n in decreasing order (i.e. from n to 1), * for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d). For example, the above algorithm applied to the string s="codeforces" leads to the following changes: "codeforces" β†’ "secrofedoc" β†’ "orcesfedoc" β†’ "rocesfedoc" β†’ "rocesfedoc" (obviously, the last reverse operation doesn't change the string because d=1). You are given the encrypted string t. Your task is to decrypt this string, i.e., to find a string s such that the above algorithm results in string t. It can be proven that this string s always exists and is unique. Input The first line of input consists of a single integer n (1 ≀ n ≀ 100) β€” the length of the string t. The second line of input consists of the string t. The length of t is n, and it consists only of lowercase Latin letters. Output Print a string s such that the above algorithm results in t. Examples Input 10 rocesfedoc Output codeforces Input 16 plmaetwoxesisiht Output thisisexampletwo Input 1 z Output z Note The first example is described in the problem statement. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. View Russian Translation Little pig Benny has just taken a shower. Now she is going to buy some gifts for her relatives. But the problem is that Benny doesn't know how to reach to the gift shop. Her friend Mike has created a special set of instructions for her. A set of instructions is a string which consists of letters {'L', 'R', 'U', 'D'}. For simplicity, let's assume that Benny is staying at point (0, 0) on the infinite plane. She consistently fulfills all the instructions written by Mike. Let's assume that now she is staying at point (X, Y). Then depending on what is the current instruction she moves in some direction: 'L' -- from (X, Y) moves to point (X, Y - 1) 'R' -- from (X, Y) moves to point (X, Y + 1) 'U' -- from (X, Y) moves to point (X - 1, Y) 'D' -- from (X, Y) moves to point (X + 1, Y) The weather is cold because it's winter now. Initially, all points are snowy. But if Benny have already visited some point at any time this point becomes icy (because Benny has just taken a shower). Every time, when Benny makes a step into icy points she slips and falls down. You are given a string S which denotes a set of instructions for Benny. Your task is to calculate how may times she will fall down. Input format Single line contains string S. Output format Output how many times Benny will fall down. Constraints - 1 ≀ S ≀ 10^5 SAMPLE INPUT RRULDL SAMPLE OUTPUT 2 Explanation Benny's route consists of points 0 0 (becomes icy) --> 0 1 (becomes icy) --> 0 2 (becomes icy) --> -1 2 (becomes icy) --> -1 1 (becomes icy) --> 0 1 (is icy) --> 0 0 (is icy) So Benny made two steps into icy points. The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mr. Hahn, our very own DJ, was seeing Chester and Mike fighting over such questions lately. Being a geek himself, he thought of showing off his skills and gave the both of them a question. He gave them a single positive integer, N. For all the numbers under 10^N(inclusive) they had to add the square of the digits of the number. They had to do this again for the new number obtained. This process was to be repeated until a cycle was formed. Now Mike figured out that a cycle could only be formed when they reached either 89 or 1 and also that a cycle is always formed. They had to find the number of numbers under 10^N which form a cycle at 89 and also number of those numbers that formed a cycle at 1. Input: A single positive integer, N. Output: A single line containing two space-separated positive integers. The first being the number of numbers which form a cycle at 89 and the second denoting the number of numbers which form a cycle at 1. Constraints: 1 ≀ N ≀ 10 Problem Setter: Chintan Shah SAMPLE INPUT 1 SAMPLE OUTPUT 7 3 Explanation As N = 1 they have to count for all numbers under 10^1 = 10 1 -> 1 2 -> 4 -> 16 -> 37 -> 58 -> 89 3 -> 9 -> 81 -> 65 -> 61 -> 37 -> 58 -> 89 4 -> 16 -> 37 -> 58 -> 89 and so on... The input will be give Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.