question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. E869120's and square1001's 16-th birthday is coming soon. Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces. E869120 and square1001 were just about to eat A and B of those pieces, respectively, when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake". Can both of them obey the instruction in the note and take desired numbers of pieces of cake? -----Constraints----- - A and B are integers between 1 and 16 (inclusive). - A+B is at most 16. -----Input----- Input is given from Standard Input in the following format: A B -----Output----- If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print Yay!; otherwise, print :(. -----Sample Input----- 5 4 -----Sample Output----- Yay! Both of them can take desired number of pieces as follows: Read the inputs from stdin solve the problem and write the answer to stdout (do 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 how Kai constructed the word "eternity" using pieces of ice as components? Little Sheldon plays with pieces of ice, each piece has exactly one digit between 0 and 9. He wants to construct his favourite number t. He realized that digits 6 and 9 are very similar, so he can rotate piece of ice with 6 to use as 9 (and vice versa). Similary, 2 and 5 work the same. There is no other pair of digits with similar effect. He called this effect "Digital Mimicry". Sheldon favourite number is t. He wants to have as many instances of t as possible. How many instances he can construct using the given sequence of ice pieces. He can use any piece at most once. -----Input----- The first line contains integer t (1 ≤ t ≤ 10000). The second line contains the sequence of digits on the pieces. The length of line is equal to the number of pieces and between 1 and 200, inclusive. It contains digits between 0 and 9. -----Output----- Print the required number of instances. -----Examples----- Input 42 23454 Output 2 Input 169 12118999 Output 1 -----Note----- This problem contains very weak pretests. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it. After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies. Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies). You have to answer $q$ independent queries. Let's see the following example: $[1, 3, 4]$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob — then Alice has $4$ candies, and Bob has $4$ candies. Another example is $[1, 10, 100]$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $54$ candies, and Alice takes $46$ candies. Now Bob has $55$ candies, and Alice has $56$ candies, so she has to discard one candy — and after that, she has $55$ candies too. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 1000$) — the number of queries. Then $q$ queries follow. The only line of the query contains three integers $a, b$ and $c$ ($1 \le a, b, c \le 10^{16}$) — the number of candies in the first, second and third piles correspondingly. -----Output----- Print $q$ lines. The $i$-th line should contain the answer for the $i$-th query — the maximum number of candies Alice can have after the division, if both Alice and Bob act optimally (of course, Bob will have the same number of candies). -----Example----- Input 4 1 3 4 1 10 100 10000000000000000 10000000000000000 10000000000000000 23 34 45 Output 4 55 15000000000000000 51 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. JavaScript provides a built-in parseInt method. It can be used like this: - `parseInt("10")` returns `10` - `parseInt("10 apples")` also returns `10` We would like it to return `"NaN"` (as a string) for the second case because the input string is not a valid number. You are asked to write a `myParseInt` method with the following rules: - It should make the conversion if the given string only contains a single integer value (and possibly spaces - including tabs, line feeds... - at both ends) - For all other strings (including the ones representing float values), it should return NaN - It should assume that all numbers are not signed and written in base 10 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A little girl loves problems on bitwise operations very much. Here's one of them. You are given two integers l and r. Let's consider the values of $a \oplus b$ for all pairs of integers a and b (l ≤ a ≤ b ≤ r). Your task is to find the maximum value among all considered ones. Expression $x \oplus y$ means applying bitwise excluding or operation to integers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is represented as "^", in Pascal — as «xor». -----Input----- The single line contains space-separated integers l and r (1 ≤ l ≤ r ≤ 10^18). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Output----- In a single line print a single integer — the maximum value of $a \oplus b$ for all pairs of integers a, b (l ≤ a ≤ b ≤ r). -----Examples----- Input 1 2 Output 3 Input 8 16 Output 31 Input 1 1 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are N people standing in a queue from west to east. Given is a string S of length N representing the directions of the people. The i-th person from the west is facing west if the i-th character of S is L, and east if that character of S is R. A person is happy if the person in front of him/her is facing the same direction. If no person is standing in front of a person, however, he/she is not happy. You can perform the following operation any number of times between 0 and K (inclusive): Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa. What is the maximum possible number of happy people you can have? -----Constraints----- - N is an integer satisfying 1 \leq N \leq 10^5. - K is an integer satisfying 1 \leq K \leq 10^5. - |S| = N - Each character of S is L or R. -----Input----- Input is given from Standard Input in the following format: N K S -----Output----- Print the maximum possible number of happy people after at most K operations. -----Sample Input----- 6 1 LRLRRL -----Sample Output----- 3 If we choose (l, r) = (2, 5), we have LLLRLL, where the 2-nd, 3-rd, and 6-th persons from the west are happy. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In this Kata, you will be given a string and your task will be to return the length of the longest prefix that is also a suffix. A prefix is the start of a string while the suffix is the end of a string. For instance, the prefixes of the string `"abcd"` are `["a","ab","abc"]`. The suffixes are `["bcd", "cd", "d"]`. You should not overlap the prefix and suffix. ```Haskell for example: solve("abcd") = 0, because no prefix == suffix. solve("abcda") = 1, because the longest prefix which == suffix is "a". solve("abcdabc") = 3. Longest prefix which == suffix is "abc". solve("aaaa") = 2. Longest prefix which == suffix is "aa". You should not overlap the prefix and suffix solve("aa") = 1. You should not overlap the prefix and suffix. solve("a") = 0. You should not overlap the prefix and suffix. ``` All strings will be lowercase and string lengths are `1 <= length <= 500` More examples in test cases. Good luck! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p_1, p_2, ..., p_{n} for his birthday. Jeff hates inversions in sequences. An inversion in sequence a_1, a_2, ..., a_{n} is a pair of indexes i, j (1 ≤ i < j ≤ n), such that an inequality a_{i} > a_{j} holds. Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get. -----Input----- The first line contains integer n (1 ≤ n ≤ 2000). The next line contains n integers — sequence p_1, p_2, ..., p_{n} (|p_{i}| ≤ 10^5). The numbers are separated by spaces. -----Output----- In a single line print the answer to the problem — the minimum number of inversions Jeff can get. -----Examples----- Input 2 2 1 Output 0 Input 9 -2 0 -1 0 -1 2 1 0 -1 Output 6 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function `count_vowels` to count the number of vowels in a given string. ### Notes: - Return `nil` or `None` for non-string inputs. - Return `0` if the parameter is omitted. ### Examples: ```python count_vowels("abcdefg") => 2 count_vowels("aAbcdeEfg") => 4 count_vowels(12) => None ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Give the summation of all even numbers in a Fibonacci sequence up to, but not including, the maximum value. The Fibonacci sequence is a series of numbers where the next value is the addition of the previous two values. The series starts with 0 and 1: 0 1 1 2 3 5 8 13 21... For example: ```python eve_fib(0)==0 eve_fib(33)==10 eve_fib(25997544)==19544084 ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. From beginning till end, this message has been waiting to be conveyed. For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times: * Remove any two elements s and t from the set, and add their concatenation s + t to the set. The cost of such operation is defined to be <image>, where f(s, c) denotes the number of times character c appears in string s. Given a non-negative integer k, construct any valid non-empty set of no more than 100 000 letters, such that the minimum accumulative cost of the whole process is exactly k. It can be shown that a solution always exists. Input The first and only line of input contains a non-negative integer k (0 ≤ k ≤ 100 000) — the required minimum cost. Output Output a non-empty string of no more than 100 000 lowercase English letters — any multiset satisfying the requirements, concatenated to be a string. Note that the printed string doesn't need to be the final concatenated string. It only needs to represent an unordered multiset of letters. Examples Input 12 Output abababab Input 3 Output codeforces Note For the multiset {'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'}, one of the ways to complete the process is as follows: * {"ab", "a", "b", "a", "b", "a", "b"}, with a cost of 0; * {"aba", "b", "a", "b", "a", "b"}, with a cost of 1; * {"abab", "a", "b", "a", "b"}, with a cost of 1; * {"abab", "ab", "a", "b"}, with a cost of 0; * {"abab", "aba", "b"}, with a cost of 1; * {"abab", "abab"}, with a cost of 1; * {"abababab"}, with a cost of 8. The total cost is 12, and it can be proved to be the minimum cost of the process. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. LiLand is a country, consisting of n cities. The cities are numbered from 1 to n. The country is well known because it has a very strange transportation system. There are many one-way flights that make it possible to travel between the cities, but the flights are arranged in a way that once you leave a city you will never be able to return to that city again. Previously each flight took exactly one hour, but recently Lily has become the new manager of transportation system and she wants to change the duration of some flights. Specifically, she wants to change the duration of some flights to exactly 2 hours in such a way that all trips from city 1 to city n take the same time regardless of their path. Your task is to help Lily to change the duration of flights. Input First line of the input contains two integer numbers n and m (2 ≤ n ≤ 1000; 1 ≤ m ≤ 5000) specifying the number of cities and the number of flights. Each of the next m lines contains two integers ai and bi (1 ≤ ai < bi ≤ n) specifying a one-directional flight from city ai to city bi. It is guaranteed that there exists a way to travel from city number 1 to city number n using the given flights. It is guaranteed that there is no sequence of flights that forms a cyclical path and no two flights are between the same pair of cities. Output If it is impossible for Lily to do her task, print "No" (without quotes) on the only line of the output. Otherwise print "Yes" (without quotes) on the first line of output, then print an integer ansi (1 ≤ ansi ≤ 2) to each of the next m lines being the duration of flights in new transportation system. You should print these numbers in the order that flights are given in the input. If there are multiple solutions for the input, output any of them. Examples Input 3 3 1 2 2 3 1 3 Output Yes 1 1 2 Input 4 4 1 2 2 3 3 4 1 4 Output No Input 5 6 1 2 2 3 3 5 1 4 4 5 1 3 Output Yes 1 1 1 2 1 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You get a new job working for Eggman Movers. Your first task is to write a method that will allow the admin staff to enter a person’s name and return what that person's role is in the company. You will be given an array of object literals holding the current employees of the company. You code must find the employee with the matching firstName and lastName and then return the role for that employee or if no employee is not found it should return "Does not work here!" The array is preloaded and can be referenced using the variable `employees` (`$employees` in Ruby). It uses the following structure. ```python employees = [ {'first_name': "Dipper", 'last_name': "Pines", 'role': "Boss"}, ...... ] ``` There are no duplicate names in the array and the name passed in will be a single string with a space between the first and last name i.e. Jane Doe or just a name. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides. Input The first line of the input data contains numbers n and m (1 ≤ n, m ≤ 50), n — amount of lines, and m — amount of columns on Bob's sheet. The following n lines contain m characters each. Character «.» stands for a non-shaded square on the sheet, and «*» — for a shaded square. It is guaranteed that Bob has shaded at least one square. Output Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better. Examples Input 6 7 ....... ..***.. ..*.... ..***.. ..*.... ..***.. Output *** *.. *** *.. *** Input 3 3 *** *.* *** Output *** *.* *** Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high. At the beginning of the first experiment there is a single bacterium in the test tube. Every second each bacterium in the test tube divides itself into k bacteria. After that some abnormal effects create b more bacteria in the test tube. Thus, if at the beginning of some second the test tube had x bacteria, then at the end of the second it will have kx + b bacteria. The experiment showed that after n seconds there were exactly z bacteria and the experiment ended at this point. For the second experiment Qwerty is going to sterilize the test tube and put there t bacteria. He hasn't started the experiment yet but he already wonders, how many seconds he will need to grow at least z bacteria. The ranger thinks that the bacteria will divide by the same rule as in the first experiment. Help Qwerty and find the minimum number of seconds needed to get a tube with at least z bacteria in the second experiment. Input The first line contains four space-separated integers k, b, n and t (1 ≤ k, b, n, t ≤ 106) — the parameters of bacterial growth, the time Qwerty needed to grow z bacteria in the first experiment and the initial number of bacteria in the second experiment, correspondingly. Output Print a single number — the minimum number of seconds Qwerty needs to grow at least z bacteria in the tube. Examples Input 3 1 3 5 Output 2 Input 1 4 4 7 Output 3 Input 2 2 4 100 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. 12:17 (UTC): The sample input 1 and 2 were swapped. The error is now fixed. We are very sorry for your inconvenience. There are N children in AtCoder Kindergarten, conveniently numbered 1 through N. Mr. Evi will distribute C indistinguishable candies to the children. If child i is given a candies, the child's happiness will become x_i^a, where x_i is the child's excitement level. The activity level of the kindergarten is the product of the happiness of all the N children. For each possible way to distribute C candies to the children by giving zero or more candies to each child, calculate the activity level of the kindergarten. Then, calculate the sum over all possible way to distribute C candies. This sum can be seen as a function of the children's excitement levels x_1,..,x_N, thus we call it f(x_1,..,x_N). You are given integers A_i,B_i (1≦i≦N). Find modulo 10^9+7. -----Constraints----- - 1≦N≦400 - 1≦C≦400 - 1≦A_i≦B_i≦400 (1≦i≦N) -----Partial Score----- - 400 points will be awarded for passing the test set satisfying A_i=B_i (1≦i≦N). -----Input----- The input is given from Standard Input in the following format: N C A_1 A_2 ... A_N B_1 B_2 ... B_N -----Output----- Print the value of modulo 10^9+7. -----Sample Input----- 2 3 1 1 1 1 -----Sample Output----- 4 This case is included in the test set for the partial score, since A_i=B_i. We only have to consider the sum of the activity level of the kindergarten where the excitement level of both child 1 and child 2 are 1 (f(1,1)). - If child 1 is given 0 candy, and child 2 is given 3 candies, the activity level of the kindergarten is 1^0*1^3=1. - If child 1 is given 1 candy, and child 2 is given 2 candies, the activity level of the kindergarten is 1^1*1^2=1. - If child 1 is given 2 candies, and child 2 is given 1 candy, the activity level of the kindergarten is 1^2*1^1=1. - If child 1 is given 3 candies, and child 2 is given 0 candy, the activity level of the kindergarten is 1^3*1^0=1. Thus, f(1,1)=1+1+1+1=4, and the sum over all f is also 4. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. After learning about polynomial hashing, Heidi decided to learn about shift-xor hashing. In particular, she came across this interesting problem. Given a bitstring $y \in \{0,1\}^n$ find out the number of different $k$ ($0 \leq k < n$) such that there exists $x \in \{0,1\}^n$ for which $y = x \oplus \mbox{shift}^k(x).$ In the above, $\oplus$ is the xor operation and $\mbox{shift}^k$ is the operation of shifting a bitstring cyclically to the right $k$ times. For example, $001 \oplus 111 = 110$ and $\mbox{shift}^3(00010010111000) = 00000010010111$. -----Input----- The first line contains an integer $n$ ($1 \leq n \leq 2 \cdot 10^5$), the length of the bitstring $y$. The second line contains the bitstring $y$. -----Output----- Output a single integer: the number of suitable values of $k$. -----Example----- Input 4 1010 Output 3 -----Note----- In the first example: $1100\oplus \mbox{shift}^1(1100) = 1010$ $1000\oplus \mbox{shift}^2(1000) = 1010$ $0110\oplus \mbox{shift}^3(0110) = 1010$ There is no $x$ such that $x \oplus x = 1010$, hence the answer is $3$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor. To begin with friends learned the rules: in the race there are n sections of equal length and m participants. The participants numbered from 1 to m. About each participant the following is known: * li — the number of the starting section, * ri — the number of the finishing section (li ≤ ri), * ti — the time a biathlete needs to complete an section of the path, * ci — the profit in roubles. If the i-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman. The i-th biathlete passes the sections from li to ri inclusive. The competitor runs the whole way in (ri - li + 1)·ti time units. It takes him exactly ti time units to pass each section. In case of the athlete's victory on k sections the man who has betted on him receives k·ci roubles. In each section the winner is determined independently as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed. We should also add that Nikita can bet on each section and on any contestant running in this section. Help the friends find the maximum possible profit. Input The first line contains two integers n and m (1 ≤ n, m ≤ 100). Then follow m lines, each containing 4 integers li, ri, ti, ci (1 ≤ li ≤ ri ≤ n, 1 ≤ ti, ci ≤ 1000). Output Print a single integer, the maximal profit in roubles that the friends can get. In each of n sections it is not allowed to place bets on more than one sportsman. Examples Input 4 4 1 4 20 5 1 3 21 10 3 3 4 30 3 4 4 20 Output 60 Input 8 4 1 5 24 10 2 4 6 15 4 6 30 50 6 7 4 20 Output 105 Note In the first test the optimal bet is: in the 1-2 sections on biathlete 1, in section 3 on biathlete 3, in section 4 on biathlete 4. Total: profit of 5 rubles for 1 section, the profit of 5 rubles for 2 section, profit of 30 rubles for a 3 section, profit of 20 rubles for 4 section. Total profit 60 rubles. In the second test the optimal bet is: on 1 and 5 sections on biathlete 1, in the 2-4 sections on biathlete 2, in the 6-7 sections on athlete 4. There is no winner in the 8 section. Total: profit of 10 rubles for 1 section, the profit of 15 rubles for 2,3,4 section, profit of 10 rubles for a 5 section, profit of 20 rubles for 6, 7 section. Total profit 105 rubles. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. Grapes of Coderpur are very famous. Devu went to the market and saw that there were N people selling grapes. He didn’t like it because things were not very structured. So, he gave a task to Dhinwa to make things better. If Dhinwa successfully completes the task, Devu will be happy. Devu wants to change the number of grapes in a bucket of zero or more sellers in such a way that the GCD of all the number of grapes is divisible by K. Dhinwa can add or remove any number of grapes from each of the buckets. Adding or removing a grape will be counted as an operation. Also after the operation, none of the seller’s bucket should be empty. Help Dhinwa in finding the minimum number of operations needed to make Devu happy. ------ Input ------ First line of input contains an integer T denoting the number of test cases. For each test case, first line will contain an integer N denoting the number of buckets and integer K. Next line contains N space separated integers denoting the number of grapes in each of the bucket. ------ Output ------ For each test case, print a single integer representing the answer of that test case. ------ Constraints ------ Subtask #1: 10 points $1 ≤ T ≤ 10, 1 ≤ N ,K ≤ 10, 1 ≤ number of grapes in a bucket ≤ 10$ Subtask #2: 10 points $1 ≤ T ≤ 10, 1 ≤ N,K ≤ 100, 1 ≤ number of grapes in a bucket ≤ 100$ Subtask #3: 80 points $1 ≤ T ≤ 10, 1 ≤ N ≤ 10^{5}, 1 ≤ K ≤ 10^{9}, 1 number of grapes in a bucket ≤ 10^{9} $ ----- Sample Input 1 ------ 2 2 2 3 5 3 7 10 16 18 ----- Sample Output 1 ------ 2 8 ----- explanation 1 ------ For the first test case, add or remove 1 grape in each of the bucket. For the second test case, remove three grapes in the first bucket, remove two grapes from the second bucket and add three grapes in the third bucket. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address (vasya@gmail.com). It is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots. You have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result. Overall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at. Input The first line contains the email address description. It is guaranteed that that is a proper email address with all the dots replaced by dot an the at signs replaced by at. The line is not empty and its length does not exceed 100 symbols. Output Print the shortest email address, from which the given line could be made by the described above replacements. If there are several solutions to that problem, print the lexicographically minimal one (the lexicographical comparison of the lines are implemented with an operator < in modern programming languages). In the ASCII table the symbols go in this order: . @ ab...z Examples Input vasyaatgmaildotcom Output vasya@gmail.com Input dotdotdotatdotdotat Output dot..@..at Input aatt Output a@t Read the inputs from stdin solve the problem and write the answer to stdout (do 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 strongness of an even number is the number of times we can successively divide by 2 until we reach an odd number starting with an even number n. For example, if n = 12, then * 12 / 2 = 6 * 6 / 2 = 3 So we divided successively 2 times and we reached 3, so the strongness of 12 is `2`. If n = 16 then * 16 / 2 = 8 * 8 / 2 = 4 * 4 / 2 = 2 * 2 / 2 = 1 we divided successively 4 times and we reached 1, so the strongness of 16 is `4` # Task Given a closed interval `[n, m]`, return the even number that is the strongest in the interval. If multiple solutions exist return the smallest strongest even number. Note that programs must run within the allotted server time; a naive solution will probably time out. # Constraints ```if-not:ruby 1 <= n < m <= INT_MAX ``` ```if:ruby 1 <= n < m <= 2^64 ``` # Examples ``` [1, 2] --> 2 # 1 has strongness 0, 2 has strongness 1 [5, 10] --> 8 # 5, 7, 9 have strongness 0; 6, 10 have strongness 1; 8 has strongness 3 [48, 56] --> 48 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Problem statement AOR Ika-chan is in a bad mood lately. Apparently, I don't like the ratio of the number of followers to the number of followers of "Ikatta". Currently, AOR Ika-chan has $ A $ followers, $ B $ followers, and a ratio of $ A: B $. Therefore, AOR Ika decided to increase or decrease the number of followers so that the ratio of the number of followers to the number of followers would be an integer ratio that she liked. The integer ratio I like is a ratio that can be expressed so that both values ​​included in the ratio are integers of $ 1 $ or more and $ N $ or less. However, AOR Ika doesn't want to change the number of followers as much as possible, so I want to make the absolute value of the difference from before the change as small as possible. Create a program that asks at least how many followers you need to change to make AOR Ika feel good. Input constraints $ 1 \ le A, \ B \ le 10 ^ {12} $ $ 1 \ leq N \ leq 100 $ sample Sample input 1 19 30 3 Sample output 1 1 Sample input 2 3 7 7 Sample output 2 0 Sample input 3 3 7 1 Sample output 3 Four Sample input 4 102 30 3 Sample output 4 12 By reducing the number of followers by $ 12 $, it becomes $ 90: 30 \ (= 3: 1) $, and the higher ratio number is $ 3 $ or less. At this time, the amount of change is $ 12 $. Sample input 5 3 4 2 Sample output 5 1 If you unfollow one person, it will be $ 2: 4 \ (= 1: 2) $, and if you follow it, it will be $ 4: 4 \ (= 1: 1) $. In both cases, the absolute value of increase / decrease is $ 1 $, which is the answer. Sample input 6 1 100 2 Sample output 6 49 Please note that at least $ 1 $ people must be following. input $ A \ B \ N $ output Output the minimum absolute value of the amount of change in $ A $, which can be an integer ratio you like. Example Input 19 30 3 Output 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This is the hard version of the problem. The only difference between the two versions is the constraint on n. You can make hacks only if all versions of the problem are solved. A forest is an undirected graph without cycles (not necessarily connected). Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from 1 to n, and they would like to add edges to their forests such that: * After adding edges, both of their graphs are still forests. * They add the same edges. That is, if an edge (u, v) is added to Mocha's forest, then an edge (u, v) is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add. Input The first line contains three integers n, m_1 and m_2 (1 ≤ n ≤ 10^5, 0 ≤ m_1, m_2 < n) — the number of nodes and the number of initial edges in Mocha's forest and Diana's forest. Each of the next m_1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the edges in Mocha's forest. Each of the next m_2 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the edges in Diana's forest. Output The first line contains only one integer h, the maximum number of edges Mocha and Diana can add. Each of the next h lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the edge you add each time. If there are multiple correct answers, you can print any one of them. Examples Input 3 2 2 1 2 2 3 1 2 1 3 Output 0 Input 5 3 2 5 4 2 1 4 3 4 3 1 4 Output 1 2 4 Input 8 1 2 1 7 2 6 1 5 Output 5 5 2 2 3 3 4 4 7 6 8 Note In the first example, we cannot add any edge. In the second example, the initial forests are as follows. <image> We can add an edge (2, 4). <image> Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a program which finds the greatest common divisor of two natural numbers a and b Hint You can use the following observation: For integers x and y, if x ≥ y, then gcd(x, y) = gcd(y, x%y) Constrants 1 ≤ a, b ≤ 109 Input a and b are given in a line sparated by a single space. Output Output the greatest common divisor of a and b. Examples Input 54 20 Output 2 Input 147 105 Output 21 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this: [Image] Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors. The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d_1, d_2, ..., d_{k} a cycle if and only if it meets the following condition: These k dots are different: if i ≠ j then d_{i} is different from d_{j}. k is at least 4. All dots belong to the same color. For all 1 ≤ i ≤ k - 1: d_{i} and d_{i} + 1 are adjacent. Also, d_{k} and d_1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field. -----Input----- The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter. -----Output----- Output "Yes" if there exists a cycle, and "No" otherwise. -----Examples----- Input 3 4 AAAA ABCA AAAA Output Yes Input 3 4 AAAA ABCA AADA Output No Input 4 4 YYYR BYBY BBBY BBBY Output Yes Input 7 6 AAAAAB ABBBAB ABAAAB ABABBB ABAAAB ABBBAB AAAAAB Output Yes Input 2 13 ABCDEFGHIJKLM NOPQRSTUVWXYZ Output No -----Note----- In first sample test all 'A' form a cycle. In second sample there is no such cycle. The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red). Read the inputs from stdin solve the problem and write the answer to stdout (do 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 can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by $1$; during the second operation you choose one of these numbers and increase it by $2$, and so on. You choose the number of these operations yourself. For example, if $a = 1$ and $b = 3$, you can perform the following sequence of three operations: add $1$ to $a$, then $a = 2$ and $b = 3$; add $2$ to $b$, then $a = 2$ and $b = 5$; add $3$ to $a$, then $a = 5$ and $b = 5$. Calculate the minimum number of operations required to make $a$ and $b$ equal. -----Input----- The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. The only line of each test case contains two integers $a$ and $b$ ($1 \le a, b \le 10^9$). -----Output----- For each test case print one integer — the minimum numbers of operations required to make $a$ and $b$ equal. -----Example----- Input 3 1 3 11 11 30 20 Output 3 0 4 -----Note----- First test case considered in the statement. In the second test case integers $a$ and $b$ are already equal, so you don't need to perform any operations. In the third test case you have to apply the first, the second, the third and the fourth operation to $b$ ($b$ turns into $20 + 1 + 2 + 3 + 4 = 30$). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages. Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Some days are so busy that Petr will have no time to read whatsoever. However, we know that he will be able to read at least one page a week. Assuming that Petr will not skip days and will read as much as he can every day, determine on which day of the week he will read the last page of the book. Input The first input line contains the single integer n (1 ≤ n ≤ 1000) — the number of pages in the book. The second line contains seven non-negative space-separated integers that do not exceed 1000 — those integers represent how many pages Petr can read on Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday correspondingly. It is guaranteed that at least one of those numbers is larger than zero. Output Print a single number — the number of the day of the week, when Petr will finish reading the book. The days of the week are numbered starting with one in the natural order: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday. Examples Input 100 15 20 20 15 10 30 45 Output 6 Input 2 1 0 0 0 0 0 0 Output 1 Note Note to the first sample: By the end of Monday and therefore, by the beginning of Tuesday Petr has 85 pages left. He has 65 pages left by Wednesday, 45 by Thursday, 30 by Friday, 20 by Saturday and on Saturday Petr finishes reading the book (and he also has time to read 10 pages of something else). Note to the second sample: On Monday of the first week Petr will read the first page. On Monday of the second week Petr will read the second page and will finish reading the book. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. Input The first line contains two space-separated integers x1, y1 ( - 106 ≤ x1, y1 ≤ 106) — the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≤ x2, y2 ≤ 106) — the coordinates of the university you are studying at. The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≤ ai, bi, ci ≤ 106; |ai| + |bi| > 0) — the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). Output Output the answer to the problem. Examples Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 Note Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): <image> <image> Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor. On the current level, the hero is facing $n$ caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave $i$, he will have to fight $k_i$ monsters in a row: first a monster with armor $a_{i, 1}$, then a monster with armor $a_{i, 2}$ and so on, finally, a monster with armor $a_{i, k_i}$. The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order. Each time the hero beats a monster, the hero's power increases by $1$. Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^5$). Description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) — the number of caves. The $i$-th of the next $n$ lines contains an integer $k_i$ ($1 \le k_i \le 10^5$) — the number of monsters in the $i$-th cave, followed by $k_i$ integers $a_{i, 1}, a_{i, 2}, \ldots, a_{i, k_i}$ ($1 \le a_{i, j} \le 10^9$) — armor levels of the monsters in cave $i$ in order the hero has to fight them. It is guaranteed that the sum of $k_i$ over all test cases does not exceed $10^5$. -----Output----- For each test case print a single integer — the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters. -----Examples----- Input 2 1 1 42 2 3 10 15 8 2 12 11 Output 43 13 -----Note----- In the first test case, the hero has to beat a single monster with armor $42$, it's enough to have power $43$ to achieve that. In the second test case, the hero can pass the level with initial power $13$ as follows: enter cave $2$: beat a monster with armor $12$, power increases to $14$; beat a monster with armor $11$, power increases to $15$; enter cave $1$: beat a monster with armor $10$, power increases to $16$; beat a monster with armor $15$, power increases to $17$; beat a monster with armor $8$, power increases to $18$. Read the inputs from stdin solve the problem and write the answer to stdout (do 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. Chanek wants to knit a batik, a traditional cloth from Indonesia. The cloth forms a grid a with size n × m. There are k colors, and each cell in the grid can be one of the k colors. Define a sub-rectangle as an ordered pair of two cells ((x_1, y_1), (x_2, y_2)), denoting the top-left cell and bottom-right cell (inclusively) of a sub-rectangle in a. Two sub-rectangles ((x_1, y_1), (x_2, y_2)) and ((x_3, y_3), (x_4, y_4)) have the same pattern if and only if the following holds: * they have the same width (x_2 - x_1 = x_4 - x_3); * they have the same height (y_2 - y_1 = y_4 - y_3); * for every pair (i, j) where 0 ≤ i ≤ x_2 - x_1 and 0 ≤ j ≤ y_2 - y_1, the color of cells (x_1 + i, y_1 + j) and (x_3 + i, y_3 + j) are equal. Count the number of possible batik color combinations, such that the subrectangles ((a_x, a_y),(a_x + r - 1, a_y + c - 1)) and ((b_x, b_y),(b_x + r - 1, b_y + c - 1)) have the same pattern. Output the answer modulo 10^9 + 7. Input The first line contains five integers n, m, k, r, and c (1 ≤ n, m ≤ 10^9, 1 ≤ k ≤ 10^9, 1 ≤ r ≤ min(10^6, n), 1 ≤ c ≤ min(10^6, m)) — the size of the batik, the number of colors, and size of the sub-rectangle. The second line contains four integers a_x, a_y, b_x, and b_y (1 ≤ a_x, b_x ≤ n, 1 ≤ a_y, b_y ≤ m) — the top-left corners of the first and second sub-rectangle. Both of the sub-rectangles given are inside the grid (1 ≤ a_x + r - 1, b_x + r - 1 ≤ n, 1 ≤ a_y + c - 1, b_y + c - 1 ≤ m). Output Output an integer denoting the number of possible batik color combinations modulo 10^9 + 7. Examples Input 3 3 2 2 2 1 1 2 2 Output 32 Input 4 5 170845 2 2 1 4 3 1 Output 756680455 Note The following are all 32 possible color combinations in the first example. <image> Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya has his favourite number $n$. He wants to split it to some non-zero digits. It means, that he wants to choose some digits $d_1, d_2, \ldots, d_k$, such that $1 \leq d_i \leq 9$ for all $i$ and $d_1 + d_2 + \ldots + d_k = n$. Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different digits among $d_1, d_2, \ldots, d_k$. Help him! -----Input----- The first line contains a single integer $n$ — the number that Vasya wants to split ($1 \leq n \leq 1000$). -----Output----- In the first line print one integer $k$ — the number of digits in the partition. Note that $k$ must satisfy the inequality $1 \leq k \leq n$. In the next line print $k$ digits $d_1, d_2, \ldots, d_k$ separated by spaces. All digits must satisfy the inequalities $1 \leq d_i \leq 9$. You should find a partition of $n$ in which the number of different digits among $d_1, d_2, \ldots, d_k$ will be minimal possible among all partitions of $n$ into non-zero digits. Among such partitions, it is allowed to find any. It is guaranteed that there exists at least one partition of the number $n$ into digits. -----Examples----- Input 1 Output 1 1 Input 4 Output 2 2 2 Input 27 Output 3 9 9 9 -----Note----- In the first test, the number $1$ can be divided into $1$ digit equal to $1$. In the second test, there are $3$ partitions of the number $4$ into digits in which the number of different digits is $1$. This partitions are $[1, 1, 1, 1]$, $[2, 2]$ and $[4]$. Any of these partitions can be found. And, for example, dividing the number $4$ to the digits $[1, 1, 2]$ isn't an answer, because it has $2$ different digits, that isn't the minimum possible number. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step. Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n. Input The input contains the only integer n (1 ≤ n ≤ 106). Output Print the only integer k. Examples Input 5 Output 3 Input 1 Output 0 Note The pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1) → (1,2) → (3,2) → (5,2). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with. String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab". Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him. Input The first input line contains a non-empty string s1. The second input line contains a non-empty string s2. Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters. Output Print the number of common divisors of strings s1 and s2. Examples Input abcdabcd abcdabcdabcdabcd Output 2 Input aaa aa Output 1 Note In first sample the common divisors are strings "abcd" and "abcdabcd". In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa". Read the inputs from stdin solve the problem and write the answer to stdout (do 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 some animals in a garden. Each of them is a crane with two legs or a turtle with four legs. Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct. -----Constraints----- - 1 \leq X \leq 100 - 1 \leq Y \leq 100 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: X Y -----Output----- If there is a combination of numbers of cranes and turtles in which the statement is correct, print Yes; otherwise, print No. -----Sample Input----- 3 8 -----Sample Output----- Yes The statement "there are 3 animals in total in the garden, and they have 8 legs in total" is correct if there are two cranes and one turtle. Thus, there is a combination of numbers of cranes and turtles in which the statement is correct. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not. A permutation triple of permutations of length n (a, b, c) is called a Lucky Permutation Triple if and only if <image>. The sign ai denotes the i-th element of permutation a. The modular equality described above denotes that the remainders after dividing ai + bi by n and dividing ci by n are equal. Now, he has an integer n and wants to find a Lucky Permutation Triple. Could you please help him? Input The first line contains a single integer n (1 ≤ n ≤ 105). Output If no Lucky Permutation Triple of length n exists print -1. Otherwise, you need to print three lines. Each line contains n space-seperated integers. The first line must contain permutation a, the second line — permutation b, the third — permutation c. If there are multiple solutions, print any of them. Examples Input 5 Output 1 4 3 2 0 1 0 2 4 3 2 4 0 1 3 Input 2 Output -1 Note In Sample 1, the permutation triple ([1, 4, 3, 2, 0], [1, 0, 2, 4, 3], [2, 4, 0, 1, 3]) is Lucky Permutation Triple, as following holds: * <image>; * <image>; * <image>; * <image>; * <image>. In Sample 2, you can easily notice that no lucky permutation triple exists. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Petya often visits his grandmother in the countryside. The grandmother has a large vertical garden, which can be represented as a set of `n` rectangles of varying height. Due to the newest irrigation system we can create artificial rain above them. Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. The water will then flow to the neighbouring sections but only if each of their heights does not exceed the height of the previous watered section. ___ ## Example: Let's say there's a garden consisting of 5 rectangular sections of heights `4, 2, 3, 3, 2`. Creating the artificial rain over the left-most section is inefficient as the water **WILL FLOW DOWN** to the section with the height of `2`, but it **WILL NOT FLOW UP** to the section with the height of `3` from there. Only 2 sections will be covered: `4, 2`. The most optimal choice will be either of the sections with the height of `3` because the water will flow to its neighbours covering 4 sections altogether: `2, 3, 3, 2`. You can see this process in the following illustration: ___ As Petya is keen on programming, he decided to find such section that if we create artificial rain above it, the number of watered sections will be maximal. ## Output: The maximal number of watered sections if we create artificial rain above exactly one section. **Note: performance will be tested.** Read the inputs from stdin solve the problem and write the answer to stdout (do 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 flea is sitting at one of the n hassocks, arranged in a circle, at the moment. After minute number k the flea jumps through k - 1 hassoсks (clockwise). For example, after the first minute the flea jumps to the neighboring hassock. You should answer: will the flea visit all the hassocks or not. We assume that flea has infinitely much time for this jumping. Input The only line contains single integer: 1 ≤ n ≤ 1000 — number of hassocks. Output Output "YES" if all the hassocks will be visited and "NO" otherwise. Examples Input 1 Output YES Input 3 Output NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. D: Is greed the best? story In Japan, where there are 1, 5, 10, 50, 100, 500 yen coins, it is known that the number of coins can be minimized by using as many coins as possible when paying a certain amount. .. If the amount of coins is different from that of Japan, it is not always possible to minimize it by paying greedily. What are the conditions that the amount of coins must meet in order to be optimally paid greedily? problem TAB was curious about the above, so I decided to first consider the case where there are only three types of coins, 1, A and B. Since A and B are given, output the smallest amount of money that will not minimize the number of sheets if you pay greedily. Also, if the greedy algorithm is optimal for any amount of money, output -1. Input format A B Constraint * 1 <A \ leq 10 ^ 5 * A <B \ leq 10 ^ 9 Input example 1 4 6 Output example 1 8 If you greedily pay 8 yen, you will pay 6 + 1 \ times 2 for a total of 3 cards, but you can pay 4 \ times 2 for a total of 2 cards. Input example 2 2 1000000000 Output example 2 -1 It is best to greedily pay any amount. Example Input 4 6 Output 8 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is a_{i} meters high. Vladimir has just planted n bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing. Vladimir wants to check the bamboos each d days (i.e. d days after he planted, then after 2d days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than k meters. What is the maximum value d he can choose so that he can achieve what he wants without cutting off more than k meters of bamboo? -----Input----- The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^11) — the number of bamboos and the maximum total length of cut parts, in meters. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the required heights of bamboos, in meters. -----Output----- Print a single integer — the maximum value of d such that Vladimir can reach his goal. -----Examples----- Input 3 4 1 3 5 Output 3 Input 3 40 10 30 50 Output 32 -----Note----- In the first example Vladimir can check bamboos each 3 days. Then he will cut the first and the second bamboos after 3 days, and the third bamboo after 6 days. The total length of cut parts is 2 + 0 + 1 = 3 meters. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.) Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn? (We assume that there are six kinds of coins available: 500-yen, 100-yen, 50-yen, 10-yen, 5-yen, and 1-yen coins.) -----Constraints----- - 0 \leq X \leq 10^9 - X is an integer. -----Input----- Input is given from Standard Input in the following format: X -----Output----- Print the maximum number of happiness points that can be earned. -----Sample Input----- 1024 -----Sample Output----- 2020 By exchanging his money so that he gets two 500-yen coins and four 5-yen coins, he gains 2020 happiness points, which is the maximum number of happiness points that can be earned. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same. The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him. Input The first line of the input contains four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks. Output Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length. Examples Input 4 2 1 3 Output TRIANGLE Input 7 2 2 4 Output SEGMENT Input 3 5 9 1 Output IMPOSSIBLE Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Paul is at the orchestra. The string section is arranged in an r × c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take. Two pictures are considered to be different if the coordinates of corresponding rectangles are different. Input The first line of input contains four space-separated integers r, c, n, k (1 ≤ r, c, n ≤ 3000, 1 ≤ k ≤ min(n, 10)) — the number of rows and columns of the string section, the total number of violas, and the minimum number of violas Paul would like in his photograph, respectively. The next n lines each contain two integers xi and yi (1 ≤ xi ≤ r, 1 ≤ yi ≤ c): the position of the i-th viola. It is guaranteed that no location appears more than once in the input. Output Print a single integer — the number of photographs Paul can take which include at least k violas. Examples Input 2 2 1 1 1 2 Output 4 Input 3 2 3 3 1 1 3 1 2 2 Output 1 Input 3 2 3 2 1 1 3 1 2 2 Output 4 Note We will use '*' to denote violinists and '#' to denote violists. In the first sample, the orchestra looks as follows: *# ** Paul can take a photograph of just the viola, the 1 × 2 column containing the viola, the 2 × 1 row containing the viola, or the entire string section, for 4 pictures total. In the second sample, the orchestra looks as follows: #* *# #* Paul must take a photograph of the entire section. In the third sample, the orchestra looks the same as in the second sample. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 came to the exhibition and one exhibit has drawn your attention. It consists of $n$ stacks of blocks, where the $i$-th stack consists of $a_i$ blocks resting on the surface. The height of the exhibit is equal to $m$. Consequently, the number of blocks in each stack is less than or equal to $m$. There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks.$\text{Top View}$ Find the maximum number of blocks you can remove such that the views for both the cameras would not change. Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either. -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n \le 100\,000$, $1 \le m \le 10^9$) — the number of stacks and the height of the exhibit. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le m$) — the number of blocks in each stack from left to right. -----Output----- Print exactly one integer — the maximum number of blocks that can be removed. -----Examples----- Input 5 6 3 3 3 3 3 Output 10 Input 3 5 1 2 4 Output 3 Input 5 5 2 3 1 4 4 Output 9 Input 1 1000 548 Output 0 Input 3 3 3 1 1 Output 1 -----Note----- The following pictures illustrate the first example and its possible solution. Blue cells indicate removed blocks. There are $10$ blue cells, so the answer is $10$.[Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two positive integers N and K. How many multisets of rational numbers satisfy all of the following conditions? - The multiset has exactly N elements and the sum of them is equal to K. - Each element of the multiset is one of 1, \frac{1}{2}, \frac{1}{4}, \frac{1}{8}, \dots. In other words, each element can be represented as \frac{1}{2^i}\ (i = 0,1,\dots). The answer may be large, so print it modulo 998244353. -----Constraints----- - 1 \leq K \leq N \leq 3000 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N K -----Output----- Print the number of multisets of rational numbers that satisfy all of the given conditions modulo 998244353. -----Sample Input----- 4 2 -----Sample Output----- 2 The following two multisets satisfy all of the given conditions: - {1, \frac{1}{2}, \frac{1}{4}, \frac{1}{4}} - {\frac{1}{2}, \frac{1}{2}, \frac{1}{2}, \frac{1}{2}} Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This is the easy version of the problem. The only difference between easy and hard versions is the constraint of $m$. You can make hacks only if both versions are solved. Chiori loves dolls and now she is going to decorate her bedroom![Image]  As a doll collector, Chiori has got $n$ dolls. The $i$-th doll has a non-negative integer value $a_i$ ($a_i < 2^m$, $m$ is given). Chiori wants to pick some (maybe zero) dolls for the decoration, so there are $2^n$ different picking ways. Let $x$ be the bitwise-xor-sum of values of dolls Chiori picks (in case Chiori picks no dolls $x = 0$). The value of this picking way is equal to the number of $1$-bits in the binary representation of $x$. More formally, it is also equal to the number of indices $0 \leq i < m$, such that $\left\lfloor \frac{x}{2^i} \right\rfloor$ is odd. Tell her the number of picking ways with value $i$ for each integer $i$ from $0$ to $m$. Due to the answers can be very huge, print them by modulo $998\,244\,353$. -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$, $0 \le m \le 35$)  — the number of dolls and the maximum value of the picking way. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i < 2^m$)  — the values of dolls. -----Output----- Print $m+1$ integers $p_0, p_1, \ldots, p_m$  — $p_i$ is equal to the number of picking ways with value $i$ by modulo $998\,244\,353$. -----Examples----- Input 4 4 3 5 8 14 Output 2 2 6 6 0 Input 6 7 11 45 14 9 19 81 Output 1 2 11 20 15 10 5 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In an attempt to control the rise in population, Archer was asked to come up with a plan. This time he is targeting marriages. Archer, being as intelligent as he is, came up with the following plan: A man with name M is allowed to marry a woman with name W, only if M is a subsequence of W or W is a subsequence of M. A is said to be a subsequence of B, if A can be obtained by deleting some elements of B without changing the order of the remaining elements. Your task is to determine whether a couple is allowed to marry or not, according to Archer's rule. ------ Input ------ The first line contains an integer T, the number of test cases. T test cases follow. Each test case contains two space separated strings M and W. ------ Output ------ For each test case print "YES" if they are allowed to marry, else print "NO". (quotes are meant for clarity, please don't print them) ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ |M|, |W| ≤ 25000 (|A| denotes the length of the string A.)$ $All names consist of lowercase English letters only.$ ----- Sample Input 1 ------ 3 john johanna ira ira kayla jayla ----- Sample Output 1 ------ YES YES NO ----- explanation 1 ------ Case 1: Consider S = "johanna". So, S[0] = 'j', S[1] = 'o', S[2] = 'h' and so on. If we remove the indices [3, 4, 6] or [3, 5, 6] from S, it becomes "john". Hence "john" is a subsequence of S, so the answer is "YES". Case 2: Any string is a subsequence of it self, as it is formed after removing "0" characters. Hence the answer is "YES". Case 3: "jayla" can not be attained from "kayla" as removing any character from "kayla" would make the string length smaller than "jayla", also there is no 'j' in "kayla". Similar reasoning can be applied to see why "kayla" can't be attained from "jayla". Hence the answer is "NO". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him. [Image] Thus, he came up with a puzzle to tell his mom his coordinates. His coordinates are the answer to the following problem. A string consisting only of parentheses ('(' and ')') is called a bracket sequence. Some bracket sequence are called correct bracket sequences. More formally: Empty string is a correct bracket sequence. if s is a correct bracket sequence, then (s) is also a correct bracket sequence. if s and t are correct bracket sequences, then st (concatenation of s and t) is also a correct bracket sequence. A string consisting of parentheses and question marks ('?') is called pretty if and only if there's a way to replace each question mark with either '(' or ')' such that the resulting string is a non-empty correct bracket sequence. Will gave his mom a string s consisting of parentheses and question marks (using Morse code through the lights) and his coordinates are the number of pairs of integers (l, r) such that 1 ≤ l ≤ r ≤ |s| and the string s_{l}s_{l} + 1... s_{r} is pretty, where s_{i} is i-th character of s. Joyce doesn't know anything about bracket sequences, so she asked for your help. -----Input----- The first and only line of input contains string s, consisting only of characters '(', ')' and '?' (2 ≤ |s| ≤ 5000). -----Output----- Print the answer to Will's puzzle in the first and only line of output. -----Examples----- Input ((?)) Output 4 Input ??()?? Output 7 -----Note----- For the first sample testcase, the pretty substrings of s are: "(?" which can be transformed to "()". "?)" which can be transformed to "()". "((?)" which can be transformed to "(())". "(?))" which can be transformed to "(())". For the second sample testcase, the pretty substrings of s are: "??" which can be transformed to "()". "()". "??()" which can be transformed to "()()". "?()?" which can be transformed to "(())". "??" which can be transformed to "()". "()??" which can be transformed to "()()". "??()??" which can be transformed to "()()()". Read the inputs from stdin solve the problem and write the answer to stdout (do 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 stardate is 1983, and Princess Heidi is getting better at detecting the Death Stars. This time, two Rebel spies have yet again given Heidi two maps with the possible locations of the Death Star. Since she got rid of all double agents last time, she knows that both maps are correct, and indeed show the map of the solar system that contains the Death Star. However, this time the Empire has hidden the Death Star very well, and Heidi needs to find a place that appears on both maps in order to detect the Death Star. The first map is an N × M grid, each cell of which shows some type of cosmic object that is present in the corresponding quadrant of space. The second map is an M × N grid. Heidi needs to align those two maps in such a way that they overlap over some M × M section in which all cosmic objects are identical. Help Heidi by identifying where such an M × M section lies within both maps. -----Input----- The first line of the input contains two space-separated integers N and M (1 ≤ N ≤ 2000, 1 ≤ M ≤ 200, M ≤ N). The next N lines each contain M lower-case Latin characters (a-z), denoting the first map. Different characters correspond to different cosmic object types. The next M lines each contain N characters, describing the second map in the same format. -----Output----- The only line of the output should contain two space-separated integers i and j, denoting that the section of size M × M in the first map that starts at the i-th row is equal to the section of the second map that starts at the j-th column. Rows and columns are numbered starting from 1. If there are several possible ways to align the maps, Heidi will be satisfied with any of those. It is guaranteed that a solution exists. -----Example----- Input 10 5 somer andom noise mayth eforc ebewi thyou hctwo again noise somermayth andomeforc noiseebewi againthyou noisehctwo Output 4 6 -----Note----- The 5-by-5 grid for the first test case looks like this: mayth eforc ebewi thyou hctwo Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Welcome to Rockport City! It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet $a$ dollars and Ronnie has bet $b$ dollars. But the fans seem to be disappointed. The excitement of the fans is given by $gcd(a,b)$, where $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$. To make the race more exciting, you can perform two types of operations: Increase both $a$ and $b$ by $1$. Decrease both $a$ and $b$ by $1$. This operation can only be performed if both $a$ and $b$ are greater than $0$. In one move, you can perform any one of these operations. You can perform arbitrary (possibly zero) number of moves. Determine the maximum excitement the fans can get and the minimum number of moves required to achieve it. Note that $gcd(x,0)=x$ for any $x \ge 0$. -----Input----- The first line of input contains a single integer $t$ ($1\leq t\leq 5\cdot 10^3$) — the number of test cases. The first and the only line of each test case contains two integers $a$ and $b$ ($0\leq a, b\leq 10^{18}$). -----Output----- For each test case, print a single line containing two integers. If the fans can get infinite excitement, print 0 0. Otherwise, the first integer must be the maximum excitement the fans can get, and the second integer must be the minimum number of moves required to achieve that excitement. -----Examples----- Input 4 8 5 1 2 4 4 3 9 Output 3 1 1 0 0 0 6 3 -----Note----- For the first test case, you can apply the first operation $1$ time to get $a=9$ and $b=6$. It can be shown that $3$ is the maximum excitement possible. For the second test case, no matter how many operations you apply, the fans will always have an excitement equal to $1$. Since the initial excitement is also $1$, you don't need to apply any operation. For the third case, the fans can get infinite excitement by applying the first operation an infinite amount of times. For the fourth test case, you can apply the second operation $3$ times to get $a=0$ and $b=6$. Since, $gcd(0,6)=6$, the fans will get an excitement of $6$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Welcome to PC Koshien, players. This year marks the 10th anniversary of Computer Koshien, but the number of questions and the total score will vary from year to year. Scores are set for each question according to the difficulty level. When the number of questions is 10 and the score of each question is given, create a program that outputs the total of them. input The input is given in the following format. s1 s2 .. .. s10 The input consists of 10 lines, and the i line is given the integer si (0 ≤ si ≤ 100) representing the score of problem i. output Output the total score on one line. Example Input 1 2 3 4 5 6 7 8 9 10 Output 55 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Little Girl loves problems on games very much. Here's one of them. Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second. -----Input----- The input contains a single line, containing string s (1 ≤ |s| ≤ 10^3). String s consists of lowercase English letters. -----Output----- In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes. -----Examples----- Input aba Output First Input abca Output Second Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of $n$ rows and $n$ columns of square cells. The rows are numbered from $1$ to $n$, from top to bottom, and the columns are numbered from $1$ to $n$, from left to right. The position of a cell at row $r$ and column $c$ is represented as $(r, c)$. There are only two colors for the cells in cfpaint — black and white. There is a tool named eraser in cfpaint. The eraser has an integer size $k$ ($1 \le k \le n$). To use the eraser, Gildong needs to click on a cell $(i, j)$ where $1 \le i, j \le n - k + 1$. When a cell $(i, j)$ is clicked, all of the cells $(i', j')$ where $i \le i' \le i + k - 1$ and $j \le j' \le j + k - 1$ become white. In other words, a square with side equal to $k$ cells and top left corner at $(i, j)$ is colored white. A white line is a row or a column without any black cells. Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 2000$) — the number of rows and columns, and the size of the eraser. The next $n$ lines contain $n$ characters each without spaces. The $j$-th character in the $i$-th line represents the cell at $(i,j)$. Each character is given as either 'B' representing a black cell, or 'W' representing a white cell. -----Output----- Print one integer: the maximum number of white lines after using the eraser exactly once. -----Examples----- Input 4 2 BWWW WBBW WBBW WWWB Output 4 Input 3 1 BWB WWB BWB Output 2 Input 5 3 BWBBB BWBBB BBBBB BBBBB WBBBW Output 2 Input 2 2 BW WB Output 4 Input 2 1 WW WW Output 4 -----Note----- In the first example, Gildong can click the cell $(2, 2)$, then the working screen becomes: BWWW WWWW WWWW WWWB Then there are four white lines — the $2$-nd and $3$-rd row, and the $2$-nd and $3$-rd column. In the second example, clicking the cell $(2, 3)$ makes the $2$-nd row a white line. In the third example, both the $2$-nd column and $5$-th row become white lines by clicking the cell $(3, 2)$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a positive integer N. Find the minimum positive integer divisible by both 2 and N. -----Constraints----- - 1 \leq N \leq 10^9 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N -----Output----- Print the minimum positive integer divisible by both 2 and N. -----Sample Input----- 3 -----Sample Output----- 6 6 is divisible by both 2 and 3. Also, there is no positive integer less than 6 that is divisible by both 2 and 3. Thus, the answer is 6. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a string $s$. You can build new string $p$ from $s$ using the following operation no more than two times: choose any subsequence $s_{i_1}, s_{i_2}, \dots, s_{i_k}$ where $1 \le i_1 < i_2 < \dots < i_k \le |s|$; erase the chosen subsequence from $s$ ($s$ can become empty); concatenate chosen subsequence to the right of the string $p$ (in other words, $p = p + s_{i_1}s_{i_2}\dots s_{i_k}$). Of course, initially the string $p$ is empty. For example, let $s = \text{ababcd}$. At first, let's choose subsequence $s_1 s_4 s_5 = \text{abc}$ — we will get $s = \text{bad}$ and $p = \text{abc}$. At second, let's choose $s_1 s_2 = \text{ba}$ — we will get $s = \text{d}$ and $p = \text{abcba}$. So we can build $\text{abcba}$ from $\text{ababcd}$. Can you build a given string $t$ using the algorithm above? -----Input----- The first line contains the single integer $T$ ($1 \le T \le 100$) — the number of test cases. Next $2T$ lines contain test cases — two per test case. The first line contains string $s$ consisting of lowercase Latin letters ($1 \le |s| \le 400$) — the initial string. The second line contains string $t$ consisting of lowercase Latin letters ($1 \le |t| \le |s|$) — the string you'd like to build. It's guaranteed that the total length of strings $s$ doesn't exceed $400$. -----Output----- Print $T$ answers — one per test case. Print YES (case insensitive) if it's possible to build $t$ and NO (case insensitive) otherwise. -----Example----- Input 4 ababcd abcba a b defi fed xyz x Output YES NO NO YES Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers. Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is w_{i}, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash. Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks. Help the party to determine minimum possible total instability! -----Input----- The first line contains one number n (2 ≤ n ≤ 50). The second line contains 2·n integer numbers w_1, w_2, ..., w_2n, where w_{i} is weight of person i (1 ≤ w_{i} ≤ 1000). -----Output----- Print minimum possible total instability. -----Examples----- Input 2 1 2 3 4 Output 1 Input 4 1 3 4 6 3 4 100 200 Output 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i. Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they will alternately perform the following action: * Draw some number of cards from the top of the deck. Then, discard the card in his hand and keep the last drawn card instead. Here, at least one card must be drawn. The game ends when there is no more card in the deck. The score of the game is the absolute difference of the integers written on the cards in the two players' hand. X will play the game so that the score will be maximized, and Y will play the game so that the score will be minimized. What will be the score of the game? Constraints * All input values are integers. * 1 \leq N \leq 2000 * 1 \leq Z, W, a_i \leq 10^9 Input Input is given from Standard Input in the following format: N Z W a_1 a_2 ... a_N Output Print the score. Examples Input 3 100 100 10 1000 100 Output 900 Input 3 100 1000 10 100 100 Output 900 Input 5 1 1 1 1 1 1 1 Output 0 Input 1 1 1 1000000000 Output 999999999 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Skyscraper "MinatoHarukas" Mr. Port plans to start a new business renting one or more floors of the new skyscraper with one giga floors, MinatoHarukas. He wants to rent as many vertically adjacent floors as possible, because he wants to show advertisement on as many vertically adjacent windows as possible. The rent for one floor is proportional to the floor number, that is, the rent per month for the n-th floor is n times that of the first floor. Here, the ground floor is called the first floor in the American style, and basement floors are out of consideration for the renting. In order to help Mr. Port, you should write a program that computes the vertically adjacent floors satisfying his requirement and whose total rental cost per month is exactly equal to his budget. For example, when his budget is 15 units, with one unit being the rent of the first floor, there are four possible rent plans, 1+2+3+4+5, 4+5+6, 7+8, and 15. For all of them, the sums are equal to 15. Of course in this example the rent of maximal number of the floors is that of 1+2+3+4+5, that is, the rent from the first floor to the fifth floor. Input The input consists of multiple datasets, each in the following format. > b > A dataset consists of one line, the budget of Mr. Port b as multiples of the rent of the first floor. b is a positive integer satisfying 1 < b < 109. The end of the input is indicated by a line containing a zero. The number of datasets does not exceed 1000. Output For each dataset, output a single line containing two positive integers representing the plan with the maximal number of vertically adjacent floors with its rent price exactly equal to the budget of Mr. Port. The first should be the lowest floor number and the second should be the number of floors. Sample Input 15 16 2 3 9699690 223092870 847288609 900660121 987698769 999999999 0 Output for the Sample Input 1 5 16 1 2 1 1 2 16 4389 129 20995 4112949 206 15006 30011 46887 17718 163837 5994 Example Input 15 16 2 3 9699690 223092870 847288609 900660121 987698769 999999999 0 Output 1 5 16 1 2 1 1 2 16 4389 129 20995 4112949 206 15006 30011 46887 17718 163837 5994 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 simple version of Fastest Code series. If you need some challenges, please try the [Performance version](http://www.codewars.com/kata/5714594d2817ff681c000783) ## Task: Give you a number array ```numbers``` and a number ```c```. Find out a pair of numbers(we called them number a and number b) from the array ```numbers```, let a*b=c, result format is an array ```[a,b]``` The array ```numbers``` is a sorted array, value range: `-100...100` The result will be the first pair of numbers, for example,```findAB([1,2,3,4,5,6],6)``` should return ```[1,6]```, instead of ```[2,3]``` Please see more example in testcases. ### Series: - [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9) - [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008) - [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009) - [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1) - [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3) - [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e) - [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4) - [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947) - [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1) - [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b) - [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba) - [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba) - [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742) - [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c) - [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048) - [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633) - [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a) - [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594) - [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9) - [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001) - [Tidy up the room](http://www.codewars.com/kata/5703ace6e55d30d3e0001029) - [Waiting for a Bus](http://www.codewars.com/kata/57070eff924f343280000015) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function called `LCS` that accepts two sequences and returns the longest subsequence common to the passed in sequences. ### Subsequence A subsequence is different from a substring. The terms of a subsequence need not be consecutive terms of the original sequence. ### Example subsequence Subsequences of `"abc"` = `"a"`, `"b"`, `"c"`, `"ab"`, `"ac"`, `"bc"` and `"abc"`. ### LCS examples ```python lcs( "abcdef" , "abc" ) => returns "abc" lcs( "abcdef" , "acf" ) => returns "acf" lcs( "132535365" , "123456789" ) => returns "12356" ``` ### Notes * Both arguments will be strings * Return value must be a string * Return an empty string if there exists no common subsequence * Both arguments will have one or more characters (in JavaScript) * All tests will only have a single longest common subsequence. Don't worry about cases such as `LCS( "1234", "3412" )`, which would have two possible longest common subsequences: `"12"` and `"34"`. Note that the Haskell variant will use randomized testing, but any longest common subsequence will be valid. Note that the OCaml variant is using generic lists instead of strings, and will also have randomized tests (any longest common subsequence will be valid). ### Tips Wikipedia has an explanation of the two properties that can be used to solve the problem: - [First property](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#First_property) - [Second property](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Second_property) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back w tokens then he'll get $\lfloor \frac{w \cdot a}{b} \rfloor$ dollars. Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has n numbers x_1, x_2, ..., x_{n}. Number x_{i} is the number of tokens given to each worker on the i-th day. Help him calculate for each of n days the number of tokens he can save. -----Input----- The first line of input contains three space-separated integers n, a, b (1 ≤ n ≤ 10^5; 1 ≤ a, b ≤ 10^9). The second line of input contains n space-separated integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^9). -----Output----- Output n space-separated integers. The i-th of them is the number of tokens Mashmokh can save on the i-th day. -----Examples----- Input 5 1 4 12 6 11 9 1 Output 0 2 3 1 1 Input 3 1 2 1 2 3 Output 1 0 1 Input 1 1 1 1 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island). Find a way to cover some cells with sand so that exactly k islands appear on the n × n map, or determine that no such way exists. Input The single line contains two positive integers n, k (1 ≤ n ≤ 100, 0 ≤ k ≤ n2) — the size of the map and the number of islands you should form. Output If the answer doesn't exist, print "NO" (without the quotes) in a single line. Otherwise, print "YES" in the first line. In the next n lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal n. If there are multiple answers, you may print any of them. You should not maximize the sizes of islands. Examples Input 5 2 Output YES SSSSS LLLLL SSSSS LLLLL SSSSS Input 5 25 Output NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Stellar history 2005.11.5. You are about to engage an enemy spacecraft as the captain of the UAZ Advance spacecraft. Fortunately, the enemy spaceship is still unnoticed. In addition, the space coordinates of the enemy are already known, and the "feather cannon" that emits a powerful straight beam is ready to launch. After that, I just issue a launch command. However, there is an energy barrier installed by the enemy in outer space. The barrier is triangular and bounces off the "feather cannon" beam. Also, if the beam hits the barrier, the enemy will notice and escape. If you cannot determine that you will hit in advance, you will not be able to issue a launch command. Therefore, enter the cosmic coordinates (three-dimensional coordinates x, y, z) of the UAZ Advance, enemy, and barrier positions, and if the beam avoids the barrier and hits the enemy, "HIT", if it hits the barrier " Create a program that outputs "MISS". However, the barrier is only for those that look like a triangle from the Advance issue, and nothing that looks like a line segment is crushed. Barriers are also valid at boundaries containing triangular vertices and shall bounce the beam. Also, if the enemy is in the barrier, output "MISS". Constraints * -100 ≤ x, y, z ≤ 100 * The UAZ Advance and the enemy are never in the same position. Input The format of the input data is as follows: The first line is the coordinates of UAZ Advance (x, y, z) (integer, half-width space delimited) The second line is the coordinates of the enemy (x, y, z) (integer, half-width space delimiter) The third line is the coordinates of vertex 1 of the barrier (x, y, z) (integer, half-width space delimiter) The fourth line is the coordinates (x, y, z) of the vertex 2 of the barrier (integer, half-width space delimiter) The fifth line is the coordinates (x, y, z) of the vertex 3 of the barrier (integer, half-width space delimiter) Output Output on one line with HIT or MISS. Examples Input -10 0 0 10 0 0 0 10 0 0 10 10 0 0 10 Output HIT Input -10 6 6 10 6 6 0 10 0 0 10 10 0 0 10 Output MISS Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces». With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols? A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». -----Input----- The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·10^5. It's guaranteed that all lines are non-empty. -----Output----- Print a single integer — the minimum number of clicks. -----Examples----- Input snow affects sports such as skiing, snowboarding, and snowmachine travel. snowboarding is a recreational activity and olympic and paralympic sport. Output 141 Input 'co-co-co, codeforces?!' Output 25 Input thun-thun-thunder, thunder, thunder thunder, thun-, thunder thun-thun-thunder, thunder thunder, feel the thunder lightning then the thunder thunder, feel the thunder lightning then the thunder thunder, thunder Output 183 -----Note----- In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks. In sample case two it doesn't matter whether to use autocompletion or not. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order. Iroha is looking for X,Y,Z-Haiku (defined below) in integer sequences. Consider all integer sequences of length N whose elements are between 1 and 10, inclusive. Out of those 10^N sequences, how many contain an X,Y,Z-Haiku? Here, an integer sequence a_0, a_1, ..., a_{N-1} is said to contain an X,Y,Z-Haiku if and only if there exist four indices x, y, z, w (0 ≦ x < y < z < w ≦ N) such that all of the following are satisfied: - a_x + a_{x+1} + ... + a_{y-1} = X - a_y + a_{y+1} + ... + a_{z-1} = Y - a_z + a_{z+1} + ... + a_{w-1} = Z Since the answer can be extremely large, print the number modulo 10^9+7. -----Constraints----- - 3 ≦ N ≦ 40 - 1 ≦ X ≦ 5 - 1 ≦ Y ≦ 7 - 1 ≦ Z ≦ 5 -----Input----- The input is given from Standard Input in the following format: N X Y Z -----Output----- Print the number of the sequences that contain an X,Y,Z-Haiku, modulo 10^9+7. -----Sample Input----- 3 5 7 5 -----Sample Output----- 1 Here, the only sequence that contains a 5,7,5-Haiku is [5, 7, 5]. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have held a popularity poll for N items on sale. Item i received A_i votes. From these N items, we will select M as popular items. However, we cannot select an item with less than \dfrac{1}{4M} of the total number of votes. If M popular items can be selected, print Yes; otherwise, print No. -----Constraints----- - 1 \leq M \leq N \leq 100 - 1 \leq A_i \leq 1000 - A_i are distinct. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N M A_1 ... A_N -----Output----- If M popular items can be selected, print Yes; otherwise, print No. -----Sample Input----- 4 1 5 4 2 1 -----Sample Output----- Yes There were 12 votes in total. The most popular item received 5 votes, and we can select it. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a method that takes a string as an argument and groups the number of time each character appears in the string as a hash sorted by the highest number of occurrences. The characters should be sorted alphabetically e.g: ```python get_char_count("cba") == {1: ["a", "b", "c"]} ``` You should ignore spaces, special characters and count uppercase letters as lowercase ones. For example: ```python get_char_count("Mississippi") == {4: ["i", "s"], 2: ["p"], 1: ["m"]} get_char_count("Hello. Hello? HELLO!") == {6: ["l"], 3: ["e", "h", "o"]} get_char_count("aaa...bb...c!") == {3: ["a"], 2: ["b"], 1: ["c"]} get_char_count("abc123") == {1: ["1", "2", "3", "a", "b", "c"]} get_char_count("aaabbbccc") == {3: ["a", "b", "c"]} ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are N integers a_1, a_2, ..., a_N not less than 1. The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P. Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N. Constraints * 1 \leq N \leq 10^{12} * 1 \leq P \leq 10^{12} Input Input is given from Standard Input in the following format: N P Output Print the answer. Examples Input 3 24 Output 2 Input 5 1 Output 1 Input 1 111 Output 111 Input 4 972439611840 Output 206 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 bracket sequence $s$ of length $n$, where $n$ is even (divisible by two). The string $s$ consists of $\frac{n}{2}$ opening brackets '(' and $\frac{n}{2}$ closing brackets ')'. In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $i$, remove the $i$-th character of $s$ and insert it before or after all remaining characters of $s$). Your task is to find the minimum number of moves required to obtain regular bracket sequence from $s$. It can be proved that the answer always exists under the given constraints. Recall what the regular bracket sequence is: "()" is regular bracket sequence; if $s$ is regular bracket sequence then "(" + $s$ + ")" is regular bracket sequence; if $s$ and $t$ are regular bracket sequences then $s$ + $t$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($2 \le n \le 50$) — the length of $s$. It is guaranteed that $n$ is even. The second line of the test case containg the string $s$ consisting of $\frac{n}{2}$ opening and $\frac{n}{2}$ closing brackets. -----Output----- For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $s$. It can be proved that the answer always exists under the given constraints. -----Example----- Input 4 2 )( 4 ()() 8 ())()()( 10 )))((((()) Output 1 0 1 3 -----Note----- In the first test case of the example, it is sufficient to move the first bracket to the end of the string. In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string. In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())". Read the inputs from stdin solve the problem and write the answer to stdout (do 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 items, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i. Taro has decided to choose some of the N items and carry them home in a knapsack. The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W. Find the maximum possible sum of the values of items that Taro takes home. Constraints * All values in input are integers. * 1 \leq N \leq 100 * 1 \leq W \leq 10^9 * 1 \leq w_i \leq W * 1 \leq v_i \leq 10^3 Input Input is given from Standard Input in the following format: N W w_1 v_1 w_2 v_2 : w_N v_N Output Print the maximum possible sum of the values of items that Taro takes home. Examples Input 3 8 3 30 4 50 5 60 Output 90 Input 1 1000000000 1000000000 10 Output 10 Input 6 15 6 5 5 6 6 4 6 6 3 5 7 2 Output 17 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Arthur and Alexander are number busters. Today they've got a competition. Arthur took a group of four integers a, b, w, x (0 ≤ b < w, 0 < x < w) and Alexander took integer с. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number. In other words, he performs the assignment: c = c - 1. Arthur is a sophisticated guy. Each second Arthur performs a complex operation, described as follows: if b ≥ x, perform the assignment b = b - x, if b < x, then perform two consecutive assignments a = a - 1; b = w - (x - b). You've got numbers a, b, w, x, c. Determine when Alexander gets ahead of Arthur if both guys start performing the operations at the same time. Assume that Alexander got ahead of Arthur if c ≤ a. -----Input----- The first line contains integers a, b, w, x, c (1 ≤ a ≤ 2·10^9, 1 ≤ w ≤ 1000, 0 ≤ b < w, 0 < x < w, 1 ≤ c ≤ 2·10^9). -----Output----- Print a single integer — the minimum time in seconds Alexander needs to get ahead of Arthur. You can prove that the described situation always occurs within the problem's limits. -----Examples----- Input 4 2 3 1 6 Output 2 Input 4 2 3 1 7 Output 4 Input 1 2 3 2 6 Output 13 Input 1 1 2 1 1 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a^2 is a divisor of x. [Image] Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to give her a lovely number from his store. He wants this number to be as big as possible. Malek always had issues in math, so he asked for your help. Please tell him what is the biggest lovely number in his store. -----Input----- The first and only line of input contains one integer, n (1 ≤ n ≤ 10^12). -----Output----- Print the answer in one line. -----Examples----- Input 10 Output 10 Input 12 Output 6 -----Note----- In first sample case, there are numbers 1, 2, 5 and 10 in the shop. 10 isn't divisible by any perfect square, so 10 is lovely. In second sample case, there are numbers 1, 2, 3, 4, 6 and 12 in the shop. 12 is divisible by 4 = 2^2, so 12 is not lovely, while 6 is indeed lovely. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a: * Remove any two elements from a and append their sum to b. The compressed array b has to have a special property. The greatest common divisor (gcd) of all its elements should be greater than 1. Recall that the gcd of an array of positive integers is the biggest integer that is a divisor of all integers in the array. It can be proven that it is always possible to compress array a into an array b of size n-1 such that gcd(b_1, b_2..., b_{n-1}) > 1. Help Ashish find a way to do so. Input The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 1000). The second line of each test case contains 2n integers a_1, a_2, …, a_{2n} (1 ≤ a_i ≤ 1000) — the elements of the array a. Output For each test case, output n-1 lines — the operations performed to compress the array a to the array b. The initial discard of the two elements is not an operation, you don't need to output anything about it. The i-th line should contain two integers, the indices (1 —based) of the two elements from the array a that are used in the i-th operation. All 2n-2 indices should be distinct integers from 1 to 2n. You don't need to output two initially discarded elements from a. If there are multiple answers, you can find any. Example Input 3 3 1 2 3 4 5 6 2 5 7 9 10 5 1 3 3 4 5 90 100 101 2 3 Output 3 6 4 5 3 4 1 9 2 3 4 5 6 10 Note In the first test case, b = \{3+6, 4+5\} = \{9, 9\} and gcd(9, 9) = 9. In the second test case, b = \{9+10\} = \{19\} and gcd(19) = 19. In the third test case, b = \{1+2, 3+3, 4+5, 90+3\} = \{3, 6, 9, 93\} and gcd(3, 6, 9, 93) = 3. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Story Well, here I am stuck in another traffic jam. *Damn all those courteous people!* Cars are trying to enter the main road from side-streets somewhere ahead of me and people keep letting them cut in. Each time somebody is let in the effect ripples back down the road, so pretty soon I am not moving at all. (Sigh... late again...) ## Visually The diagram below shows lots of cars all attempting to go North. * the `a`,`b`,`c`... cars are on the main road with me (`X`) * the `B` cars and `C` cars are merging from side streets | a | | b | ↑ --------+ c | BBBBBB d | --------+ e | | f | ↑ | g | --------+ h | CCCCC i | --------+ j | ↑ | k | | l | | m | | X | This can be represented as * `mainRoad` = `"abcdefghijklmX"` * `sideStreets` = `["","","","BBBBBB","","","","","CCCCC"]` # Kata Task Assume every car on the main road will "give way" to 1 car entering from each side street. Return a string representing the cars (up to and including me) in the order they exit off the top of the diagram. ## Notes * My car is the only `X`, and I am always on the main road * Other cars may be any alpha-numeric character (except `X` of course) * There are no "gaps" between cars * Assume side streets are always on the left (as in the diagram) * The `sideStreets` array length may vary but is never more than the length of the main road * A pre-loaded `Util.display(mainRoad,sideStreets)` method is provided which may help to visualise the data * (Util.Display for C#) ## Example Here are the first few iterations of my example, showing that I am hardly moving at all... InitialIter 1Iter 2Iter 3Iter 4Iter 5Iter 6Iter 7 a b c BBBBBBd e f g h CCCCCi j k l m X b c d BBBBBB e f g h CCCCCi j k l m X c d B BBBBBe f g h i CCCCC j k l m X d B e BBBBB f g h i CCCCC j k l m X B e B BBBBf g h i C CCCCj k l m X e B f BBBB g h i C CCCCj k l m X B f B BBBg h i C j CCCC k l m X f B g BBB h i C j CCCC k l m X :-) DM Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an array $a$ of length $n$, which initially is a permutation of numbers from $1$ to $n$. In one operation, you can choose an index $i$ ($1 \leq i < n$) such that $a_i < a_{i + 1}$, and remove either $a_i$ or $a_{i + 1}$ from the array (after the removal, the remaining parts are concatenated). For example, if you have the array $[1, 3, 2]$, you can choose $i = 1$ (since $a_1 = 1 < a_2 = 3$), then either remove $a_1$ which gives the new array $[3, 2]$, or remove $a_2$ which gives the new array $[1, 2]$. Is it possible to make the length of this array equal to $1$ with these operations? -----Input----- The first line contains a single integer $t$ ($1 \leq t \leq 2 \cdot 10^4$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $n$ ($2 \leq n \leq 3 \cdot 10^5$)  — the length of the array. The second line of each test case contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \leq a_i \leq n$, $a_i$ are pairwise distinct) — elements of the array. It is guaranteed that the sum of $n$ over all test cases doesn't exceed $3 \cdot 10^5$. -----Output----- For each test case, output on a single line the word "YES" if it is possible to reduce the array to a single element using the aforementioned operation, or "NO" if it is impossible to do so. -----Example----- Input 4 3 1 2 3 4 3 1 2 4 3 2 3 1 6 2 4 6 1 3 5 Output YES YES NO YES -----Note----- For the first two test cases and the fourth test case, we can operate as follow (the bolded elements are the pair chosen for that operation): $[\text{1}, \textbf{2}, \textbf{3}] \rightarrow [\textbf{1}, \textbf{2}] \rightarrow [\text{1}]$ $[\text{3}, \textbf{1}, \textbf{2}, \text{4}] \rightarrow [\text{3}, \textbf{1}, \textbf{4}] \rightarrow [\textbf{3}, \textbf{4}] \rightarrow [\text{4}]$ $[\textbf{2}, \textbf{4}, \text{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\textbf{4}, \textbf{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\text{4}, \text{1}, \textbf{3}, \textbf{5}] \rightarrow [\text{4}, \textbf{1}, \textbf{5}] \rightarrow [\textbf{4}, \textbf{5}] \rightarrow [\text{4}]$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 110011 54322345 For a given number ```num```, write a function which returns the number of numerical palindromes within each number. For this kata, single digit numbers will NOT be considered numerical palindromes. Return "Not valid" if the input is not an integer or is less than 0. ``` palindrome(5) => 0 palindrome(1221) => 2 palindrome(141221001) => 5 palindrome(1294) => 0 palindrome("1221") => "Not valid" ``` ```Haskell In Haskell, return a Maybe Int with Nothing for negative numbers. ``` Other Kata in this Series: Numerical Palindrome #1 Numerical Palindrome #1.5 Numerical Palindrome #2 Numerical Palindrome #3 Numerical Palindrome #3.5 Numerical Palindrome #4 Numerical Palindrome #5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Two circles A, B are given on a two-dimensional plane. The coordinate of the center and radius of circle A is (x_A, y_A) and r_A respectively. The coordinate of the center and radius of circle B is (x_B, y_B) and r_B respectively. These two circles have no intersection inside. Here, we consider a set of circles S that satisfies the following conditions. * Each circle in S touches both A and B, and does not have common points with them inside the circle. * Any two different circles in S have no common points inside them. Write a program that finds the maximum number of elements in S. Constraints * 1 \leq T \leq 50000 * -10^5 \leq x_A \leq 10^5 * -10^5 \leq y_A \leq 10^5 * -10^5 \leq x_B \leq 10^5 * -10^5 \leq y_B \leq 10^5 * 1 \leq r_A \leq 10^5 * 1 \leq r_B \leq 10^5 * {r_A}^2 + {r_B}^2 < (x_A - x_B)^2 + (y_A - y_B)^2 * All values given as input are integers. * It is guaranteed that, when the radiuses of A and B change by 0.0005, the answer does not change. Input The input consists of multiple test cases and is given from Standard Input in the following format: T testcase_1 : testcase_T Each test case is given with the following format. x_A y_A r_A x_B y_B r_B Output The output consists of T lines. On line i (1 \leq i \leq T), putput the maximum number of elements in S in i-th test case. Example Input 4 0 -3 2 0 3 2 0 0 9 8 8 2 0 0 9 10 10 5 0 0 707 1000 1000 707 Output 3 10 21 180 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting. Input The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive. Output Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed. Examples Input 5 1 2 3 4 5 Output 1 1 2 3 4 Input 5 2 3 4 5 6 Output 1 2 3 4 5 Input 3 2 2 2 Output 1 2 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is the word heuristics. It's a relatively simple approach that usually works, although there is no guarantee that it will work. The world is full of heuristics because it is simple and powerful. Some examples of heuristics include: In an anime program, the popularity of a character is proportional to the total appearance time in the main part of the anime. Certainly this seems to hold true in many cases. However, it seems that I belong to the minority. Only characters with light shadows and mobs that glimpse in the background look cute. It doesn't matter what other people think of your favorite character. Unfortunately, there are circumstances that cannot be said. Related products, figures and character song CDs, tend to be released with priority from popular characters. Although it is a commercial choice, fans of unpopular characters have a narrow shoulder. Therefore, what is important is the popularity vote held by the production company of the anime program. Whatever the actual popularity, getting a lot of votes here opens the door to related products. You have to collect votes by any means. For strict voting, you will be given one vote for each purchase of a related product. Whether or not this mechanism should be called strict is now being debated, but anyway I got the right to vote for L votes. There are a total of N characters to be voted on, and related products of K characters who have won more votes (in the case of the same vote, in dictionary order of names) will be planned. I have M characters in all, and I want to put as many characters as possible in the top K. I first predicted how many votes each character would get (it's not difficult, I just assumed that a character's popularity is proportional to the sum of its appearance times). Given that this prediction is correct, who and how much should I cast this L-vote to ensure that more related products of my favorite characters are released? Input The input consists of multiple cases. Each case is given in the following format. N M K L name0 x0 .. .. .. nameN-1 xN-1 fav0 .. .. .. favM-1 The meanings of N, M, K, and L are as described in the problem statement. namei is the name of the character and xi is the total number of votes for the i-th character. favi represents the name of the character you like. These names are always different and are always included in the character's name input. The end of the input is given by a line consisting of N = 0, M = 0, K = 0, and L = 0. In addition, each value satisfies the following conditions 1 ≤ N ≤ 100,000 1 ≤ M ≤ N 1 ≤ K ≤ N 1 ≤ L ≤ 100,000,000 0 ≤ xi ≤ 100,000,000 namei contains only the alphabet and is 10 characters or less in length. The number of test cases does not exceed 150. It is also guaranteed that the number of cases where 20,000 ≤ N does not exceed 20. Judge data is large, so it is recommended to use fast input. Output Output in one line how many of the M characters can be included in the top K. Example Input 4 1 3 4 yskwcnt 16 akzakr 7 tsnukk 12 fnmyi 13 akzakr 4 1 3 5 akzakr 7 tsnukk 12 fnmyi 13 yskwcnt 16 akzakr 4 2 2 1 akzakr 4 tsnukk 6 yskwcnt 6 fnmyi 12 akzakr fnmyi 5 2 3 28 knmmdk 6 skrkyk 14 tmemm 14 akmhmr 15 mksyk 25 knmmdk skrkyk 5 2 3 11 tmemm 12 skrkyk 18 knmmdk 21 mksyk 23 akmhmr 42 skrkyk tmemm 14 5 10 38 iormns 19 hbkgnh 23 yyitktk 31 rtkakzk 36 mmftm 43 ykhhgwr 65 hrkamm 66 ktrotns 67 mktkkc 68 mkhsi 69 azsmur 73 tknsj 73 amftm 81 chyksrg 88 mkhsi hbkgnh mktkkc yyitktk tknsj 14 5 10 38 mktkkc 24 rtkakzk 25 ykhhgwr 25 hrkamm 27 amftm 37 iormns 38 tknsj 38 yyitktk 39 hbkgnh 53 mmftm 53 chyksrg 63 ktrotns 63 azsmur 65 mkhsi 76 mkhsi hbkgnh mktkkc yyitktk tknsj 0 0 0 0 Output 0 1 1 2 1 4 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. It's 3AM and you get the dreaded call from a customer: the program your company sold them is hanging. You eventually trace the problem down to a call to a function named `mystery`. Usually, `mystery` works fine and produces an integer result for an integer input. However, on certain inputs, the `mystery` function just locks up. Unfortunately, the `mystery` function is part of a third-party library, and you don't have access to the source code. Uck. It may take a while to get support from the provider of the library, and in the meantime, your customer is getting frustrated. Your mission, should you choose to accept it, is to create a new function called `wrap_mystery` that returns the same results as `mystery`, but does not hang. Since you're not sure exactly what values `mystery` should be returning for hangs, just have `wrap_mystery` return -1 for problematic input. Your customer is counting on you! `wrap_mystery` will only be called with positive integers less than 1,000,000. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You finally woke up after this crazy dream and decided to walk around to clear your head. Outside you saw your house's fence — so plain and boring, that you'd like to repaint it. You have a fence consisting of $n$ planks, where the $i$-th plank has the color $a_i$. You want to repaint the fence in such a way that the $i$-th plank has the color $b_i$. You've invited $m$ painters for this purpose. The $j$-th painter will arrive at the moment $j$ and will recolor exactly one plank to color $c_j$. For each painter you can choose which plank to recolor, but you can't turn them down, i. e. each painter has to color exactly one plank. Can you get the coloring $b$ you want? If it's possible, print for each painter which plank he must paint. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow. The first line of each test case contains two integers $n$ and $m$ ($1 \le n, m \le 10^5$) — the number of planks in the fence and the number of painters. The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) — the initial colors of the fence. The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le n$) — the desired colors of the fence. The fourth line of each test case contains $m$ integers $c_1, c_2, \dots, c_m$ ($1 \le c_j \le n$) — the colors painters have. It's guaranteed that the sum of $n$ doesn't exceed $10^5$ and the sum of $m$ doesn't exceed $10^5$ over all test cases. -----Output----- For each test case, output "NO" if it is impossible to achieve the coloring $b$. Otherwise, print "YES" and $m$ integers $x_1, x_2, \dots, x_m$, where $x_j$ is the index of plank the $j$-th painter should paint. You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes" and "YES" are all recognized as positive answer). -----Examples----- Input 6 1 1 1 1 1 5 2 1 2 2 1 1 1 2 2 1 1 1 2 3 3 2 2 2 2 2 2 2 3 2 10 5 7 3 2 1 7 9 4 2 7 9 9 9 2 1 4 9 4 2 3 9 9 9 7 4 3 5 2 1 2 2 1 1 1 2 2 1 1 3 3 6 4 3 4 2 4 1 2 2 3 1 3 1 1 2 2 3 4 Output YES 1 YES 2 2 YES 1 1 1 YES 2 1 9 5 9 NO NO -----Note----- None Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sugoroku problem JOI is playing sugoroku alone. There are N squares in a straight line in this sugoroku, and each has a movement instruction written on it. The starting point is the 1st square and the goal is the Nth square. JOI repeats the following until he reaches the goal. Roll the dice and proceed from the current square by the number of rolls, and follow the instructions of that square. Do not follow the instructions of the square to which you moved according to the instructions. The goal is not only when you stop at the Nth square, but also when the destination exceeds the Nth square. Create a program that outputs how many times you roll the dice to reach the goal when you are given a sugoroku board and M dice rolls. input The input consists of multiple datasets. Each dataset is given in the following format. Each dataset consists of 1 + N + M rows. Two integers N, M (2 ≤ N ≤ 1000, 1 ≤ M ≤ 1000) are written on the first line of the input, separated by blanks. N represents the number of sugoroku squares, and M represents the number of dice given. In the following N lines, integers between -999 and 999 are written one by one. The integer on the 1 + i line (1 ≤ i ≤ N) represents the indication of the sugoroku i-th cell. Let X be the written integer. When X = 0, it indicates "do nothing", when X> 0, it indicates "advance X mass", and when X <0, it indicates "| X | mass return". However, | X | represents the absolute value of X. In the following M line, integers from 1 to 6 are written one by one, and the number on the 1 + N + j line (1 ≤ j ≤ M) represents the dice roll that appears on the jth time. However, the number of lines 2 and 1 + N is always 0. There is no cell with instructions to move to the cell before the first cell. In addition, the number of times the dice are rolled is M or less in any scoring input data. When both N and M are 0, it indicates the end of input. The number of data sets does not exceed 5. output For each data set, an integer indicating how many times the dice are rolled to reach the goal is output on one line. Input / output example Input example 10 5 0 0 Five 6 -3 8 1 8 -Four 0 1 3 Five 1 Five 10 10 0 -1 -1 Four Four -Five 0 1 -6 0 1 Five 2 Four 6 Five Five Four 1 6 0 0 Output example Five 6 The following figure shows the first input example. <image> The following figure shows the second input example. <image> The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring. Example Input 10 5 0 0 5 6 -3 8 1 8 -4 0 1 3 5 1 5 10 10 0 -1 -1 4 4 -5 0 1 -6 0 1 5 2 4 6 5 5 4 1 6 0 0 Output 5 6 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Define a function that takes in two non-negative integers `$a$` and `$b$` and returns the last decimal digit of `$a^b$`. Note that `$a$` and `$b$` may be very large! For example, the last decimal digit of `$9^7$` is `$9$`, since `$9^7 = 4782969$`. The last decimal digit of `$({2^{200}})^{2^{300}}$`, which has over `$10^{92}$` decimal digits, is `$6$`. Also, please take `$0^0$` to be `$1$`. You may assume that the input will always be valid. ## Examples ```python last_digit(4, 1) # returns 4 last_digit(4, 2) # returns 6 last_digit(9, 7) # returns 9 last_digit(10, 10 ** 10) # returns 0 last_digit(2 ** 200, 2 ** 300) # returns 6 ``` ___ ## Remarks ### JavaScript, C++, R, PureScript Since these languages don't have native arbitrarily large integers, your arguments are going to be strings representing non-negative integers instead. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any $i$ ($1 \le i \le n-1$), this condition must be satisfied: $$\frac{\max(a[i], a[i+1])}{\min(a[i], a[i+1])} \le 2$$ For example, the arrays $[1, 2, 3, 4, 3]$, $[1, 1, 1]$ and $[5, 10]$ are dense. And the arrays $[5, 11]$, $[1, 4, 2]$, $[6, 6, 1]$ are not dense. You are given an array $a$ of $n$ integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added. For example, if $a=[4,2,10,1]$, then the answer is $5$, and the array itself after inserting elements into it may look like this: $a=[4,2,\underline{\textbf{3}},\underline{\textbf{5}},10,\underline{\textbf{6}},\underline{\textbf{4}},\underline{\textbf{2}},1]$ (there are other ways to build such $a$). -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$). Then $t$ test cases follow. The first line of each test case contains one integer $n$ ($2 \le n \le 50$) — the length of the array $a$. The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 50$). -----Output----- For each test case, output one integer — the minimum number of numbers that must be added to the array to make it dense. -----Examples----- Input 6 4 4 2 10 1 2 1 3 2 6 1 3 1 4 2 5 1 2 3 4 3 12 4 31 25 50 30 20 34 46 42 16 15 16 Output 5 1 2 1 0 3 -----Note----- The first test case is explained in the statements. In the second test case, you can insert one element, $a=[1,\underline{\textbf{2}},3]$. In the third test case, you can insert two elements, $a=[6,\underline{\textbf{4}},\underline{\textbf{2}},1]$. In the fourth test case, you can insert one element, $a=[1,\underline{\textbf{2}},4,2]$. In the fifth test case, the array $a$ is already dense. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke loves flags. Snuke is placing N flags on a line. The i-th flag can be placed at either coordinate x_i or coordinate y_i. Snuke thinks that the flags look nicer when the smallest distance between two of them, d, is larger. Find the maximum possible value of d. Constraints * 2 ≤ N ≤ 10^{4} * 1 ≤ x_i, y_i ≤ 10^{9} * x_i and y_i are integers. Input The input is given from Standard Input in the following format: N x_1 y_1 : x_N y_N Output Print the answer. Examples Input 3 1 3 2 5 1 9 Output 4 Input 5 2 2 2 2 2 2 2 2 2 2 Output 0 Input 22 93 6440 78 6647 862 11 8306 9689 798 99 801 521 188 206 6079 971 4559 209 50 94 92 6270 5403 560 803 83 1855 99 42 504 75 484 629 11 92 122 3359 37 28 16 648 14 11 269 Output 17 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1 ≤ x < n) such that dx = 4 and dx + 1 = 7, if x is odd, then to assign dx = dx + 1 = 4, otherwise to assign dx = dx + 1 = 7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all. You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations. Input The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 109) — the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero. Output In the single line print the result without spaces — the number after the k operations are fulfilled. Examples Input 7 4 4727447 Output 4427477 Input 4 2 4478 Output 4478 Note In the first sample the number changes in the following sequence: 4727447 → 4427447 → 4427477 → 4427447 → 4427477. In the second sample: 4478 → 4778 → 4478. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each i (1 ≤ i ≤ |s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with. -----Input----- The first line of the input contains a string s (1 ≤ |s| ≤ 10^5). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character. -----Output----- If there is no way of replacing '#' characters which leads to a beautiful string print - 1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with. If there are several possible answers, you may output any of them. -----Examples----- Input (((#)((#) Output 1 2 Input ()((#((#(#() Output 2 2 1 Input # Output -1 Input (#) Output -1 -----Note----- |s| denotes the length of the string s. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k < n), and this should be done in the smallest possible number of moves. One move is choosing an integer i (1 ≤ i ≤ n) such that ai > 0 and an integer t (t ≥ 0) such that i + 2t ≤ n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai + 2t is increased by 1. For example, let n = 4 and a = (1, 0, 1, 2), then it is possible to make move i = 3, t = 0 and get a = (1, 0, 0, 3) or to make move i = 1, t = 1 and get a = (0, 0, 2, 2) (the only possible other move is i = 1, t = 0). You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1 ≤ k < n). Input The first input line contains a single integer n. The second line contains n integers ai (0 ≤ ai ≤ 104), separated by single spaces. The input limitations for getting 20 points are: * 1 ≤ n ≤ 300 The input limitations for getting 50 points are: * 1 ≤ n ≤ 2000 The input limitations for getting 100 points are: * 1 ≤ n ≤ 105 Output Print exactly n - 1 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams, or the %I64d specifier. Examples Input 4 1 0 1 2 Output 1 1 3 Input 8 1 2 3 4 5 6 7 8 Output 1 3 6 10 16 24 40 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 lowercase English letters, and an integer K. Print the string obtained by replacing every character in S that differs from the K-th character of S, with `*`. Constraints * 1 \leq K \leq N\leq 10 * S is a string of length N consisting of lowercase English letters. * N and K are integers. Input Input is given from Standard Input in the following format: N S K Output Print the string obtained by replacing every character in S that differs from the K-th character of S, with `*`. Examples Input 5 error 2 Output *rr*r Input 6 eleven 5 Output e*e*e* Input 9 education 7 Output ******i** Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke is having another barbeque party. This time, he will make one serving of Skewer Meal. He has a stock of N Skewer Meal Packs. The i-th Skewer Meal Pack contains one skewer, A_i pieces of beef and B_i pieces of green pepper. All skewers in these packs are different and distinguishable, while all pieces of beef and all pieces of green pepper are, respectively, indistinguishable. To make a Skewer Meal, he chooses two of his Skewer Meal Packs, and takes out all of the contents from the chosen packs, that is, two skewers and some pieces of beef or green pepper. (Remaining Skewer Meal Packs will not be used.) Then, all those pieces of food are threaded onto both skewers, one by one, in any order. (See the image in the Sample section for better understanding.) In how many different ways can he make a Skewer Meal? Two ways of making a Skewer Meal is different if and only if the sets of the used skewers are different, or the orders of the pieces of food are different. Since this number can be extremely large, find it modulo 10^9+7. Constraints * 2≦N≦200,000 * 1≦A_i≦2000, 1≦B_i≦2000 Input The input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the number of the different ways Snuke can make a serving of Skewer Meal, modulo 10^9+7. Example Input 3 1 1 1 1 2 1 Output 26 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a_1, a_2, ..., a_{n} in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number n and array a. loop integer variable i from 1 to n - 1     loop integer variable j from i to n - 1         if (a_{j} > a_{j} + 1), then swap the values of elements a_{j} and a_{j} + 1 But Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of n doesn't exist, print -1. -----Input----- You've got a single integer n (1 ≤ n ≤ 50) — the size of the sorted array. -----Output----- Print n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100) — the counter-example, for which Valera's algorithm won't work correctly. If the counter-example that meets the described conditions is impossible to give, print -1. If there are several counter-examples, consisting of n numbers, you are allowed to print any of them. -----Examples----- Input 1 Output -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sasha is a very happy guy, that's why he is always on the move. There are $n$ cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from $1$ to $n$ in increasing order. The distance between any two adjacent cities is equal to $1$ kilometer. Since all roads in the country are directed, it's possible to reach the city $y$ from the city $x$ only if $x < y$. Once Sasha decided to go on a trip around the country and to visit all $n$ cities. He will move with the help of his car, Cheetah-2677. The tank capacity of this model is $v$ liters, and it spends exactly $1$ liter of fuel for $1$ kilometer of the way. At the beginning of the journey, the tank is empty. Sasha is located in the city with the number $1$ and wants to get to the city with the number $n$. There is a gas station in each city. In the $i$-th city, the price of $1$ liter of fuel is $i$ dollars. It is obvious that at any moment of time, the tank can contain at most $v$ liters of fuel. Sasha doesn't like to waste money, that's why he wants to know what is the minimum amount of money is needed to finish the trip if he can buy fuel in any city he wants. Help him to figure it out! -----Input----- The first line contains two integers $n$ and $v$ ($2 \le n \le 100$, $1 \le v \le 100$)  — the number of cities in the country and the capacity of the tank. -----Output----- Print one integer — the minimum amount of money that is needed to finish the trip. -----Examples----- Input 4 2 Output 4 Input 7 6 Output 6 -----Note----- In the first example, Sasha can buy $2$ liters for $2$ dollars ($1$ dollar per liter) in the first city, drive to the second city, spend $1$ liter of fuel on it, then buy $1$ liter for $2$ dollars in the second city and then drive to the $4$-th city. Therefore, the answer is $1+1+2=4$. In the second example, the capacity of the tank allows to fill the tank completely in the first city, and drive to the last city without stops in other cities. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The string $t_1t_2 \dots t_k$ is good if each letter of this string belongs to at least one palindrome of length greater than 1. A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not. Here are some examples of good strings: $t$ = AABBB (letters $t_1$, $t_2$ belong to palindrome $t_1 \dots t_2$ and letters $t_3$, $t_4$, $t_5$ belong to palindrome $t_3 \dots t_5$); $t$ = ABAA (letters $t_1$, $t_2$, $t_3$ belong to palindrome $t_1 \dots t_3$ and letter $t_4$ belongs to palindrome $t_3 \dots t_4$); $t$ = AAAAA (all letters belong to palindrome $t_1 \dots t_5$); You are given a string $s$ of length $n$, consisting of only letters A and B. You have to calculate the number of good substrings of string $s$. -----Input----- The first line contains one integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the length of the string $s$. The second line contains the string $s$, consisting of letters A and B. -----Output----- Print one integer — the number of good substrings of string $s$. -----Examples----- Input 5 AABBB Output 6 Input 3 AAA Output 3 Input 7 AAABABB Output 15 -----Note----- In the first test case there are six good substrings: $s_1 \dots s_2$, $s_1 \dots s_4$, $s_1 \dots s_5$, $s_3 \dots s_4$, $s_3 \dots s_5$ and $s_4 \dots s_5$. In the second test case there are three good substrings: $s_1 \dots s_2$, $s_1 \dots s_3$ and $s_2 \dots s_3$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. For given two lines s1 and s2, print "2" if they are parallel, "1" if they are orthogonal, or "0" otherwise. s1 crosses points p0 and p1, and s2 crosses points p2 and p3. Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xpi, ypi ≤ 10000 * p0 ≠ p1 and p2 ≠ p3. Input The entire input looks like: q (the number of queries) 1st query 2nd query ... qth query Each query consists of integer coordinates of the points p0, p1, p2, p3 in the following format: xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3 Output For each query, print "2", "1" or "0". Example Input 3 0 0 3 0 0 2 3 2 0 0 3 0 1 1 1 4 0 0 3 0 1 1 2 2 Output 2 1 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given some text $t$ and a set of $n$ strings $s_1, s_2, \dots, s_n$. In one step, you can choose any occurrence of any string $s_i$ in the text $t$ and color the corresponding characters of the text in red. For example, if $t={bababa}$ and $s_1={ba}$, $s_2={aba}$, you can get $t={{ba}}{baba}$, $t={b}{{aba}}{ba}$ or $t={bab}{{aba}}$ in one step. You want to color all the letters of the text $t$ in red. When you color a letter in red again, it stays red. In the example above, three steps are enough: Let's color $t[2 \dots 4]=s_2={aba}$ in red, we get $t={b}{{aba}}{ba}$; Let's color $t[1 \dots 2]=s_1={ba}$ in red, we get $t={{baba}}{ba}$; Let's color $t[4 \dots 6]=s_2={aba}$ in red, we get $t={{bababa}}$. Each string $s_i$ can be applied any number of times (or not at all). Occurrences for coloring can intersect arbitrarily. Determine the minimum number of steps needed to color all letters $t$ in red and how to do it. If it is impossible to color all letters of the text $t$ in red, output -1. -----Input----- The first line of the input contains an integer $q$ ($1 \le q \le 100$) —the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains the text $t$ ($1 \le |t| \le 100$), consisting only of lowercase Latin letters, where $|t|$ is the length of the text $t$. The second line of each test case contains a single integer $n$ ($1 \le n \le 10$) — the number of strings in the set. This is followed by $n$ lines, each containing a string $s_i$ ($1 \le |s_i| \le 10$) consisting only of lowercase Latin letters, where $|s_i|$ — the length of string $s_i$. -----Output----- For each test case, print the answer on a separate line. If it is impossible to color all the letters of the text in red, print a single line containing the number -1. Otherwise, on the first line, print the number $m$ — the minimum number of steps it will take to turn all the letters $t$ red. Then in the next $m$ lines print pairs of indices: $w_j$ and $p_j$ ($1 \le j \le m$), which denote that the string with index $w_j$ was used as a substring to cover the occurrences starting in the text $t$ from position $p_j$. The pairs can be output in any order. If there are several answers, output any of them. -----Examples----- Input 6 bababa 2 ba aba caba 2 bac acab abacabaca 3 aba bac aca baca 3 a c b codeforces 4 def code efo forces aaaabbbbcccceeee 4 eeee cccc aaaa bbbb Output 3 2 2 1 1 2 4 -1 4 1 1 2 6 3 3 3 7 4 3 1 1 2 2 3 1 4 2 4 5 2 1 4 3 1 4 5 2 9 1 13 -----Note----- The first test case is explained in the problem statement. In the second test case, it is impossible to color all the letters of the text in red. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Two players, A and B, play the game using cards with numbers from 0 to 9. First, the two arrange the given n cards face down in a horizontal row. After that, the two players turn their cards face up one by one from the left, and the owner of the card with the larger number takes the two cards. At this time, the sum of the numbers written on the two cards shall be the score of the player who took the card. However, if the same number is written on the two open cards, it is a draw and each player takes one of his own cards. For example, consider the case where the hands of A and B are arranged as shown in the following input examples 1 to 3. However, the input file consists of n + 1 lines, the first line contains the number of cards n for each player, and the i + 1 line (i = 1, 2, ..., n) is A. The numbers on the i-th card from the left and the numbers on the i-th card from the left of B are written in this order, with a blank as the delimiter. That is, from the second row onward of the input file, the left column represents the sequence of A cards, and the right column represents the sequence of B cards. At this time, the scores of A and B after the end of the game are shown in the corresponding output examples, respectively. Create a program that outputs the score of A and the score of B when the game corresponding to the input file ends on one line with a space as a delimiter in this order. However, n ≤ 10000. Input example 1 | Input example 2 | Input example 3 --- | --- | --- 3 | 3 | 3 9 1 | 9 1 | 9 1 5 4 | 5 4 | 5 5 0 8 | 1 0 | 1 8 Output example 1 | Output example 2 | Output example 3 19 8 | 20 0 | 15 14 input The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5. output For each dataset, the score of A and the score of B are output on one line. Input example 3 9 1 5 4 0 8 3 9 1 5 4 Ten 3 9 1 5 5 1 8 0 Output example 19 8 20 0 15 14 Insert a line break after the output of each dataset (after the score of B). The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring. Example Input 3 9 1 5 4 0 8 3 9 1 5 4 1 0 3 9 1 5 5 1 8 0 Output 19 8 20 0 15 14 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. At the end of a busy day, The Chef and his assistants play a game together. The game is not just for fun but also used to decide who will have to clean the kitchen. The Chef is a Game Master, so his concern is how to manage the game but not how to win the game like his assistants do. The game requires players to find the only ball under one of the N cups after their positions are changed in a special way. At the beginning of the game, The Chef places N cups in a row and put a ball under the C-th cup from the left (the cups are numbered from 1 to N). All players can see the initial position of the ball. Then Chef performs Q flip operations. Each flip operation is defined by two integers L and R such that 1 ≤ L ≤ R ≤ N and consists in reversing the segment [L, R] of cups. Namely, Chef swaps L-th and R-th cups, (L+1)-th and (R−1)-th cups, and so on. After performing all the operations Chef asks his assistants to choose a cup that they think the ball is under it. Who can guess the position of the ball will win the game, and of course, the others will have to clean the kitchen. The Chef doesn't want to check all the N cups at the end of the game. He notes down the value of C and the pairs (L, R) and asked you, the mastered programmer, to determine the cup that contains the ball. ------ Input ------ The first line of the input contains a single integer T, denoting the number of test cases. The description of T test cases follows. The first line of each test case contains three space-separated integers N, C and Q, denoting the total number of cups, the initial position of the ball and the number of flip operations Chef will perform. Each of the following Q lines contains two space-separated integers L and R, denoting the ends of the segment of the current flip operation. ------ Output ------ For each test case output on a separate line the final position of the ball. ------ Constraints ------ $1 ≤ T ≤ 10$ $1 ≤ N ≤ 100000 (10^{5})$ $1 ≤ C ≤ N$ $1 ≤ Q ≤ 10000 (10^{4})$ $1 ≤ L ≤ R ≤ N$ ----- Sample Input 1 ------ 1 5 2 3 1 4 3 5 1 5 ----- Sample Output 1 ------ 1 ----- explanation 1 ------ The row of cups at the beginning of the game and after each flip is shown below. Here '-' means an empty cup and 'B' is the cup that hides the ball, the segment of flip is marked bold. -B--- --B-- ----B B---- Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently, Chef got obsessed with piano. He is a just a rookie in this stuff and can not move his fingers from one key to other fast enough. He discovered that the best way to train finger speed is to play scales. There are different kinds of scales which are divided on the basis of their interval patterns. For instance, major scale is defined by pattern T-T-S-T-T-T-S, where ‘T’ stands for a whole tone whereas ‘S’ stands for a semitone. Two semitones make one tone. To understand how they are being played, please refer to the below image of piano’s octave – two consecutive keys differ by one semitone. If we start playing from first key (note C), then we’ll play all white keys in a row (notes C-D-E-F-G-A-B-C – as you can see C and D differ for a tone as in pattern, and E and F differ for a semitone). This pattern could be played some number of times (in cycle). Each time Chef takes some type of a scale and plays using some number of octaves. Sometimes Chef can make up some scales, so please don’t blame him if you find some scale that does not exist in real world. Formally, you have a set of 12 keys (i.e. one octave) and you have N such sets in a row. So in total, you have 12*N keys. You also have a pattern that consists of letters 'T' and 'S', where 'T' means move forward for two keys (from key x to key x + 2, and 'S' means move forward for one key (from key x to key x + 1). Now, you can start playing from any of the 12*N keys. In one play, you can repeat the pattern as many times as you want, but you cannot go outside the keyboard. Repeating pattern means that if, for example, you have pattern STTST, you can play STTST as well as STTSTSTTST, as well as STTSTSTTSTSTTST, as well as any number of repeating. For this pattern, if you choose to repeat it once, if you start at some key x, you'll press keys: x (letter 'S')-> x + 1 (letter 'T')-> x + 3 (letter 'T')-> x + 5 (letter 'S') -> x + 6 (letter 'T')-> x + 8. Also 1 ≤ x, x + 8 ≤ 12*N so as to avoid going off the keyboard. You are asked to calculate number of different plays that can be performed. Two plays differ if and only if they start at different keys or patterns are repeated different number of times. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. First line of each test case contains scale’s pattern – string s consisting of letters ‘T’ and ‘S’ only. Second line contains one integer N – number of octaves he’ll be using. -----Output----- For each test case output a single number in a line corresponding to number of different scales he’ll play. -----Constraints----- - 1 ≤ T ≤ 105 - 1 ≤ |S| ≤ 100 - 1 ≤ n ≤ 7 -----Subtasks----- Subtask 1: T < 10 4, N = 1 Subtask 2: No additional constraints. -----Example----- Input: 2 TTTT 1 TTSTTTS 3 Output: 4 36 -----Explanation----- Example case 1. In the first case there is only one octave and Chef can play scale (not in cycle each time) starting with notes C, C#, D, D# - four together. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Karan's company makes software that provides different features based on the version of operating system of the user. For finding which version is more recent, Karan uses the following method: While this function worked for OS versions 10.6, 10.7, 10.8 and 10.9, the Operating system company just released OS version 10.10. Karan's function fails for the new version: ```python compare_versions ("10.9", "10.10"); # returns True, while it should return False ``` Karan now wants to spend some time to right a more robust version comparison function that works for any future version/sub-version updates. Help Karan write this function. Here are a few sample cases: ```python compare_versions("11", "10"); # returns True compare_versions("11", "11"); # returns True compare_versions("10.4.6", "10.4"); # returns True compare_versions("10.4", "11"); # returns False compare_versions("10.4", "10.10"); # returns False compare_versions("10.4.9", "10.5"); # returns False ``` ```haskell compareVersions "11" "10" `shouldBe` GT compareVersions "10.4.6" "10.4" `shouldBe` GT compareVersions "10.10" "10.9" `shouldBe` GT compareVersions xs xs `shouldBe` EQ -- xs is an arbitrary version compareVersions "10" "11" `shouldBe` LT compareVersions "10.4" "10.4.6" `shouldBe` LT compareVersions "10.99" "10.100" `shouldBe` LT ``` It can be assumed that version strings are non empty and only contain numeric literals and the character `'.'`. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. I am a pipe tie craftsman. As long as you get the joints and pipes that connect the pipes, you can connect any pipe. Every day, my master gives me pipes and joints, which I connect and give to my master. But if you have too many pipes, you can't connect them all in one day. Even in such a case, the master smiles and gives me a salary. By the way, I noticed something strange at one point. Often, the salary is higher when all the pipes are not connected than when they are all connected. It's so weird that one day when my boss came, I secretly saw a memo that describes how to calculate my salary. Then, how "The salary is paid by" the number of pipes x the total length of pipes ". However, if they are connected by a joint and become one, it is regarded as one pipe. " It was written. Now I understand why the salary may be cheaper if you connect them all. For example, as shown in the figure below, if you connect all three pipes of length 1 and two joints of length 2 to make one pipe of length 1 + 2 + 1 + 2 + 1 = 7, 1 × (7) ) = 7. However, if you use only one joint and make two pipes with a length of 1 + 2 + 1 = 4 and a pipe with a length of 1, 2 × (4 + 1) = 10, so you will get more salary than connecting all of them. .. <image> I don't know why my boss decides my salary this way, but I know how I can get more salary! Now, create a program that calculates the maximum amount of salary you can get given the number of pipes. input The input consists of multiple datasets. The end of the input is indicated by a single zero line. Each dataset is given in the following format. n p1 ... pn j1 ... jn-1 The number of pipes n (2 ≤ n ≤ 65000) is given in the first line. The second line consists of n integers separated by a single space. pi (1 ≤ pi ≤ 1000) indicates the length of the i-th pipe. The third line consists of n-1 integers separated by one space. ji (1 ≤ ji ≤ 1000) indicates the length of the i-th joint. The i-th joint can connect only the i-th and i + 1-th pipes. The length of the connected pipe is pi + ji + pi + 1. The number of datasets does not exceed 100. output For each dataset, print the maximum amount of salary you can get on one line. For datasets given as input, the output value must always fall within the range of 32-bit unsigned integers. Example Input 3 1 1 1 3 3 4 3 3 3 3 1 1 1 5 1 2 3 4 5 4 3 2 1 0 Output 12 48 76 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem: You've got some training set of documents. For each document you know its subject. The subject in this problem is an integer from 1 to 3. Each of these numbers has a physical meaning. For instance, all documents with subject 3 are about trade. You can download the training set of documents at the following link: http://download4.abbyy.com/a2/X2RZ2ZWXBG5VYWAL61H76ZQM/train.zip. The archive contains three directories with names "1", "2", "3". Directory named "1" contains documents on the 1-st subject, directory "2" contains documents on the 2-nd subject, and directory "3" contains documents on the 3-rd subject. Each document corresponds to exactly one file from some directory. All documents have the following format: the first line contains the document identifier, the second line contains the name of the document, all subsequent lines contain the text of the document. The document identifier is used to make installing the problem more convenient and has no useful information for the participants. You need to write a program that should indicate the subject for a given document. It is guaranteed that all documents given as input to your program correspond to one of the three subjects of the training set. Input The first line contains integer id (0 ≤ id ≤ 106) — the document identifier. The second line contains the name of the document. The third and the subsequent lines contain the text of the document. It is guaranteed that the size of any given document will not exceed 10 kilobytes. The tests for this problem are divided into 10 groups. Documents of groups 1 and 2 are taken from the training set, but their identifiers will not match the identifiers specified in the training set. Groups from the 3-rd to the 10-th are roughly sorted by the author in ascending order of difficulty (these groups contain documents which aren't present in the training set). Output Print an integer from 1 to 3, inclusive — the number of the subject the given document corresponds to. Examples Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.