question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors. Polycaprus calculated that the optimal celling price for such scissors would be p bourles. However, he read somewhere that customers are attracted by prices that say something like "Special Offer! Super price 999 bourles!". So Polycarpus decided to lower the price a little if it leads to the desired effect. Polycarpus agrees to lower the price by no more than d bourles so that the number of nines at the end of the resulting price is maximum. If there are several ways to do it, he chooses the maximum possible price. Note, Polycarpus counts only the trailing nines in a price. Input The first line contains two integers p and d (1 ≀ p ≀ 1018; 0 ≀ d < p) β€” the initial price of scissors and the maximum possible price reduction. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier. Output Print the required price β€” the maximum price that ends with the largest number of nines and that is less than p by no more than d. The required number shouldn't have leading zeroes. Examples Input 1029 102 Output 999 Input 27191 17 Output 27189 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Once upon a time, a CodeWarrior, after reading a [discussion on what can be the plural](http://www.codewars.com/kata/plural/discuss/javascript), took a look at [this page](http://en.wikipedia.org/wiki/Grammatical_number#Types_of_number ) and discovered that **more than 1** "kind of plural" may exist. For example [Sursurunga Language](http://en.wikipedia.org/wiki/Sursurunga_language) distinguishes 5 types of numbers: **singular** (1 thing), **dual** (2 things), '**trial**' or '**lesser paucal**' (3 or 4), '**greater paucal**' (more than 4) and **plural** (many). In this kata, you'll have to handle only four types of numbers: - **singular**: 0 or 1 thing - **dual**: 2 things - **paucal**: 3 to 9 things - **plural**: more than 9 things To add some flavor the **number-marker** will not be added in same places: - **singular**, no marker : `1 cat` - **dual**, prefixed "`bu`" : `2 cats -> 2 bucat` - **paucal**, suffixed "`zo`" : `4 cats -> 4 catzo` - **plural**, "circumfixed `ga`" : `100 cats -> 100 gacatga` As you all ("hawk eyes") have seen, the final `s` of english plural **disappears**. ( btw these markers, of course, have absolutely nothing to do with true sursurunga language, we're just talking about "**pig**-sursurunga" with **pig** as **pig** in "**pig latin**" ) ## Your Job . . . . . . if you accept it, will be to write a `sursurungal` function which get a `string` as argument and returns this string with words in it eventually converted to their "pig-sursurunga number type". If a `number` ( *ie* 1 or more digit ) + a `space` + a `word` ( letters ) are found then the word should be converted. **Each** group of `number+space+word` found in the string should be evaluated. ### Examples : You may assume at least 1 `number+space+word` group will be provided. **Beware** `s` of english plural should be removed, not ending `s` of some singular words ( *eg* "kiss" ) 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. Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light. Three mirrors of length N are set so that they form an equilateral triangle. Let the vertices of the triangle be a, b and c. Inside the triangle, the rifle is placed at the point p on segment ab such that ap = X. (The size of the rifle is negligible.) Now, the rifle is about to fire a ray of Mysterious Light in the direction of bc. The ray of Mysterious Light will travel in a straight line, and will be reflected by mirrors, in the same ways as "ordinary" light. There is one major difference, though: it will be also reflected by its own trajectory as if it is a mirror! When the ray comes back to the rifle, the ray will be absorbed. The following image shows the ray's trajectory where N = 5 and X = 2. btriangle.png It can be shown that the ray eventually comes back to the rifle and is absorbed, regardless of the values of N and X. Find the total length of the ray's trajectory. Constraints * 2≦N≦10^{12} * 1≦X≦N-1 * N and X are integers. Input The input is given from Standard Input in the following format: N X Output Print the total length of the ray's trajectory. Example Input 5 2 Output 12 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let us define the oddness of a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n} as \sum_{i = 1}^n |i - p_i|. Find the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7. -----Constraints----- - All values in input are integers. - 1 \leq n \leq 50 - 0 \leq k \leq n^2 -----Input----- Input is given from Standard Input in the following format: n k -----Output----- Print the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7. -----Sample Input----- 3 2 -----Sample Output----- 2 There are six permutations of {1,\ 2,\ 3}. Among them, two have oddness of 2: {2,\ 1,\ 3} and {1,\ 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. Let w be a string consisting of lowercase letters. We will call w beautiful if the following condition is satisfied: - Each lowercase letter of the English alphabet occurs even number of times in w. You are given the string w. Determine if w is beautiful. -----Constraints----- - 1 \leq |w| \leq 100 - w consists of lowercase letters (a-z). -----Input----- The input is given from Standard Input in the following format: w -----Output----- Print Yes if w is beautiful. Print No otherwise. -----Sample Input----- abaccaba -----Sample Output----- Yes a occurs four times, b occurs twice, c occurs twice and the other letters occur zero times. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew $n$ distinct lines, given by equations $y = x + p_i$ for some distinct $p_1, p_2, \ldots, p_n$. Then JLS drew on the same paper sheet $m$ distinct lines given by equations $y = -x + q_i$ for some distinct $q_1, q_2, \ldots, q_m$. DLS and JLS are interested in counting how many line pairs have integer intersection points, i.e. points with both coordinates that are integers. Unfortunately, the lesson will end up soon, so DLS and JLS are asking for your help. -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$), the number of test cases in the input. Then follow the test case descriptions. The first line of a test case contains an integer $n$ ($1 \le n \le 10^5$), the number of lines drawn by DLS. The second line of a test case contains $n$ distinct integers $p_i$ ($0 \le p_i \le 10^9$) describing the lines drawn by DLS. The integer $p_i$ describes a line given by the equation $y = x + p_i$. The third line of a test case contains an integer $m$ ($1 \le m \le 10^5$), the number of lines drawn by JLS. The fourth line of a test case contains $m$ distinct integers $q_i$ ($0 \le q_i \le 10^9$) describing the lines drawn by JLS. The integer $q_i$ describes a line given by the equation $y = -x + q_i$. The sum of the values of $n$ over all test cases in the input does not exceed $10^5$. Similarly, the sum of the values of $m$ over all test cases in the input does not exceed $10^5$. In hacks it is allowed to use only one test case in the input, so $t=1$ should be satisfied. -----Output----- For each test case in the input print a single integerΒ β€” the number of line pairs with integer intersection points. -----Example----- Input 3 3 1 3 2 2 0 3 1 1 1 1 1 2 1 1 Output 3 1 0 -----Note----- The picture shows the lines from the first test case of the example. Black circles denote intersection points with integer coordinates. [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. Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? -----Input----- The single line contains two space separated integers n, m (0 < n ≀ 10000, 1 < m ≀ 10). -----Output----- Print a single integer β€” the minimal number of moves being a multiple of m. If there is no way he can climb satisfying condition print - 1 instead. -----Examples----- Input 10 2 Output 6 Input 3 5 Output -1 -----Note----- For the first sample, Dreamoon could climb in 6 moves with following sequence of steps: {2, 2, 2, 2, 1, 1}. For the second sample, there are only three valid sequence of steps {2, 1}, {1, 2}, {1, 1, 1} with 2, 2, and 3 steps respectively. All these numbers are not multiples of 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. You are going to eat X red apples and Y green apples. You have A red apples of deliciousness p_1,p_2, \dots, p_A, B green apples of deliciousness q_1,q_2, \dots, q_B, and C colorless apples of deliciousness r_1,r_2, \dots, r_C. Before eating a colorless apple, you can paint it red or green, and it will count as a red or green apple, respectively. From the apples above, you will choose the apples to eat while making the sum of the deliciousness of the eaten apples as large as possible. Find the maximum possible sum of the deliciousness of the eaten apples that can be achieved when optimally coloring zero or more colorless apples. -----Constraints----- - 1 \leq X \leq A \leq 10^5 - 1 \leq Y \leq B \leq 10^5 - 1 \leq C \leq 10^5 - 1 \leq p_i \leq 10^9 - 1 \leq q_i \leq 10^9 - 1 \leq r_i \leq 10^9 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: X Y A B C p_1 p_2 ... p_A q_1 q_2 ... q_B r_1 r_2 ... r_C -----Output----- Print the maximum possible sum of the deliciousness of the eaten apples. -----Sample Input----- 1 2 2 2 1 2 4 5 1 3 -----Sample Output----- 12 The maximum possible sum of the deliciousness of the eaten apples can be achieved as follows: - Eat the 2-nd red apple. - Eat the 1-st green apple. - Paint the 1-st colorless apple green and eat 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. Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than k characters, it will be very suspicious. Find the least number of distinct characters that can remain in the string after no more than k characters are deleted. You also have to find any possible way to delete the characters. Input The first input data line contains a string whose length is equal to n (1 ≀ n ≀ 105). The string consists of lowercase Latin letters. The second line contains the number k (0 ≀ k ≀ 105). Output Print on the first line the only number m β€” the least possible number of different characters that could remain in the given string after it loses no more than k characters. Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly m distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly m distinct characters, print any of them. Examples Input aaaaa 4 Output 1 aaaaa Input abacaba 4 Output 1 aaaa Input abcdefgh 10 Output 0 Note In the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length. In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string. In the third sample you are given a line whose length is equal to 8, and k = 10, so that the whole line can be deleted. The correct answer is 0 and an empty string. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has a string $s[1 \dots n]$ of length $n$ consisting of decimal digits. Polycarp performs the following operation with the string $s$ no more than once (i.e. he can perform operation $0$ or $1$ time): Polycarp selects two numbers $i$ and $j$ ($1 \leq i \leq j \leq n$) and removes characters from the $s$ string at the positions $i, i+1, i+2, \ldots, j$ (i.e. removes substring $s[i \dots j]$). More formally, Polycarp turns the string $s$ into the string $s_1 s_2 \ldots s_{i-1} s_{j+1} s_{j+2} \ldots s_{n}$. For example, the string $s = $"20192020" Polycarp can turn into strings: "2020" (in this case $(i, j)=(3, 6)$ or $(i, j)=(1, 4)$); "2019220" (in this case $(i, j)=(6, 6)$); "020" (in this case $(i, j)=(1, 5)$); other operations are also possible, only a few of them are listed above. Polycarp likes the string "2020" very much, so he is wondering if it is possible to turn the string $s$ into a string "2020" in no more than one operation? Note that you can perform zero operations. -----Input----- The first line contains a positive integer $t$ ($1 \leq t \leq 1000 $) β€” number of test cases in the test. Then $t$ test cases follow. The first line of each test case contains an integer $n$ ($4 \leq n \leq 200$) β€” length of the string $s$. The next line contains a string $s$ of length $n$ consisting of decimal digits. It is allowed that the string $s$ starts with digit 0. -----Output----- For each test case, output on a separate line: "YES" if Polycarp can turn the string $s$ into a string "2020" in no more than one operation (i.e. he can perform $0$ or $1$ operation); "NO" otherwise. You may print every letter of "YES" and "NO" in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). -----Examples----- Input 6 8 20192020 8 22019020 4 2020 5 20002 6 729040 6 200200 Output YES YES YES NO NO NO -----Note----- In the first test case, Polycarp could choose $i=3$ and $j=6$. In the second test case, Polycarp could choose $i=2$ and $j=5$. In the third test case, Polycarp did not perform any operations with the string. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has sequence a consisting of n integers. The subsequence of the sequence a is such subsequence that can be obtained from a by removing zero or more of its elements. Two sequences are considered different if index sets of numbers included in them are different. That is, the values ​of the elements ​do not matter in the comparison of subsequences. In particular, any sequence of length n has exactly 2n different subsequences (including an empty subsequence). A subsequence is considered lucky if it has a length exactly k and does not contain two identical lucky numbers (unlucky numbers can be repeated any number of times). Help Petya find the number of different lucky subsequences of the sequence a. As Petya's parents don't let him play with large numbers, you should print the result modulo prime number 1000000007 (109 + 7). Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n integers ai (1 ≀ ai ≀ 109) β€” the sequence a. Output On the single line print the single number β€” the answer to the problem modulo prime number 1000000007 (109 + 7). Examples Input 3 2 10 10 10 Output 3 Input 4 2 4 4 7 7 Output 4 Note In the first sample all 3 subsequences of the needed length are considered lucky. In the second sample there are 4 lucky subsequences. For them the sets of indexes equal (the indexation starts from 1): {1, 3}, {1, 4}, {2, 3} and {2, 4}. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are $n$ startups. Startups can be active or acquired. If a startup is acquired, then that means it has exactly one active startup that it is following. An active startup can have arbitrarily many acquired startups that are following it. An active startup cannot follow any other startup. The following steps happen until there is exactly one active startup. The following sequence of steps takes exactly 1 day. Two distinct active startups $A$, $B$, are chosen uniformly at random. A fair coin is flipped, and with equal probability, $A$ acquires $B$ or $B$ acquires $A$ (i.e. if $A$ acquires $B$, then that means $B$'s state changes from active to acquired, and its starts following $A$). When a startup changes from active to acquired, all of its previously acquired startups become active. For example, the following scenario can happen: Let's say $A$, $B$ are active startups. $C$, $D$, $E$ are acquired startups under $A$, and $F$, $G$ are acquired startups under $B$: [Image] Active startups are shown in red. If $A$ acquires $B$, then the state will be $A$, $F$, $G$ are active startups. $C$, $D$, $E$, $B$ are acquired startups under $A$. $F$ and $G$ have no acquired startups: $G$ If instead, $B$ acquires $A$, then the state will be $B$, $C$, $D$, $E$ are active startups. $F$, $G$, $A$ are acquired startups under $B$. $C$, $D$, $E$ have no acquired startups: [Image] You are given the initial state of the startups. For each startup, you are told if it is either acquired or active. If it is acquired, you are also given the index of the active startup that it is following. You're now wondering, what is the expected number of days needed for this process to finish with exactly one active startup at the end. It can be shown the expected number of days can be written as a rational number $P/Q$, where $P$ and $Q$ are co-prime integers, and $Q \not= 0 \pmod{10^9+7}$. Return the value of $P \cdot Q^{-1}$ modulo $10^9+7$. -----Input----- The first line contains a single integer $n$ ($2 \leq n \leq 500$), the number of startups. The next line will contain $n$ space-separated integers $a_1, a_2, \ldots, a_n$ ($a_i = -1$ or $1 \leq a_i \leq n$). If $a_i = -1$, then that means startup $i$ is active. Otherwise, if $1 \leq a_i \leq n$, then startup $i$ is acquired, and it is currently following startup $a_i$. It is guaranteed if $a_i \not= -1$, then $a_{a_i} =-1$ (that is, all startups that are being followed are active). -----Output----- Print a single integer, the expected number of days needed for the process to end with exactly one active startup, modulo $10^9+7$. -----Examples----- Input 3 -1 -1 -1 Output 3 Input 2 2 -1 Output 0 Input 40 3 3 -1 -1 4 4 -1 -1 -1 -1 -1 10 10 10 10 10 10 4 20 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 3 3 3 3 3 3 3 3 Output 755808950 -----Note----- In the first sample, there are three active startups labeled $1$, $2$ and $3$, and zero acquired startups. Here's an example of how one scenario can happen Startup $1$ acquires startup $2$ (This state can be represented by the array $[-1, 1, -1]$) Startup $3$ acquires startup $1$ (This state can be represented by the array $[3, -1, -1]$) Startup $2$ acquires startup $3$ (This state can be represented by the array $[-1, -1, 2]$). Startup $2$ acquires startup $1$ (This state can be represented by the array $[2, -1, 2]$). At this point, there is only one active startup, and this sequence of steps took $4$ days. It can be shown the expected number of days is $3$. For the second sample, there is only one active startup, so we need zero days. For the last sample, remember to take the answer modulo $10^9+7$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation. A set ρ of pairs (a, b) of elements of some set A is called a binary relation on set A. For two elements a and b of the set A we say that they are in relation ρ, if pair <image>, in this case we use a notation <image>. Binary relation is equivalence relation, if: 1. It is reflexive (for any a it is true that <image>); 2. It is symmetric (for any a, b it is true that if <image>, then <image>); 3. It is transitive (if <image> and <image>, than <image>). Little Johnny is not completely a fool and he noticed that the first condition is not necessary! Here is his "proof": Take any two elements, a and b. If <image>, then <image> (according to property (2)), which means <image> (according to property (3)). It's very simple, isn't it? However, you noticed that Johnny's "proof" is wrong, and decided to show him a lot of examples that prove him wrong. Here's your task: count the number of binary relations over a set of size n such that they are symmetric, transitive, but not an equivalence relations (i.e. they are not reflexive). Since their number may be very large (not 0, according to Little Johnny), print the remainder of integer division of this number by 109 + 7. Input A single line contains a single integer n (1 ≀ n ≀ 4000). Output In a single line print the answer to the problem modulo 109 + 7. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 10 Note If n = 1 there is only one such relation β€” an empty one, i.e. <image>. In other words, for a single element x of set A the following is hold: <image>. If n = 2 there are three such relations. Let's assume that set A consists of two elements, x and y. Then the valid relations are <image>, ρ = {(x, x)}, ρ = {(y, y)}. It is easy to see that the three listed binary relations are symmetric and transitive relations, but they are not equivalence relations. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015. Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016. Limak wants to prove how responsible a bear he is. He is going to regularly save candies for the entire year 2016! He considers various saving plans. He can save one candy either on some fixed day of the week or on some fixed day of the month. Limak chose one particular plan. He isn't sure how many candies he will save in the 2016 with his plan. Please, calculate it and tell him. -----Input----- The only line of the input is in one of the following two formats: "x of week" where x (1 ≀ x ≀ 7) denotes the day of the week. The 1-st day is Monday and the 7-th one is Sunday. "x of month" where x (1 ≀ x ≀ 31) denotes the day of the month. -----Output----- Print one integerΒ β€” the number of candies Limak will save in the year 2016. -----Examples----- Input 4 of week Output 52 Input 30 of month Output 11 -----Note----- Polar bears use the Gregorian calendar. It is the most common calendar and you likely use it too. You can read about it on Wikipedia if you want to – https://en.wikipedia.org/wiki/Gregorian_calendar. The week starts with Monday. In the first sample Limak wants to save one candy on each Thursday (the 4-th day of the week). There are 52 Thursdays in the 2016. Thus, he will save 52 candies in total. In the second sample Limak wants to save one candy on the 30-th day of each month. There is the 30-th day in exactly 11 months in the 2016Β β€” all months but February. It means that Limak will save 11 candies in total. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis. You planned a trip along the axis. In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0. However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i. You will visit the remaining spots as planned in the order they are numbered. You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned. For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled. Constraints * 2 \leq N \leq 10^5 * -5000 \leq A_i \leq 5000 (1 \leq i \leq N) * All input values are integers. Input Input is given from Standard Input in the following format: N A_1 A_2 ... A_N Output Print N lines. In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled. Examples Input 3 3 5 -1 Output 12 8 10 Input 5 1 1 1 2 0 Output 4 4 4 2 4 Input 6 -679 -2409 -3258 3095 -3291 -4462 Output 21630 21630 19932 8924 21630 19288 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was. Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on. Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active. Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake. -----Input----- The first line contains integer n (1 ≀ n ≀ 1000) β€” the number of gears. The second line contains n digits a_1, a_2, ..., a_{n} (0 ≀ a_{i} ≀ n - 1) β€” the sequence of active teeth: the active tooth of the i-th gear contains number a_{i}. -----Output----- In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise. -----Examples----- Input 3 1 0 0 Output Yes Input 5 4 2 1 4 3 Output Yes Input 4 0 2 3 1 Output No -----Note----- In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 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. Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three integers x_1, x_2, x_3 and three more integers y_1, y_2, y_3, such that x_1 < x_2 < x_3, y_1 < y_2 < y_3 and the eight point set consists of all points (x_{i}, y_{j}) (1 ≀ i, j ≀ 3), except for point (x_2, y_2). You have a set of eight points. Find out if Gerald can use this set? -----Input----- The input consists of eight lines, the i-th line contains two space-separated integers x_{i} and y_{i} (0 ≀ x_{i}, y_{i} ≀ 10^6). You do not have any other conditions for these points. -----Output----- In a single line print word "respectable", if the given set of points corresponds to Gerald's decency rules, and "ugly" otherwise. -----Examples----- Input 0 0 0 1 0 2 1 0 1 2 2 0 2 1 2 2 Output respectable Input 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 Output ugly Input 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 Output ugly Read the inputs from stdin solve the problem and write the answer to stdout (do 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$ lamps on a line, numbered from $1$ to $n$. Each one has an initial state off ($0$) or on ($1$). You're given $k$ subsets $A_1, \ldots, A_k$ of $\{1, 2, \dots, n\}$, such that the intersection of any three subsets is empty. In other words, for all $1 \le i_1 < i_2 < i_3 \le k$, $A_{i_1} \cap A_{i_2} \cap A_{i_3} = \varnothing$. In one operation, you can choose one of these $k$ subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation. Let $m_i$ be the minimum number of operations you have to do in order to make the $i$ first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between $i+1$ and $n$), they can be either off or on. You have to compute $m_i$ for all $1 \le i \le n$. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le n, k \le 3 \cdot 10^5$). The second line contains a binary string of length $n$, representing the initial state of each lamp (the lamp $i$ is off if $s_i = 0$, on if $s_i = 1$). The description of each one of the $k$ subsets follows, in the following format: The first line of the description contains a single integer $c$ ($1 \le c \le n$) Β β€” the number of elements in the subset. The second line of the description contains $c$ distinct integers $x_1, \ldots, x_c$ ($1 \le x_i \le n$) Β β€” the elements of the subset. It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. -----Output----- You must output $n$ lines. The $i$-th line should contain a single integer $m_i$ Β β€” the minimum number of operations required to make the lamps $1$ to $i$ be simultaneously on. -----Examples----- Input 7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 Output 1 2 3 3 3 3 3 Input 8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 Output 1 1 1 1 1 1 4 4 Input 5 3 00011 3 1 2 3 1 4 3 3 4 5 Output 1 1 1 1 1 Input 19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 Output 0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 -----Note----- In the first example: For $i = 1$, we can just apply one operation on $A_1$, the final states will be $1010110$; For $i = 2$, we can apply operations on $A_1$ and $A_3$, the final states will be $1100110$; For $i \ge 3$, we can apply operations on $A_1$, $A_2$ and $A_3$, the final states will be $1111111$. In the second example: For $i \le 6$, we can just apply one operation on $A_2$, the final states will be $11111101$; For $i \ge 7$, we can apply operations on $A_1, A_3, A_4, A_6$, the final states will be $11111111$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≀ i, j ≀ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≀ x ≀ 100) β€” the required sharpness of the matrix. Output Print a single number β€” the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a binary matrix $A$ of size $n \times n$. Let's denote an $x$-compression of the given matrix as a matrix $B$ of size $\frac{n}{x} \times \frac{n}{x}$ such that for every $i \in [1, n], j \in [1, n]$ the condition $A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil]$ is met. Obviously, $x$-compression is possible only if $x$ divides $n$, but this condition is not enough. For example, the following matrix of size $2 \times 2$ does not have any $2$-compression: $01$ $10$ For the given matrix $A$, find maximum $x$ such that an $x$-compression of this matrix is possible. Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input. -----Input----- The first line contains one number $n$ ($4 \le n \le 5200$) β€” the number of rows and columns in the matrix $A$. It is guaranteed that $n$ is divisible by $4$. Then the representation of matrix follows. Each of $n$ next lines contains $\frac{n}{4}$ one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from $0$ to $9$ or as uppercase Latin letters from $A$ to $F$). Binary representation of each of these numbers denotes next $4$ elements of the matrix in the corresponding row. For example, if the number $B$ is given, then the corresponding elements are 1011, and if the number is $5$, then the corresponding elements are 0101. Elements are not separated by whitespaces. -----Output----- Print one number: maximum $x$ such that an $x$-compression of the given matrix is possible. -----Examples----- Input 8 E7 E7 E7 00 00 E7 E7 E7 Output 1 Input 4 7 F F F Output 1 -----Note----- The first example corresponds to the matrix: $11100111$ $11100111$ $11100111$ $00000000$ $00000000$ $11100111$ $11100111$ $11100111$ It is easy to see that the answer on this example is $1$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of $n$ different bloggers. Blogger numbered $i$ has $a_i$ followers. Since Masha has a limited budget, she can only sign a contract with $k$ different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers. Help her, find the number of ways to select $k$ bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers). For example, if $n=4$, $k=3$, $a=[1, 3, 1, 2]$, then Masha has two ways to select $3$ bloggers with the maximum total number of followers: conclude contracts with bloggers with numbers $1$, $2$ and $4$. In this case, the number of followers will be equal to $a_1 + a_2 + a_4 = 6$. conclude contracts with bloggers with numbers $2$, $3$ and $4$. In this case, the number of followers will be equal to $a_2 + a_3 + a_4 = 6$. Since the answer can be quite large, output it modulo $10^9+7$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) β€” the number of test cases. Then $t$ test cases follow. The first line of each test case contains two integers $n$ and $k$ ($1 \le k \le n \le 1000$) β€” the number of bloggers and how many of them you can sign a contract with. The second line of each test case contains $n$ integers $a_1, a_2, \ldots a_n$ ($1 \le a_i \le n$) β€” the number of followers of each blogger. It is guaranteed that the sum of $n$ over all test cases does not exceed $1000$. -----Output----- For each test case, on a separate line output one integer β€” the number of ways to select $k$ bloggers so that the total number of their followers is maximum possible. -----Examples----- Input 3 4 3 1 3 1 2 4 2 1 1 1 1 2 1 1 2 Output 2 6 1 -----Note----- The test case is explained in the statements. In the second test case, the following ways are valid: conclude contracts with bloggers with numbers $1$ and $2$. In this case, the number of followers will be equal to $a_1 + a_2 = 2$; conclude contracts with bloggers with numbers $1$ and $3$. In this case, the number of followers will be equal to $a_1 + a_3 = 2$; conclude contracts with bloggers with numbers $1$ and $4$. In this case, the number of followers will be equal to $a_1 + a_4 = 2$; conclude contracts with bloggers with numbers $2$ and $3$. In this case, the number of followers will be equal to $a_2 + a_3 = 2$; conclude contracts with bloggers with numbers $2$ and $4$. In this case, the number of followers will be equal to $a_2 + a_4 = 2$; conclude contracts with bloggers with numbers $3$ and $4$. In this case, the number of followers will be equal to $a_3 + a_4 = 2$. In the third test case, the following ways are valid: concludes a contract with a blogger with the number $2$. In this case, the number of followers will be equal to $a_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. For this exercise you will create a global flatten method. The method takes in any number of arguments and flattens them into a single array. If any of the arguments passed in are an array then the individual objects within the array will be flattened so that they exist at the same level as the other arguments. Any nested arrays, no matter how deep, should be flattened into the single array result. The following are examples of how this function would be used and what the expected results would be: ```python flatten(1, [2, 3], 4, 5, [6, [7]]) # returns [1, 2, 3, 4, 5, 6, 7] flatten('a', ['b', 2], 3, None, [[4], ['c']]) # returns ['a', 'b', 2, 3, None, 4, '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. Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number. Petya can ask questions like: "Is the unknown number divisible by number y?". The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of. Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers yi, he should ask the questions about. Input A single line contains number n (1 ≀ n ≀ 103). Output Print the length of the sequence of questions k (0 ≀ k ≀ n), followed by k numbers β€” the questions yi (1 ≀ yi ≀ n). If there are several correct sequences of questions of the minimum length, you are allowed to print any of them. Examples Input 4 Output 3 2 4 3 Input 6 Output 4 2 4 3 5 Note The sequence from the answer to the first sample test is actually correct. If the unknown number is not divisible by one of the sequence numbers, it is equal to 1. If the unknown number is divisible by 4, it is 4. If the unknown number is divisible by 3, then the unknown number is 3. Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths) Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe) After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way. Thus, if the blinds consist of k pieces each d in length, then they are of form of a rectangle of k Γ— d bourlemeters. Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than l bourlemeter. The window is of form of a rectangle with side lengths as positive integers. Input The first output line contains two space-separated integers n and l (1 ≀ n, l ≀ 100). They are the number of stripes in the warehouse and the minimal acceptable length of a blind stripe in bourlemeters. The second line contains space-separated n integers ai. They are the lengths of initial stripes in bourlemeters (1 ≀ ai ≀ 100). Output Print the single number β€” the maximal area of the window in square bourlemeters that can be completely covered. If no window with a positive area that can be covered completely without breaking any of the given rules exist, then print the single number 0. Examples Input 4 2 1 2 3 4 Output 8 Input 5 3 5 5 7 3 1 Output 15 Input 2 3 1 2 Output 0 Note In the first sample test the required window is 2 Γ— 4 in size and the blinds for it consist of 4 parts, each 2 bourlemeters long. One of the parts is the initial stripe with the length of 2, the other one is a part of a cut stripe with the length of 3 and the two remaining stripes are parts of a stripe with the length of 4 cut in halves. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Related to MrZizoScream's Product Array kata. You might want to solve that one first :) ```if:javascript **Note:** Node 10 has now been enabled, and you can now use its BigInt capabilities if you wish, though your resulting array must still contain strings (e.g. "99999999999", not 9999999999n) Pre-node 10: You will need to use the BigNumber.js library! Please use `.toFixed(0)` or `.toPrecision()` to round instead of `.toString(10)`, as the latter is _very_ slow ``` This is an adaptation of a problem I came across on LeetCode. Given an array of numbers, your task is to return a new array where each index (`new_array[i]`) is equal to the product of the original array, except for the number at that index (`array[i]`). **Two things to keep in mind:** * Zeroes will be making their way into some of the arrays you are given * O(n^2) solutions will not pass. Examples: **Note**: All inputs will be valid arrays of nonzero length. Have fun! Please upvote if you enjoyed :) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Solve the mystery. Input: String which consists of words(all the characters of any word are lower case letters) and punctuation marks(consists of {'.' , ',' , '?' , '!'}). Also every input string consists of one '*' in it. It is guaranteed that strings doesn't start or end with space(' ') and only one answer exists for each case. Output: Lower case letter. Constrains: 1 ≀ t ≀ 1000 2 ≀ length of string(n) ≀ 100 Problem Setter : Vinay Kumar SAMPLE INPUT 7 k! cats s*ack. ah, s*tan sees natasha! aibohphobi* al lets della call ed ste*la. amy, must i jujitsu *y ma? aerata pat a*ea. lollipop i * lol. SAMPLE OUTPUT t a a l m r l Read the inputs from stdin solve the problem and write the answer to stdout (do 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 reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given. Circle inside a rectangle Constraints * $ -100 \leq x, y \leq 100$ * $ 0 < W, H, r \leq 100$ Input Five integers $W$, $H$, $x$, $y$ and $r$ separated by a single space are given in a line. Output Print "Yes" if the circle is placed inside the rectangle, otherwise "No" in a line. Examples Input 5 4 2 2 1 Output Yes Input 5 4 2 4 1 Output No Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab Read the inputs from stdin solve the problem and write the answer to stdout (do 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 to write a function to transpose a guitar tab up or down a number of semitones. The amount to transpose is a number, positive or negative. The tab is given as an array, with six elements for each guitar string (fittingly passed as strings). Output your tab in a similar form. Guitar tablature (or 'tab') is an alternative to sheet music, where notes are replaced by fret numbers and the five lines of the staff are replaced by six lines to represent each of the guitar's strings. It is still read from left to right like sheet music, and notes written directly above each other are played at the same time. For example, Led Zeppelin's Stairway to Heaven begins: ``` e|-------5-7-----7-|-8-----8-2-----2-|-0---------0-----|-----------------| B|-----5-----5-----|---5-------3-----|---1---1-----1---|-0-1-1-----------| G|---5---------5---|-----5-------2---|-----2---------2-|-0-2-2-----------| D|-7-------6-------|-5-------4-------|-3---------------|-----------------| A|-----------------|-----------------|-----------------|-2-0-0---0--/8-7-| E|-----------------|-----------------|-----------------|-----------------| ``` Transposed up two semitones, it would look like this: ``` e|-------7-9-----9-|-10-----10-4-----4-|-2---------2-----|------------------| B|-----7-----7-----|----7--------5-----|---3---3-----3---|-2-3-3------------| G|---7---------7---|------7--------4---|-----4---------4-|-2-4-4------------| D|-9-------8-------|-7---------6-------|-5---------------|------------------| A|-----------------|-------------------|-----------------|-4-2-2---2--/10-9-| E|-----------------|-------------------|-----------------|------------------| ``` Note how when the 8th fret note on the top string in bar 2 gets transposed to the 10th fret, extra '-' are added on the other strings below so as to retain the single '-' that originally separated that beat (i.e. column) from the following note – fret 7 on the B string. Each beat must retain at least one '-' separator before the next, to keep the tab legible. The inputted test tabs all obey this convention. Electric guitars usually have 22 frets, with the 0th fret being an open string. If your fret numbers transpose to either negative values or values over 22, you should return 'Out of frets!' (and probably detune your guitar). Tests include some randomly generated guitar tabs, which come with no guarantee of musical quality and/or playability...! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In the computer network of the Berland State University there are n routers numbered from 1 to n. Some pairs of routers are connected by patch cords. Information can be transmitted over patch cords in both direction. The network is arranged in such a way that communication between any two routers (directly or through other routers) is possible. There are no cycles in the network, so there is only one path between each pair of routers over patch cords. Unfortunately, the exact topology of the network was lost by administrators. In order to restore it, the following auxiliary information was collected. For each patch cord p, directly connected to the router i, list of routers located behind the patch cord p relatively i is known. In other words, all routers path from which to the router i goes through p are known. So for each router i there are ki lists, where ki is the number of patch cords connected to i. For example, let the network consists of three routers connected in chain 1 - 2 - 3. Then: * the router 1: for the single patch cord connected to the first router there is a single list containing two routers: 2 and 3; * the router 2: for each of the patch cords connected to the second router there is a list: one list contains the router 1 and the other β€” the router 3; * the router 3: for the single patch cord connected to the third router there is a single list containing two routers: 1 and 2. Your task is to help administrators to restore the network topology, i. e. to identify all pairs of routers directly connected by a patch cord. Input The first line contains a single integer n (2 ≀ n ≀ 1000) β€” the number of routers in the network. The i-th of the following n lines contains a description of the lists for the router i. The description of each list begins with the number of routers in it. Then the symbol ':' follows, and after that the numbers of routers from the list are given. This numbers are separated by comma. Lists are separated by symbol '-'. It is guaranteed, that for each router i the total number of routers in its lists equals to n - 1 and all the numbers in lists of each router are distinct. For each router i lists do not contain the number i. Output Print -1 if no solution exists. In the other case print to the first line n - 1 β€” the total number of patch cords in the network. In each of the following n - 1 lines print two integers β€” the routers which are directly connected by a patch cord. Information about each patch cord must be printed exactly once. Patch cords and routers can be printed in arbitrary order. Examples Input 3 2:3,2 1:1-1:3 2:1,2 Output 2 2 1 2 3 Input 5 4:2,5,3,4 1:4-1:1-2:5,3 4:4,5,2,1 4:2,1,3,5 1:3-3:4,2,1 Output 4 2 1 2 4 5 2 3 5 Input 3 1:2-1:3 1:1-1:3 1:1-1:2 Output -1 Note The first example is analyzed in the statement. The answer to the second example is shown on the picture. <image> The first router has one list, which contains all other routers. The second router has three lists: the first β€” the single router 4, the second β€” the single router 1, the third β€” two routers 3 and 5. The third router has one list, which contains all other routers. The fourth router also has one list, which contains all other routers. The fifth router has two lists: the first β€” the single router 3, the second β€” three routers 1, 2 and 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. ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right. Initially, tree i has color c_{i}. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≀ c_{i} ≀ m, where c_{i} = 0 means that tree i is uncolored. ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with c_{i} = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly p_{i}, j litres of paint. The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}. ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job. Please note that the friends can't color the trees that are already colored. -----Input----- The first line contains three integers, n, m and k (1 ≀ k ≀ n ≀ 100, 1 ≀ m ≀ 100)Β β€” the number of trees, number of colors and beauty of the resulting coloring respectively. The second line contains n integers c_1, c_2, ..., c_{n} (0 ≀ c_{i} ≀ m), the initial colors of the trees. c_{i} equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color c_{i}. Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes p_{i}, j (1 ≀ p_{i}, j ≀ 10^9)Β β€” the amount of litres the friends need to color i-th tree with color j. p_{i}, j's are specified even for the initially colored trees, but such trees still can't be colored. -----Output----- Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1. -----Examples----- Input 3 2 2 0 0 0 1 2 3 4 5 6 Output 10 Input 3 2 2 2 1 2 1 3 2 4 3 5 Output -1 Input 3 2 2 2 0 0 1 3 2 4 3 5 Output 5 Input 3 2 3 2 1 2 1 3 2 4 3 5 Output 0 -----Note----- In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color). In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1. In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mashmokh works in a factory. At the end of each day he must turn off all of the lights. The lights on the factory are indexed from 1 to n. There are n buttons in Mashmokh's room indexed from 1 to n as well. If Mashmokh pushes button with index i, then each light with index not less than i that is still turned on turns off. Mashmokh is not very clever. So instead of pushing the first button he pushes some of the buttons randomly each night. He pushed m distinct buttons b_1, b_2, ..., b_{m} (the buttons were pushed consecutively in the given order) this night. Now he wants to know for each light the index of the button that turned this light off. Please note that the index of button b_{i} is actually b_{i}, not i. Please, help Mashmokh, print these indices. -----Input----- The first line of the input contains two space-separated integers n and m (1 ≀ n, m ≀ 100), the number of the factory lights and the pushed buttons respectively. The next line contains m distinct space-separated integers b_1, b_2, ..., b_{m}Β (1 ≀ b_{i} ≀ n). It is guaranteed that all lights will be turned off after pushing all buttons. -----Output----- Output n space-separated integers where the i-th number is index of the button that turns the i-th light off. -----Examples----- Input 5 4 4 3 1 2 Output 1 1 3 4 4 Input 5 5 5 4 3 2 1 Output 1 2 3 4 5 -----Note----- In the first sample, after pressing button number 4, lights 4 and 5 are turned off and lights 1, 2 and 3 are still on. Then after pressing button number 3, light number 3 is turned off as well. Pressing button number 1 turns off lights number 1 and 2 as well so pressing button number 2 in the end has no effect. Thus button number 4 turned lights 4 and 5 off, button number 3 turned light 3 off and button number 1 turned light 1 and 2 off. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "name_1price_1name_2price_2...name_{n}price_{n}", where name_{i} (name of the i-th purchase) is a non-empty string of length not more than 10, consisting of lowercase English letters, and price_{i} (the price of the i-th purchase) is a non-empty string, consisting of digits and dots (decimal points). It is possible that purchases with equal names have different prices. The price of each purchase is written in the following format. If the price is an integer number of dollars then cents are not written. Otherwise, after the number of dollars a dot (decimal point) is written followed by cents in a two-digit format (if number of cents is between 1 and 9 inclusively, there is a leading zero). Also, every three digits (from less significant to the most) in dollars are separated by dot (decimal point). No extra leading zeroes are allowed. The price always starts with a digit and ends with a digit. For example: "234", "1.544", "149.431.10", "0.99" and "123.05" are valid prices, ".333", "3.33.11", "12.00", ".33", "0.1234" and "1.2" are not valid. Write a program that will find the total price of all purchases in the given bill. -----Input----- The only line of the input contains a non-empty string s with length not greater than 1000Β β€” the content of the bill. It is guaranteed that the bill meets the format described above. It is guaranteed that each price in the bill is not less than one cent and not greater than 10^6 dollars. -----Output----- Print the total price exactly in the same format as prices given in the input. -----Examples----- Input chipsy48.32televizor12.390 Output 12.438.32 Input a1b2c3.38 Output 6.38 Input aa0.01t0.03 Output 0.04 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card. She starts with 0 money on her account. In the evening of i-th day a transaction a_{i} occurs. If a_{i} > 0, then a_{i} bourles are deposited to Luba's account. If a_{i} < 0, then a_{i} bourles are withdrawn. And if a_{i} = 0, then the amount of money on Luba's account is checked. In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d. It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β». Luba must not exceed this limit, and also she wants that every day her account is checked (the days when a_{i} = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her! -----Input----- The first line contains two integers n, d (1 ≀ n ≀ 10^5, 1 ≀ d ≀ 10^9) β€”the number of days and the money limitation. The second line contains n integer numbers a_1, a_2, ... a_{n} ( - 10^4 ≀ a_{i} ≀ 10^4), where a_{i} represents the transaction in i-th day. -----Output----- Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money. -----Examples----- Input 5 10 -1 5 0 -5 3 Output 0 Input 3 4 -10 0 20 Output -1 Input 5 10 -5 0 10 -11 0 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This is the easy version of the problem. The difference between the versions is the constraints on a_i. You can make hacks only if all versions of the problem are solved. Little Dormi has recently received a puzzle from his friend and needs your help to solve it. The puzzle consists of an upright board with n rows and m columns of cells, some empty and some filled with blocks of sand, and m non-negative integers a_1,a_2,…,a_m (0 ≀ a_i ≀ n). In this version of the problem, a_i will be equal to the number of blocks of sand in column i. When a cell filled with a block of sand is disturbed, the block of sand will fall from its cell to the sand counter at the bottom of the column (each column has a sand counter). While a block of sand is falling, other blocks of sand that are adjacent at any point to the falling block of sand will also be disturbed and start to fall. Specifically, a block of sand disturbed at a cell (i,j) will pass through all cells below and including the cell (i,j) within the column, disturbing all adjacent cells along the way. Here, the cells adjacent to a cell (i,j) are defined as (i-1,j), (i,j-1), (i+1,j), and (i,j+1) (if they are within the grid). Note that the newly falling blocks can disturb other blocks. In one operation you are able to disturb any piece of sand. The puzzle is solved when there are at least a_i blocks of sand counted in the i-th sand counter for each column from 1 to m. You are now tasked with finding the minimum amount of operations in order to solve the puzzle. Note that Little Dormi will never give you a puzzle that is impossible to solve. Input The first line consists of two space-separated positive integers n and m (1 ≀ n β‹… m ≀ 400 000). Each of the next n lines contains m characters, describing each row of the board. If a character on a line is '.', the corresponding cell is empty. If it is '#', the cell contains a block of sand. The final line contains m non-negative integers a_1,a_2,…,a_m (0 ≀ a_i ≀ n) β€” the minimum amount of blocks of sand that needs to fall below the board in each column. In this version of the problem, a_i will be equal to the number of blocks of sand in column i. Output Print one non-negative integer, the minimum amount of operations needed to solve the puzzle. Examples Input 5 7 #....#. .#.#... #....#. #....## #.#.... 4 1 1 1 0 3 1 Output 3 Input 3 3 #.# #.. ##. 3 1 1 Output 1 Note For example 1, by disturbing both blocks of sand on the first row from the top at the first and sixth columns from the left, and the block of sand on the second row from the top and the fourth column from the left, it is possible to have all the required amounts of sand fall in each column. It can be proved that this is not possible with fewer than 3 operations, and as such the answer is 3. Here is the puzzle from the first example. <image> For example 2, by disturbing the cell on the top row and rightmost column, one can cause all of the blocks of sand in the board to fall into the counters at the bottom. Thus, the answer is 1. Here is the puzzle from the second 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. Some numbers have funny properties. For example: > 89 --> 8¹ + 9² = 89 * 1 > 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2 > 46288 --> 4³ + 6⁴+ 2⁡ + 8⁢ + 8⁷ = 2360688 = 46288 * 51 Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p - we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n. In other words: > Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k If it is the case we will return k, if not return -1. **Note**: n and p will always be given as strictly positive integers. ```python dig_pow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1 dig_pow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k dig_pow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2 dig_pow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁡ + 8⁢ + 8⁷ = 2360688 = 46288 * 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. Given two arrays of integers `m` and `n`, test if they contain *at least* one identical element. Return `true` if they do; `false` if not. Your code must handle any value within the range of a 32-bit integer, and must be capable of handling either array being empty (which is a `false` result, as there are no duplicated elements). Read the inputs from stdin solve the problem and write the answer to stdout (do 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 a sequence $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number $6$ $(\dots 00000000110_2)$ into $3$ $(\dots 00000000011_2)$, $12$ $(\dots 000000001100_2)$, $1026$ $(\dots 10000000010_2)$ and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence. Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with bitwise exclusive or of all elements equal to $0$. For the given sequence $a_1, a_2, \ldots, a_n$ Vasya'd like to calculate number of integer pairs $(l, r)$ such that $1 \le l \le r \le n$ and sequence $a_l, a_{l + 1}, \dots, a_r$ is good. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$) β€” length of the sequence. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{18}$) β€” the sequence $a$. -----Output----- Print one integer β€” the number of pairs $(l, r)$ such that $1 \le l \le r \le n$ and the sequence $a_l, a_{l + 1}, \dots, a_r$ is good. -----Examples----- Input 3 6 7 14 Output 2 Input 4 1 2 1 16 Output 4 -----Note----- In the first example pairs $(2, 3)$ and $(1, 3)$ are valid. Pair $(2, 3)$ is valid since $a_2 = 7 \rightarrow 11$, $a_3 = 14 \rightarrow 11$ and $11 \oplus 11 = 0$, where $\oplus$ β€” bitwise exclusive or. Pair $(1, 3)$ is valid since $a_1 = 6 \rightarrow 3$, $a_2 = 7 \rightarrow 13$, $a_3 = 14 \rightarrow 14$ and $3 \oplus 13 \oplus 14 = 0$. In the second example pairs $(1, 2)$, $(2, 3)$, $(3, 4)$ and $(1, 4)$ are valid. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. E-training Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training. As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6. Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $. Umiko told me to look up the number of "numbers that are neither multiples of 2 nor multiples of 3". However, Nene was tired, so she decided to cheat only for the answer. Based only on the values ​​of $ N, A, B, and C $, you can find the number of "numbers that are neither multiples of 2 nor multiples of 3". Create a program that asks for this. input $ N, A, B, C $ are given separated by blanks. output Output the number of "numbers that are neither multiples of 2 nor multiples of 3" in the data. However, insert a line break at the end. Constraint * $ N $ is an integer greater than or equal to $ 1 $ and less than or equal to $ 100 $ * $ A, B, C $ are integers greater than or equal to $ 0 $ and less than or equal to $ N $ * No inconsistent data is given, such as $ A $ being greater than $ N $ Input example 1 6 3 2 1 Output example 1 2 For example, if your data is $ 2, 3, 4, 5, 6, 7 $, then $ 5 $ and $ 7 $ are "numbers that are neither multiples of 2 nor multiples of 3". Input example 2 10 9 9 9 Output example 2 1 Example Input 6 3 2 1 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two arrays $a$ and $b$, each contains $n$ integers. You want to create a new array $c$ as follows: choose some real (i.e. not necessarily integer) number $d$, and then for every $i \in [1, n]$ let $c_i := d \cdot a_i + b_i$. Your goal is to maximize the number of zeroes in array $c$. What is the largest possible answer, if you choose $d$ optimally? -----Input----- The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β€” the number of elements in both arrays. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($-10^9 \le a_i \le 10^9$). The third line contains $n$ integers $b_1$, $b_2$, ..., $b_n$ ($-10^9 \le b_i \le 10^9$). -----Output----- Print one integer β€” the maximum number of zeroes in array $c$, if you choose $d$ optimally. -----Examples----- Input 5 1 2 3 4 5 2 4 7 11 3 Output 2 Input 3 13 37 39 1 2 3 Output 2 Input 4 0 0 0 0 1 2 3 4 Output 0 Input 3 1 2 -1 -6 -12 6 Output 3 -----Note----- In the first example, we may choose $d = -2$. In the second example, we may choose $d = -\frac{1}{13}$. In the third example, we cannot obtain any zero in array $c$, no matter which $d$ we choose. In the fourth example, we may choose $d = 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. Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms. If you want to know more http://en.wikipedia.org/wiki/DNA In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell). More similar exercise are found here http://rosalind.info/problems/list-view/ (source) ```python DNA_strand ("ATTGC") # return "TAACG" DNA_strand ("GTAT") # return "CATA" ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ```if:javascript `Array.prototype.length` will give you the number of top-level elements in an array. ``` ```if:ruby `Array#length` will give you the number of top-level elements in an array. ``` ```if:csharp The `Length` property of an array will give you the number of top-level elements in an array. ``` ```if:php `count()` will give you the number of top-level elements in an array if exactly one argument `$a` is passed in which is the array. ``` ```if:python `len(a)` will give you the number of top-level elements in the list/array named `a`. ``` Your task is to create a function ```deepCount``` that returns the number of ALL elements within an array, including any within inner-level arrays. For example: ```if:javascript deepCount([1, 2, 3]); //>>>>> 3 deepCount(["x", "y", ["z"]]); //>>>>> 4 deepCount([1, 2, [3, 4, [5]]]); //>>>>> 7 ``` ```if:ruby deepCount([1, 2, 3]); //>>>>> 3 deepCount(["x", "y", ["z"]]); //>>>>> 4 deepCount([1, 2, [3, 4, [5]]]); //>>>>> 7 ``` ```if:csharp deepCount([1, 2, 3]); //>>>>> 3 deepCount(["x", "y", ["z"]]); //>>>>> 4 deepCount([1, 2, [3, 4, [5]]]); //>>>>> 7 ``` ```if:php deep_c([1, 2, 3]); //>>>>> 3 deep_c(["x", "y", ["z"]]); //>>>>> 4 deep_c([1, 2, [3, 4, [5]]]); //>>>>> 7 ``` ```if:python deepCount([1, 2, 3]); //>>>>> 3 deepCount(["x", "y", ["z"]]); //>>>>> 4 deepCount([1, 2, [3, 4, [5]]]); //>>>>> 7 ``` The input will always be an array. ```if:php In PHP you may *not* assume that the array passed in will be non-associative. Please note that `count()`, `eval()` and `COUNT_RECURSIVE` are disallowed - you should be able to implement the logic for `deep_c()` yourself ;) ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given $n$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet. The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $1 \le i \le n$ the color of the right cell of the $i$-th domino is different from the color of the left cell of the $((i mod n)+1)$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell. Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid). As this number can be very big, output it modulo $998\,244\,353$. -----Input----- The first line of the input contains a single integer $n$ ($1 \le n \le 10^5$) β€” the number of dominoes. The next $n$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored. -----Output----- Print a single integer β€” the answer to the problem. -----Examples----- Input 1 ?W Output 1 Input 2 ?? W? Output 2 Input 4 BB ?? W? ?? Output 10 -----Note----- In the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this. In the second test case, there are only $2$ such colorings: BB WW and WB WB. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 daily train consists of N cars. Let's consider one particular car. It has 54 places numbered consecutively from 1 to 54, some of which are already booked and some are still free. The places are numbered in the following fashion: The car is separated into 9 compartments of 6 places each, as shown in the picture. So, the 1st compartment consists of places 1, 2, 3, 4, 53 and 54, the 2nd compartment consists of places 5, 6, 7, 8, 51 and 52, and so on. A group of X friends wants to buy tickets for free places, all of which are in one compartment (it's much funnier to travel together). You are given the information about free and booked places in each of the N cars. Find the number of ways to sell the friends exactly X tickets in one compartment (note that the order in which the tickets are sold doesn't matter). ------ Input ------ The first line of the input contains two integers X and N (1 ≀ X ≀ 6, 1 ≀ N ≀ 10) separated by a single space. Each of the following N lines contains the information about one car which is a string of length 54 consisting of '0' and '1'. The i-th character (numbered from 1) is '0' if place i in the corresponding car is free, and is '1' if place i is already booked. ------ Output ------ Output just one integer -- the requested number of ways. ----- Sample Input 1 ------ 1 3 100101110000001011000001111110010011110010010111000101 001010000000101111100000000000000111101010101111111010 011110011110000001010100101110001011111010001001111010 ----- Sample Output 1 ------ 85 ----- explanation 1 ------ In the first test case, any of the free places can be sold. ----- Sample Input 2 ------ 6 3 100101110000001011000001111110010011110010010111000101 001010000000101111100000000000000111101010101111111010 011110011110000001010100101110001011111010001001111010 ----- Sample Output 2 ------ 1 ----- explanation 2 ------ In the second test case, the only free compartment in the train is compartment 3 in the first car (places 9, 10, 11, 12, 49 and 50 are all free). ----- Sample Input 3 ------ 3 2 000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000 ----- Sample Output 3 ------ 360 ----- explanation 3 ------ In the third test case, the train is still absolutely free; as there are 20 ways to sell 3 tickets in an empty compartment, the answer is 2 * 9 * 20 = 360. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Serge came to the school dining room and discovered that there is a big queue here. There are $m$ pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him. Initially there are $n$ dishes with costs $a_1, a_2, \ldots, a_n$. As you already know, there are the queue of $m$ pupils who have $b_1, \ldots, b_m$ togrogs respectively (pupils are enumerated by queue order, i.e the first pupil in the queue has $b_1$ togrogs and the last one has $b_m$ togrogs) Pupils think that the most expensive dish is the most delicious one, so every pupil just buys the most expensive dish for which he has money (every dish has a single copy, so when a pupil has bought it nobody can buy it later), and if a pupil doesn't have money for any dish, he just leaves the queue (so brutal capitalism...) But money isn't a problem at all for Serge, so Serge is buying the most expensive dish if there is at least one remaining. Moreover, Serge's school has a very unstable economic situation and the costs of some dishes or number of togrogs of some pupils can change. More formally, you must process $q$ queries: change $a_i$ to $x$. It means that the price of the $i$-th dish becomes $x$ togrogs. change $b_i$ to $x$. It means that the $i$-th pupil in the queue has $x$ togrogs now. Nobody leaves the queue during those queries because a saleswoman is late. After every query, you must tell Serge price of the dish which he will buy if he has waited until the queue is clear, or $-1$ if there are no dishes at this point, according to rules described above. -----Input----- The first line contains integers $n$ and $m$ ($1 \leq n, m \leq 300\ 000$)Β β€” number of dishes and pupils respectively. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^{6}$)Β β€” elements of array $a$. The third line contains $m$ integers $b_1, b_2, \ldots, b_{m}$ ($1 \leq b_i \leq 10^{6}$)Β β€” elements of array $b$. The fourth line conatins integer $q$ ($1 \leq q \leq 300\ 000$)Β β€” number of queries. Each of the following $q$ lines contains as follows: if a query changes price of some dish, it contains $1$, and two integers $i$ and $x$ ($1 \leq i \leq n$, $1 \leq x \leq 10^{6}$), what means $a_i$ becomes $x$. if a query changes number of togrogs of some pupil, it contains $2$, and two integers $i$ and $x$ ($1 \leq i \leq m$, $1 \leq x \leq 10^{6}$), what means $b_i$ becomes $x$. -----Output----- For each of $q$ queries prints the answer as the statement describes, the answer of the $i$-th query in the $i$-th line (the price of the dish which Serge will buy or $-1$ if nothing remains) -----Examples----- Input 1 1 1 1 1 1 1 100 Output 100 Input 1 1 1 1 1 2 1 100 Output -1 Input 4 6 1 8 2 4 3 3 6 1 5 2 3 1 1 1 2 5 10 1 1 6 Output 8 -1 4 -----Note----- In the first sample after the first query, there is one dish with price $100$ togrogs and one pupil with one togrog, so Serge will buy the dish with price $100$ togrogs. In the second sample after the first query, there is one dish with price one togrog and one pupil with $100$ togrogs, so Serge will get nothing. In the third sample after the first query, nobody can buy the dish with price $8$, so Serge will take it. After the second query, all dishes will be bought, after the third one the third and fifth pupils will by the first and the second dishes respectively and nobody will by the fourth one. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order. (Assume that the positive x-axis points right, and the positive y-axis points up.) Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4). Given x_1,x_2,y_1,y_2, restore x_3,y_3,x_4,y_4. It can be shown that x_3,y_3,x_4 and y_4 uniquely exist and have integer values. -----Constraints----- - |x_1|,|y_1|,|x_2|,|y_2| \leq 100 - (x_1,y_1) β‰  (x_2,y_2) - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: x_1 y_1 x_2 y_2 -----Output----- Print x_3,y_3,x_4 and y_4 as integers, in this order. -----Sample Input----- 0 0 0 1 -----Sample Output----- -1 1 -1 0 (0,0),(0,1),(-1,1),(-1,0) is the four vertices of a square in counter-clockwise order. Note that (x_3,y_3)=(1,1),(x_4,y_4)=(1,0) is not accepted, as the vertices are in clockwise order. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied: * For each i = 1,2,..., n-2, a_i = a_{i+2}. * Exactly two different numbers appear in the sequence. You are given a sequence v_1,v_2,...,v_n whose length is even. We would like to make this sequence /\/\/\/ by replacing some of its elements. Find the minimum number of elements that needs to be replaced. Constraints * 2 \leq n \leq 10^5 * n is even. * 1 \leq v_i \leq 10^5 * v_i is an integer. Input Input is given from Standard Input in the following format: n v_1 v_2 ... v_n Output Print the minimum number of elements that needs to be replaced. Examples Input 4 3 1 3 2 Output 1 Input 6 105 119 105 119 105 119 Output 0 Input 4 1 1 1 1 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function that takes an integer and returns an array `[A, B, C]`, where `A` is the number of multiples of 3 (but not 5) below the given integer, `B` is the number of multiples of 5 (but not 3) below the given integer and `C` is the number of multiples of 3 and 5 below the given integer. For example, `solution(20)` should return `[5, 2, 1]` ~~~if:r ```r # in R, returns a numeric vector solution(20) [1] 5 2 1 class(solution(20)) [1] "numeric" ``` ~~~ Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Patisserie AtCoder sells cakes with number-shaped candles. There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively. Each cake has an integer value called deliciousness, as follows: - The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X. - The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y. - The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z. Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123. There are X \times Y \times Z such ways to choose three cakes. We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes. Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list. -----Constraints----- - 1 \leq X \leq 1 \ 000 - 1 \leq Y \leq 1 \ 000 - 1 \leq Z \leq 1 \ 000 - 1 \leq K \leq \min(3 \ 000, X \times Y \times Z) - 1 \leq A_i \leq 10 \ 000 \ 000 \ 000 - 1 \leq B_i \leq 10 \ 000 \ 000 \ 000 - 1 \leq C_i \leq 10 \ 000 \ 000 \ 000 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: X Y Z K A_1 \ A_2 \ A_3 \ ... \ A_X B_1 \ B_2 \ B_3 \ ... \ B_Y C_1 \ C_2 \ C_3 \ ... \ C_Z -----Output----- Print K lines. The i-th line should contain the i-th value stated in the problem statement. -----Sample Input----- 2 2 2 8 4 6 1 5 3 8 -----Sample Output----- 19 17 15 14 13 12 10 8 There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes: - (A_2, B_2, C_2): 6 + 5 + 8 = 19 - (A_1, B_2, C_2): 4 + 5 + 8 = 17 - (A_2, B_1, C_2): 6 + 1 + 8 = 15 - (A_2, B_2, C_1): 6 + 5 + 3 = 14 - (A_1, B_1, C_2): 4 + 1 + 8 = 13 - (A_1, B_2, C_1): 4 + 5 + 3 = 12 - (A_2, B_1, C_1): 6 + 1 + 3 = 10 - (A_1, B_1, C_1): 4 + 1 + 3 = 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. Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total. Each Kinder Surprise can be one of three types: * it can contain a single sticker and no toy; * it can contain a single toy and no sticker; * it can contain both a single sticker and a single toy. But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other. What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy? Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists. Input The first line contains the single integer T (1 ≀ T ≀ 100) β€” the number of queries. Next T lines contain three integers n, s and t each (1 ≀ n ≀ 10^9, 1 ≀ s, t ≀ n, s + t β‰₯ n) β€” the number of eggs, stickers and toys. All queries are independent. Output Print T integers (one number per query) β€” the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and one toy Example Input 3 10 5 7 10 10 10 2 1 1 Output 6 1 2 Note In the first query, we have to take at least 6 eggs because there are 5 eggs with only toy inside and, in the worst case, we'll buy all of them. In the second query, all eggs have both a sticker and a toy inside, that's why it's enough to buy only one egg. In the third query, we have to buy both eggs: one with a sticker and one with a toy. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Squareland national forest is divided into equal 1 Γ— 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner. Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C in the forest. Initially, all plots in the forest (including the plots A, B, C) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots A, B, C from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side. <image> For example, A=(0,0), B=(1,1), C=(2,2). The minimal number of plots to be cleared is 5. One of the ways to do it is shown with the gray color. Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees. Input The first line contains two integers x_A and y_A β€” coordinates of the plot A (0 ≀ x_A, y_A ≀ 1000). The following two lines describe coordinates (x_B, y_B) and (x_C, y_C) of plots B and C respectively in the same format (0 ≀ x_B, y_B, x_C, y_C ≀ 1000). It is guaranteed that all three plots are distinct. Output On the first line print a single integer k β€” the smallest number of plots needed to be cleaned from trees. The following k lines should contain coordinates of all plots needed to be cleaned. All k plots should be distinct. You can output the plots in any order. If there are multiple solutions, print any of them. Examples Input 0 0 1 1 2 2 Output 5 0 0 1 0 1 1 1 2 2 2 Input 0 0 2 0 1 1 Output 4 0 0 1 0 1 1 2 0 Note The first example is shown on the picture in the legend. The second example is illustrated with the following 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. Recall that the sequence $b$ is a a subsequence of the sequence $a$ if $b$ can be derived from $a$ by removing zero or more elements without changing the order of the remaining elements. For example, if $a=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$. You are given a sequence $a$ consisting of $n$ positive and negative elements (there is no zeros in the sequence). Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements. In other words, if the maximum length of alternating subsequence is $k$ then your task is to find the maximum sum of elements of some alternating subsequence of length $k$. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) β€” the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β€” the number of elements in $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9, a_i \ne 0$), where $a_i$ is the $i$-th element of $a$. It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$). -----Output----- For each test case, print the answer β€” the maximum sum of the maximum by size (length) alternating subsequence of $a$. -----Example----- Input 4 5 1 2 3 -1 -2 4 -1 -2 -1 -3 10 -2 8 3 8 -4 -15 5 -2 -3 1 6 1 -1000000000 1 -1000000000 1 -1000000000 Output 2 -1 6 -2999999997 -----Note----- In the first test case of the example, one of the possible answers is $[1, 2, \underline{3}, \underline{-1}, -2]$. In the second test case of the example, one of the possible answers is $[-1, -2, \underline{-1}, -3]$. In the third test case of the example, one of the possible answers is $[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$. In the fourth test case of the example, one of the possible answers is $[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 set of $n$ segments on the axis $Ox$, each segment has integer endpoints between $1$ and $m$ inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le m$) β€” coordinates of the left and of the right endpoints. Consider all integer points between $1$ and $m$ inclusive. Your task is to print all such points that don't belong to any segment. The point $x$ belongs to the segment $[l; r]$ if and only if $l \le x \le r$. -----Input----- The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 100$) β€” the number of segments and the upper bound for coordinates. The next $n$ lines contain two integers each $l_i$ and $r_i$ ($1 \le l_i \le r_i \le m$) β€” the endpoints of the $i$-th segment. Segments may intersect, overlap or even coincide with each other. Note, it is possible that $l_i=r_i$, i.e. a segment can degenerate to a point. -----Output----- In the first line print one integer $k$ β€” the number of points that don't belong to any segment. In the second line print exactly $k$ integers in any order β€” the points that don't belong to any segment. All points you print should be distinct. If there are no such points at all, print a single integer $0$ in the first line and either leave the second line empty or do not print it at all. -----Examples----- Input 3 5 2 2 1 2 5 5 Output 2 3 4 Input 1 7 1 7 Output 0 -----Note----- In the first example the point $1$ belongs to the second segment, the point $2$ belongs to the first and the second segments and the point $5$ belongs to the third segment. The points $3$ and $4$ do not belong to any segment. In the second example all the points from $1$ to $7$ belong to the first segment. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 cubes stacked vertically on a desk. You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1. You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them. At most how many cubes can be removed? -----Constraints----- - 1 \leq N \leq 10^5 - |S| = N - Each character in S is 0 or 1. -----Input----- Input is given from Standard Input in the following format: S -----Output----- Print the maximum number of cubes that can be removed. -----Sample Input----- 0011 -----Sample Output----- 4 All four cubes can be removed, by performing the operation as follows: - Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube. - Remove the first and second cubes from the bottom. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Petya loves stairs very much. But he is bored from simple going up and down them β€” he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them. Now Petya is on the first stair of the staircase, consisting of n stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number n without touching a dirty stair once. One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only. -----Input----- The first line contains two integers n and m (1 ≀ n ≀ 10^9, 0 ≀ m ≀ 3000) β€” the number of stairs in the staircase and the number of dirty stairs, correspondingly. The second line contains m different space-separated integers d_1, d_2, ..., d_{m} (1 ≀ d_{i} ≀ n) β€” the numbers of the dirty stairs (in an arbitrary order). -----Output----- Print "YES" if Petya can reach stair number n, stepping only on the clean stairs. Otherwise print "NO". -----Examples----- Input 10 5 2 4 8 3 6 Output NO Input 10 5 2 4 5 7 9 Output YES Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Hiking club "Up the hill" just returned from a walk. Now they are trying to remember which hills they've just walked through. It is known that there were N stops, all on different integer heights between 1 and N kilometers (inclusive) above the sea level. On the first day they've traveled from the first stop to the second stop, on the second day they've traveled from the second to the third and so on, and on the last day they've traveled from the stop N - 1 to the stop N and successfully finished their expedition. They are trying to find out which heights were their stops located at. They have an entry in a travel journal specifying how many days did they travel up the hill, and how many days did they walk down the hill. Help them by suggesting some possible stop heights satisfying numbers from the travel journal. -----Input----- In the first line there is an integer non-negative number A denoting the number of days of climbing up the hill. Second line contains an integer non-negative number BΒ β€” the number of days of walking down the hill (A + B + 1 = N, 1 ≀ N ≀ 100 000). -----Output----- Output N space-separated distinct integers from 1 to N inclusive, denoting possible heights of the stops in order of visiting. -----Examples----- Input 0 1 Output 2 1 Input 2 1 Output 1 3 4 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You've got a string $S$ consisting of $n$ lowercase English letters from your friend. It turned out that this is a number written in poman numerals. The poman numeral system is long forgotten. All that's left is the algorithm to transform number from poman numerals to the numeral system familiar to us. Characters of $S$ are numbered from $1$ to $n$ from left to right. Let's denote the value of $S$ as $f(S)$, it is defined as follows: If $|S| > 1$, an arbitrary integer $m$ ($1 \le m < |S|$) is chosen, and it is defined that $f(S) = -f(S[1, m]) + f(S[m + 1, |S|])$, where $S[l, r]$ denotes the substring of $S$ from the $l$-th to the $r$-th position, inclusively. Otherwise $S = c$, where $c$ is some English letter. Then $f(S) = 2^{pos(c)}$, where $pos(c)$ is the position of letter $c$ in the alphabet ($pos($a$) = 0$, $pos($z$) = 25$). Note that $m$ is chosen independently on each step. Your friend thinks it is possible to get $f(S) = T$ by choosing the right $m$ on every step. Is he right? -----Input----- The first line contains two integers $n$ and $T$ ($2 \leq n \leq 10^5$, $-10^{15} \leq T \leq 10^{15}$). The second line contains a string $S$ consisting of $n$ lowercase English letters. -----Output----- Print "Yes" if it is possible to get the desired value. Otherwise, print "No". You can print each letter in any case (upper or lower). -----Examples----- Input 2 -1 ba Output Yes Input 3 -7 abc Output No Input 7 -475391 qohshra Output Yes -----Note----- In the second example, you cannot get $-7$. But you can get $1$, for example, as follows: First choose $m = 1$, then $f($abc$) = -f($a$) + f($bc$)$ $f($a$) = 2^0 = 1$ $f($bc$) = -f($b$) + f($c$) = -2^1 + 2^2 = 2$ In the end $f($abc$) = -1 + 2 = 1$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given three distinct integers $a$, $b$, and $c$, find the medium number between all of them. The medium number is the number that is neither the minimum nor the maximum of the given three numbers. For example, the median of $5,2,6$ is $5$, since the minimum is $2$ and the maximum is $6$. -----Input----- The first line contains a single integer $t$ ($1 \leq t \leq 6840$) β€” the number of test cases. The description of each test case consists of three distinct integers $a$, $b$, $c$ ($1 \leq a, b, c \leq 20$). -----Output----- For each test case, output a single integer β€” the medium number of the three numbers. -----Examples----- Input 9 5 2 6 14 3 4 20 2 1 1 2 3 11 19 12 10 8 20 6 20 3 4 1 3 19 8 4 Output 5 4 2 2 12 10 6 3 8 -----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. In the good old days, the Internet was free from fears and terrorism. People did not have to worry about any cyber criminals or mad computer scientists. Today, however, you are facing atrocious crackers wherever you are, unless being disconnected. You have to protect yourselves against their attacks. Counting upon your excellent talent for software construction and strong sense of justice, you are invited to work as a cyber guardian. Your ultimate mission is to create a perfect firewall system that can completely shut out any intruders invading networks and protect children from harmful information exposed on the Net. However, it is extremely difficult and none have ever achieved it before. As the first step, instead, you are now requested to write a software simulator under much simpler assumptions. In general, a firewall system works at the entrance of a local network of an organization (e.g., a company or a university) and enforces its local administrative policy. It receives both inbound and outbound packets (note: data transmitted on the Net are divided into small segments called packets) and carefully inspects them one by one whether or not each of them is legal. The definition of the legality may vary from site to site or depend upon the local administrative policy of an organization. Your simulator should accept data representing not only received packets but also the local administrative policy. For simplicity in this problem we assume that each network packet consists of three fields: its source address, destination address, and message body. The source address specifies the computer or appliance that transmits the packet and the destination address specifies the computer or appliance to which the packet is transmitted. An address in your simulator is represented as eight digits such as 03214567 or 31415926, instead of using the standard notation of IP addresses such as 192.168.1.1. Administrative policy is described in filtering rules, each of which specifies some collection of source-destination address pairs and defines those packets with the specified address pairs either legal or illegal. Input The input consists of several data sets, each of which represents filtering rules and received packets in the following format: n m rule1 rule2 ... rulen packet1 packet2 ... packetm The first line consists of two non-negative integers n and m. If both n and m are zeros, this means the end of input. Otherwise, n lines, each representing a filtering rule, and m lines, each representing an arriving packet, follow in this order. You may assume that n and m are less than or equal to 1,024. Each rulei is in one of the following formats: permit source-pattern destination-pattern deny source-pattern destination-pattern A source-pattern or destination-pattern is a character string of length eight, where each character is either a digit ('0' to '9') or a wildcard character '?'. For instance, "1????5??" matches any address whose first and fifth digits are '1' and '5', respectively. In general, a wildcard character matches any single digit while a digit matches only itself. With the keywords "permit" and "deny", filtering rules specify legal and illegal packets, respectively. That is, if the source and destination addresses of a packed are matched with source-pattern and destination-pattern, respectively, it is permitted to pass the firewall or the request is denied according to the keyword. Note that a permit rule and a deny rule can contradict since they may share the same source and destination address pair. For the purpose of conflict resolution, we define a priority rule: rulei has a higher priority over rulej if and only if i > j. For completeness, we define the default rule: any packet is illegal unless being explicitly specified legal by some given rule. A packet is in the following format: source-address destination-address message-body Each of the first two is a character string of length eight that consists solely of digits. The last one is a character string consisting solely of alphanumeric characters ('a' to 'z', 'A' to 'Z', and '0' to '9'). Neither whitespaces nor special characters can occur in a message body. You may assume that it is not empty and that its length is at most 50. You may also assume that there is exactly one space character between any two adjacent fields in an input line representing a rule or a packet. Output For each data set, print the number of legal packets in the first line, followed by all legal packets in the same order as they occur in the data set. Each packet must be written exactly in one line. If the data set includes two packets consisting of the same source and destination addresses and the same message body, you should consider them different packets and so they must be written in different lines. Any extra whitespaces or extra empty lines must not be written. Example Input 2 5 permit 192168?? ?12??34? deny 19216899 012343?5 19216711 11233340 HiIamACracker 19216891 01234345 Hello 19216899 01234345 HiIamAlsoACracker 19216809 11200340 World 00000000 99999999 TheEndOfTheWorld 1 2 permit 12345678 23456789 19216891 01234345 Hello 12345678 23456789 Hello 0 0 Output 2 19216891 01234345 Hello 19216809 11200340 World 1 12345678 23456789 Hello Read the inputs from stdin solve the problem and write the answer to stdout (do 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 technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not. -----Input----- The first line contains two lowercase English lettersΒ β€” the password on the phone. The second line contains single integer n (1 ≀ n ≀ 100)Β β€” the number of words Kashtanka knows. The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct. -----Output----- Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower). -----Examples----- Input ya 4 ah oy to ha Output YES Input hp 2 ht tp Output NO Input ah 1 ha Output YES -----Note----- In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES". In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring. In the third example the string "hahahaha" contains "ah" as a substring. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 plays "Game 23". Initially he has a number $n$ and his goal is to transform it to $m$. In one move, he can multiply $n$ by $2$ or multiply $n$ by $3$. He can perform any number of moves. Print the number of moves needed to transform $n$ to $m$. Print -1 if it is impossible to do so. It is easy to prove that any way to transform $n$ to $m$ contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation). -----Input----- The only line of the input contains two integers $n$ and $m$ ($1 \le n \le m \le 5\cdot10^8$). -----Output----- Print the number of moves to transform $n$ to $m$, or -1 if there is no solution. -----Examples----- Input 120 51840 Output 7 Input 42 42 Output 0 Input 48 72 Output -1 -----Note----- In the first example, the possible sequence of moves is: $120 \rightarrow 240 \rightarrow 720 \rightarrow 1440 \rightarrow 4320 \rightarrow 12960 \rightarrow 25920 \rightarrow 51840.$ The are $7$ steps in total. In the second example, no moves are needed. Thus, the answer is $0$. In the third example, it is impossible to transform $48$ to $72$. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 year of 2012 is coming... According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil. The seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: a for Mephisto, b for Diablo and c for Baal. Here's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a <image> of experience, rounded down, where x will be the amount of experience for the killed megaboss and y β€” the number of people in the team. Heroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which the total amount of liking in teams were maximum. It is known that some heroes like others. But if hero p likes hero q, this does not mean that the hero q likes hero p. No hero likes himself. The total amount of liking in teams is the amount of ordered pairs (p, q), such that heroes p and q are in the same group, and hero p likes hero q (but it is not important if hero q likes hero p). In case of heroes p and q likes each other and they are in the same group, this pair should be counted twice, as (p, q) and (q, p). A team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team. It is guaranteed that every hero is able to destroy any megaboss alone. Input The first line contains a single non-negative integer n (0 ≀ n ≀ 42) β€” amount of liking between the heroes. Next n lines describe liking in the form "p likes q", meaning that the hero p likes the hero q (p β‰  q). Every liking is described in the input exactly once, no hero likes himself. In the last line are given three integers a, b and c (1 ≀ a, b, c ≀ 2Β·109), separated by spaces: the experience for Mephisto, the experience for Diablo and experience for Baal. In all the pretests, except for examples from the statement, the following condition is satisfied: a = b = c. Output Print two integers β€” the minimal difference in the experience between two heroes who will receive the maximum and minimum number of experience points, and the maximal total amount of liking in teams (the number of friendships between heroes that end up in one team). When calculating the second answer, the team division should satisfy the difference-minimizing contraint. I.e. primary you should minimize the difference in the experience and secondary you should maximize the total amount of liking. Examples Input 3 Troll likes Dracul Dracul likes Anka Snowy likes Hexadecimal 210 200 180 Output 30 3 Input 2 Anka likes Chapay Chapay likes Anka 10000 50 50 Output 1950 2 Note A note to first example: it the first team should be Dracul, Troll and Anka, in the second one Hexadecimal and Snowy, and in the third Cleo ΠΈ Chapay. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe. And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure: * if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively); * if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code; * if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits. * The length of the safe code coincides with the length of the hint. For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666". After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint. At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night... Input The first line contains string s β€” the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0. The input limits for scoring 30 points are (subproblem A1): * 1 ≀ |s| ≀ 5. The input limits for scoring 100 points are (subproblems A1+A2): * 1 ≀ |s| ≀ 105. Here |s| means the length of string s. Output Print the number of codes that match the given hint. Examples Input AJ Output 81 Input 1?AA Output 100 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Takahashi throws N dice, each having K sides with all integers from 1 to K. The dice are NOT pairwise distinguishable. For each i=2,3,...,2K, find the following value modulo 998244353: - The number of combinations of N sides shown by the dice such that the sum of no two different sides is i. Note that the dice are NOT distinguishable, that is, two combinations are considered different when there exists an integer k such that the number of dice showing k is different in those two. -----Constraints----- - 1 \leq K \leq 2000 - 2 \leq N \leq 2000 - K and N are integers. -----Input----- Input is given from Standard Input in the following format: K N -----Output----- Print 2K-1 integers. The t-th of them (1\leq t\leq 2K-1) should be the answer for i=t+1. -----Sample Input----- 3 3 -----Sample Output----- 7 7 4 7 7 - For i=2, the combinations (1,2,2),(1,2,3),(1,3,3),(2,2,2),(2,2,3),(2,3,3),(3,3,3) satisfy the condition, so the answer is 7. - For i=3, the combinations (1,1,1),(1,1,3),(1,3,3),(2,2,2),(2,2,3),(2,3,3),(3,3,3) satisfy the condition, so the answer is 7. - For i=4, the combinations (1,1,1),(1,1,2),(2,3,3),(3,3,3) satisfy the condition, so the answer is 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. Are you fond of collecting some kind of stuff? Mike is crazy about collecting stamps. He is an active member of Stamp Collecting Π‘ommunity(SCC). SCC consists of N members which are fond of philately. A few days ago Mike argued with the others from SCC. Mike told them that all stamps of the members could be divided in such a way that i'th member would get i postage stamps. Now Mike wants to know if he was right. The next SCC meeting is tomorrow. Mike still has no answer. So, help Mike! There are N members in the SCC, i'th member has Ci stamps in his collection. Your task is to determine if it is possible to redistribute C1 + C2 + ... + Cn stamps among the members of SCC thus that i'th member would get i stamps. -----Input----- The first line contains one integer N, denoting the number of members of SCC. The second line contains N integers Ci, denoting the numbers of the stamps in the collection of i'th member. -----Output----- The first line should contain YES, if we can obtain the required division, otherwise NO. -----Constraints----- 1 ≀ N ≀ 100 000; 1 ≀ Ci ≀ 109. -----Examples----- Input: 5 7 4 1 1 2 Output: YES Input: 5 1 1 1 1 1 Output: NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust. The pizza is a circle of radius r and center at the origin. Pizza consists of the main part β€” circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the iΒ -th piece of the sausage is r_{i}, and the center is given as a pair (x_{i}, y_{i}). Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust. -----Input----- First string contains two integer numbers r and d (0 ≀ d < r ≀ 500)Β β€” the radius of pizza and the width of crust. Next line contains one integer number nΒ β€” the number of pieces of sausage (1 ≀ n ≀ 10^5). Each of next n lines contains three integer numbers x_{i}, y_{i} and r_{i} ( - 500 ≀ x_{i}, y_{i} ≀ 500, 0 ≀ r_{i} ≀ 500), where x_{i} and y_{i} are coordinates of the center of i-th peace of sausage, r_{i}Β β€” radius of i-th peace of sausage. -----Output----- Output the number of pieces of sausage that lay on the crust. -----Examples----- Input 8 4 7 7 8 1 -7 3 2 0 2 1 0 -2 2 -3 -3 1 0 6 2 5 3 1 Output 2 Input 10 8 4 0 0 9 0 0 10 1 0 1 1 0 2 Output 0 -----Note----- Below is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust. [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. Example Input anagram grandmother Output 4 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Today is Devu's birthday. For celebrating the occasion, he bought n sweets from the nearby market. He has invited his f friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each friend. He wants to celebrate it in a unique style, so he would like to ensure following condition for the distribution of sweets. Assume that he has distributed n sweets to his friends such that i^{th} friend is given a_{i} sweets. He wants to make sure that there should not be any positive integer x > 1, which divides every a_{i}. Please find the number of ways he can distribute sweets to his friends in the required way. Note that the order of distribution is important, for example [1, 2] and [2, 1] are distinct distributions. As the answer could be very large, output answer modulo 1000000007 (10^9 + 7). To make the problem more interesting, you are given q queries. Each query contains an n, f pair. For each query please output the required number of ways modulo 1000000007 (10^9 + 7). -----Input----- The first line contains an integer q representing the number of queries (1 ≀ q ≀ 10^5). Each of the next q lines contains two space space-separated integers n, f (1 ≀ f ≀ n ≀ 10^5). -----Output----- For each query, output a single integer in a line corresponding to the answer of each query. -----Examples----- Input 5 6 2 7 2 6 3 6 4 7 4 Output 2 6 9 10 20 -----Note----- For first query: n = 6, f = 2. Possible partitions are [1, 5] and [5, 1]. For second query: n = 7, f = 2. Possible partitions are [1, 6] and [2, 5] and [3, 4] and [4, 3] and [5, 3] and [6, 1]. So in total there are 6 possible ways of partitioning. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method. The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps: 1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0. 2. The i-th element of the array is subtracted from the result of the previous step modulo 256. 3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed. You are given the text printed using this method. Restore the array used to produce this text. Input The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive. Output Output the initial array, which was used to produce text, one integer per line. Examples Input Hello, World! Output 238 108 112 0 64 194 48 26 244 168 24 16 162 Note Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by 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. Background There is a message that is circulating via public media that claims a reader can easily read a message where the inner letters of each words is scrambled, as long as the first and last letters remain the same and the word contains all the letters. Another example shows that it is quite difficult to read the text where all the letters are reversed rather than scrambled. In this kata we will make a generator that generates text in a similar pattern, but instead of scrambled or reversed, ours will be sorted alphabetically Requirement return a string where: 1) the first and last characters remain in original place for each word 2) characters between the first and last characters must be sorted alphabetically 3) punctuation should remain at the same place as it started, for example: shan't -> sahn't Assumptions 1) words are seperated by single spaces 2) only spaces separate words, special characters do not, for example: tik-tak -> tai-ktk 3) special characters do not take the position of the non special characters, for example: -dcba -> -dbca 4) for this kata puctuation is limited to 4 characters: hyphen(-), apostrophe('), comma(,) and period(.) 5) ignore capitalisation for reference: http://en.wikipedia.org/wiki/Typoglycemia Read the inputs from stdin solve the problem and write the answer to stdout (do 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 lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present β€” the clock that shows not only the time, but also the date. The clock's face can display any number from 1 to d. It is guaranteed that ai ≀ d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d + 1, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1. Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month. A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1. Input The first line contains the single number d β€” the maximum number of the day that Vasya's clock can show (1 ≀ d ≀ 106). The second line contains a single integer n β€” the number of months in the year (1 ≀ n ≀ 2000). The third line contains n space-separated integers: ai (1 ≀ ai ≀ d) β€” the number of days in each month in the order in which they follow, starting from the first one. Output Print a single number β€” the number of times Vasya manually increased the day number by one throughout the last year. Examples Input 4 2 2 2 Output 2 Input 5 3 3 4 3 Output 3 Input 31 12 31 28 31 30 31 30 31 31 30 31 30 31 Output 7 Note In the first sample the situation is like this: * Day 1. Month 1. The clock shows 1. Vasya changes nothing. * Day 2. Month 1. The clock shows 2. Vasya changes nothing. * Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1. * Day 2. Month 2. The clock shows 2. Vasya changes nothing. In total, Vasya manually changed the day number by 1 exactly 2 times. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a program which manipulates a disjoint set S = {S1, S2, . . . , Sk}. First of all, the program should read an integer n, then make a disjoint set where each element consists of 0, 1, ... nβˆ’1 respectively. Next, the program should read an integer q and manipulate the set for q queries. There are two kinds of queries for different operations: * unite(x, y): unites sets that contain x and y, say Sx and Sy, into a new set. * same(x, y): determine whether x and y are in the same set. Constraints * 1 ≀ n ≀ 10000 * 1 ≀ q ≀ 100000 * x β‰  y Input n q com1 x1 y1 com2 x2 y2 ... comq xq yq In the first line, n and q are given. Then, q queries are given where com represents the type of queries. '0' denotes unite and '1' denotes same operation. Output For each same operation, print 1 if x and y are in the same set, otherwise 0, in a line. Example Input 5 12 0 1 4 0 2 3 1 1 2 1 3 4 1 1 4 1 3 2 0 1 3 1 2 4 1 3 0 0 0 4 1 0 2 1 3 0 Output 0 0 1 1 1 0 1 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a_1, a_2, ..., a_{n}. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise a_{i} times. Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the n-th exercise. Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training. -----Input----- The first line contains integer n (1 ≀ n ≀ 20). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≀ a_{i} ≀ 25) β€” the number of times Greg repeats the exercises. -----Output----- Print word "chest" (without the quotes), if the chest gets the most exercise, "biceps" (without the quotes), if the biceps gets the most exercise and print "back" (without the quotes) if the back gets the most exercise. It is guaranteed that the input is such that the answer to the problem is unambiguous. -----Examples----- Input 2 2 8 Output biceps Input 3 5 1 10 Output back Input 7 3 3 2 7 9 6 8 Output chest -----Note----- In the first sample Greg does 2 chest, 8 biceps and zero back exercises, so the biceps gets the most exercises. In the second sample Greg does 5 chest, 1 biceps and 10 back exercises, so the back gets the most exercises. In the third sample Greg does 18 chest, 12 biceps and 8 back exercises, so the chest gets the most exercise. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0. It is allowed to leave a as it is. -----Input----- The first line contains integer a (1 ≀ a ≀ 10^18). The second line contains integer b (1 ≀ b ≀ 10^18). Numbers don't have leading zeroes. It is guaranteed that answer exists. -----Output----- Print the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can't have any leading zeroes. It is guaranteed that the answer exists. The number in the output should have exactly the same length as number a. It should be a permutation of digits of a. -----Examples----- Input 123 222 Output 213 Input 3921 10000 Output 9321 Input 4940 5000 Output 4940 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Elephant was fond of inventing new games. After a lot of research, Little Elephant came to know that most of the animals in the forest were showing less interest to play the multi-player games. Little Elephant had started to invent single player games, and succeeded in inventing the new single player game named COIN FLIP. In this game the player will use $N$ coins numbered from $1$ to $N$, and all the coins will be facing in "Same direction" (Either Head or Tail), which will be decided by the player before starting of the game. The player needs to play $N$ rounds. In the $k$-th round the player will flip the face of the all coins whose number is less than or equal to $k$. That is, the face of coin $i$ will be reversed, from Head to Tail, or, from Tail to Head, for $i ≀ k$. Elephant needs to guess the total number of coins showing a particular face after playing $N$ rounds. Elephant really becomes quite fond of this game COIN FLIP so Elephant plays $G$ times. Please help the Elephant to find out the answer. ------ Input: ------ The first line of input contains an integer $T$, denoting the number of test cases. Then $T$ test cases follow. The first line of each test contains an integer $G$, denoting the number of games played by Elephant. Each of the following $G$ lines denotes a single game, and contains $3$ space-separated integers $I$, $N$, $Q$, where $I$ denotes the initial state of the coins, $N$ denotes the number of coins and rounds, and $Q$, which is either $1$, or $2$ as explained below. Here $I=1$ means all coins are showing Head in the start of the game, and $I=2$ means all coins are showing Tail in the start of the game. $Q=1$ means Elephant needs to guess the total number of coins showing Head in the end of the game, and $Q=2$ means Elephant needs to guess the total number of coins showing Tail in the end of the game. ------ Output: ------ For each game, output one integer denoting the total number of coins showing the particular face in the end of the game. ------ Constraints: ------ $1 ≀ T ≀ 10$ $1 ≀ G ≀ 2000$ $1 ≀ N ≀ 10$ $1 ≀ I ≀ 2$ $1 ≀ Q ≀ 2$ ----- Sample Input 1 ------ 1 2 1 5 1 1 5 2 ----- Sample Output 1 ------ 2 3 ----- explanation 1 ------ In the 1st game in Example, $I=1$, so initial arrangement of coins are H H H H H, and now Elephant will play 5 rounds and coin faces will be changed as follows< After the 1st Round: T H H H H After the 2nd Round: H T H H H After the 3rd Round: T H T H H After the 4th Round: H T H T H After the 5th Round: T H T H T Finally Q=1, so we need to find the total number of coins showing Head, which is 2 In the 2nd game in Example: This is similar to the 1st game, except Elephant needs to find the total number of coins showing Tail. So the Answer is $3$. (Please see the final state of the coins in the $1^{st}$ game) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells. Vova's character can learn new spells during the game. Every spell is characterized by two values x_{i} and y_{i} β€” damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage x and mana cost y for z seconds, then he will deal xΒ·z damage and spend yΒ·z mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously. Also Vova can fight monsters. Every monster is characterized by two values t_{j} and h_{j} β€” monster kills Vova's character in t_{j} seconds and has h_{j} health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones. Vova's character kills a monster, if he deals h_{j} damage to it in no more than t_{j} seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in t_{j} seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight. You have to write a program which can answer two types of queries: 1 x y β€” Vova's character learns new spell which deals x damage per second and costs y mana per second. 2 t h β€” Vova fights the monster which kills his character in t seconds and has h health points. Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game. For every query of second type you have to determine if Vova is able to win the fight with corresponding monster. -----Input----- The first line contains two integer numbers q and m (2 ≀ q ≀ 10^5, 1 ≀ m ≀ 10^12) β€” the number of queries and the amount of mana at the beginning of every fight. i-th of each next q lines contains three numbers k_{i}, a_{i} and b_{i} (1 ≀ k_{i} ≀ 2, 1 ≀ a_{i}, b_{i} ≀ 10^6). Using them you can restore queries this way: let j be the index of the last query of second type with positive answer (j = 0 if there were none of these). If k_{i} = 1, then character learns spell with x = (a_{i} + j) mod 10^6 + 1, y = (b_{i} + j) mod 10^6 + 1. If k_{i} = 2, then you have to determine if Vova is able to win the fight against monster with t = (a_{i} + j) mod 10^6 + 1, h = (b_{i} + j) mod 10^6 + 1. -----Output----- For every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise. -----Example----- Input 3 100 1 4 9 2 19 49 2 19 49 Output YES NO -----Note----- In first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 certain type of steel is graded according to the following conditions. 1. Hardness of the steel must be greater than 50 2. Carbon content of the steel must be less than 0.7 3. Tensile strength must be greater than 5600 The grades awarded are as follows: Grade is 10 if all three conditions are met Grade is 9 if conditions (1) and (2) are met Grade is 8 if conditions (2) and (3) are met Grade is 7 if conditions (1) and (3) are met Grade is 6 if only one condition is met Grade is 5 if none of the three conditions are met Write a program to display the grade of the steel, based on the values of hardness, carbon content and tensile strength of the steel, given by the user. ------ Input Format ------ The first line contains an integer T, total number of testcases. Then follow T lines, each line contains three numbers hardness, carbon content and tensile strength of the steel. ------ Output Format ------ For each test case, print Grade of the steel depending on Conditions, in a new line. ------ Constraints ------ - 1 ≀ T ≀ 1000 - 0 ≀ hardness, carbon content, tensile strength ≀ 10000 ----- Sample Input 1 ------ 3 53 0.6 5602 45 0 4500 0 0 0 ----- Sample Output 1 ------ 10 6 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. Ashish has an array $a$ of size $n$. A subsequence of $a$ is defined as a sequence that can be obtained from $a$ by deleting some elements (possibly none), without changing the order of the remaining elements. Consider a subsequence $s$ of $a$. He defines the cost of $s$ as the minimum between: The maximum among all elements at odd indices of $s$. The maximum among all elements at even indices of $s$. Note that the index of an element is its index in $s$, rather than its index in $a$. The positions are numbered from $1$. So, the cost of $s$ is equal to $min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots))$. For example, the cost of $\{7, 5, 6\}$ is $min( max(7, 6), max(5) ) = min(7, 5) = 5$. Help him find the minimum cost of a subsequence of size $k$. -----Input----- The first line contains two integers $n$ and $k$ ($2 \leq k \leq n \leq 2 \cdot 10^5$) Β β€” the size of the array $a$ and the size of the subsequence. The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) Β β€” the elements of the array $a$. -----Output----- Output a single integer Β β€” the minimum cost of a subsequence of size $k$. -----Examples----- Input 4 2 1 2 3 4 Output 1 Input 4 3 1 2 3 4 Output 2 Input 5 3 5 3 4 2 6 Output 2 Input 6 4 5 3 50 2 4 5 Output 3 -----Note----- In the first test, consider the subsequence $s$ = $\{1, 3\}$. Here the cost is equal to $min(max(1), max(3)) = 1$. In the second test, consider the subsequence $s$ = $\{1, 2, 4\}$. Here the cost is equal to $min(max(1, 4), max(2)) = 2$. In the fourth test, consider the subsequence $s$ = $\{3, 50, 2, 4\}$. Here the cost is equal to $min(max(3, 2), max(50, 4)) = 3$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are m_{i} tasks assigned to the i-th server. In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression m_{a} - m_{b}, where a is the most loaded server and b is the least loaded one. In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another. Write a program to find the minimum number of seconds needed to balance the load of servers. -----Input----- The first line contains positive number n (1 ≀ n ≀ 10^5) β€” the number of the servers. The second line contains the sequence of non-negative integers m_1, m_2, ..., m_{n} (0 ≀ m_{i} ≀ 2Β·10^4), where m_{i} is the number of tasks assigned to the i-th server. -----Output----- Print the minimum number of seconds required to balance the load. -----Examples----- Input 2 1 6 Output 2 Input 7 10 11 10 11 10 11 11 Output 0 Input 5 1 2 3 4 5 Output 3 -----Note----- In the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2. In the second example the load is already balanced. A possible sequence of task movements for the third example is: move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5); then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4); then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). The above sequence is one of several possible ways to balance the load of servers in three seconds. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. 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, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not. A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a_0, a_1, ..., a_{n} - 1 if and only if a_{i} = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points. You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation. -----Input----- The first line contains a single integer n (1 ≀ n ≀ 10^5). The second line contains n integers a_0, a_1, ..., a_{n} - 1 β€” the given permutation. -----Output----- Print a single integer β€” the maximum possible number of fixed points in the permutation after at most one swap operation. -----Examples----- Input 5 0 1 3 4 2 Output 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have N items that you want to put them into a knapsack. Item i has value vi and weight wi. You want to find a subset of items to put such that: * The total value of the items is as large as possible. * The items have combined weight at most W, that is capacity of the knapsack. Find the maximum total value of items in the knapsack. Constraints * 1 ≀ N ≀ 100 * 1 ≀ vi ≀ 100 * 1 ≀ wi ≀ 10,000,000 * 1 ≀ W ≀ 1,000,000,000 Input N W v1 w1 v2 w2 : vN wN The first line consists of the integers N and W. In the following N lines, the value and weight of the i-th item are given. Output Print the maximum total values of the items in a line. Examples Input 4 5 4 2 5 2 2 1 8 3 Output 13 Input 2 20 5 9 4 10 Output 9 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are running through a rectangular field. This field can be represented as a matrix with 3 rows and m columns. (i, j) denotes a cell belonging to i-th row and j-th column. You start in (2, 1) and have to end your path in (2, m). From the cell (i, j) you may advance to: * (i - 1, j + 1) β€” only if i > 1, * (i, j + 1), or * (i + 1, j + 1) β€” only if i < 3. However, there are n obstacles blocking your path. k-th obstacle is denoted by three integers ak, lk and rk, and it forbids entering any cell (ak, j) such that lk ≀ j ≀ rk. You have to calculate the number of different paths from (2, 1) to (2, m), and print it modulo 109 + 7. Input The first line contains two integers n and m (1 ≀ n ≀ 104, 3 ≀ m ≀ 1018) β€” the number of obstacles and the number of columns in the matrix, respectively. Then n lines follow, each containing three integers ak, lk and rk (1 ≀ ak ≀ 3, 2 ≀ lk ≀ rk ≀ m - 1) denoting an obstacle blocking every cell (ak, j) such that lk ≀ j ≀ rk. Some cells may be blocked by multiple obstacles. Output Print the number of different paths from (2, 1) to (2, m), taken modulo 109 + 7. If it is impossible to get from (2, 1) to (2, m), then the number of paths is 0. Example Input 2 5 1 3 4 2 2 3 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of t_{i} minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i c_{i} times. Eugeny's play list is organized as follows: first song number 1 plays c_1 times, then song number 2 plays c_2 times, ..., in the end the song number n plays c_{n} times. Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list. Help Eugeny and calculate the required numbers of songs. -----Input----- The first line contains two integers n, m (1 ≀ n, m ≀ 10^5). The next n lines contain pairs of integers. The i-th line contains integers c_{i}, t_{i} (1 ≀ c_{i}, t_{i} ≀ 10^9) β€” the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 10^9 $(\sum_{i = 1}^{n} c_{i} \cdot t_{i} \leq 10^{9})$. The next line contains m positive integers v_1, v_2, ..., v_{m}, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time v_{i}, when the music doesn't play any longer. It is guaranteed that v_{i} < v_{i} + 1 (i < m). The moment of time v_{i} means that Eugeny wants to know which song was playing during the v_{i}-th munite from the start of listening to the playlist. -----Output----- Print m integers β€” the i-th number must equal the number of the song that was playing during the v_{i}-th minute after Eugeny started listening to the play list. -----Examples----- Input 1 2 2 8 1 16 Output 1 1 Input 4 9 1 2 2 1 1 1 2 2 1 2 3 4 5 6 7 8 9 Output 1 1 2 2 3 4 4 4 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. I need to save some money to buy a gift. I think I can do something like that: First week (W0) I save nothing on Sunday, 1 on Monday, 2 on Tuesday... 6 on Saturday, second week (W1) 2 on Monday... 7 on Saturday and so on according to the table below where the days are numbered from 0 to 6. Can you tell me how much I will have for my gift on Saturday evening after I have saved 12? (Your function finance(6) should return 168 which is the sum of the savings in the table). Imagine now that we live on planet XY140Z-n where the days of the week are numbered from 0 to n (integer n > 0) and where I save from week number 0 to week number n included (in the table below n = 6). How much money would I have at the end of my financing plan on planet XY140Z-n? -- |Su|Mo|Tu|We|Th|Fr|Sa| --|--|--|--|--|--|--|--| W6 | | | | | | |12| W5 | | | | | |10|11| W4 | | | | |8 |9 |10| W3 | | | |6 |7 |8 |9 | W2 | | |4 |5 |6 |7 |8 | W1 | |2 |3 |4 |5 |6 |7 | W0 |0 |1 |2 |3 |4 |5 |6 | #Example: ``` finance(5) --> 105 finance(6) --> 168 finance(7) --> 252 finance(5000) --> 62537505000 ``` #Hint: try to avoid nested loops Read the inputs from stdin solve the problem and write the answer to stdout (do 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 built an online judge to hold a programming contest. When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring. (The judge can return any two-character substring of S.) Determine whether the judge can return the string `AC` as the verdict to a program. Constraints * 2 \leq |S| \leq 5 * S consists of uppercase English letters. Input Input is given from Standard Input in the following format: S Output If the judge can return the string `AC` as a verdict to a program, print `Yes`; if it cannot, print `No`. Examples Input BACD Output Yes Input ABCD Output No Input CABD Output No Input ACACA Output Yes Input XX 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. Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly k months. He looked at the calendar and learned that at the moment is the month number s. Vasya immediately got interested in what month Codecraft III will appear. Help him understand that. All the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December. Input The first input line contains the name of the current month. It is guaranteed that it is a proper English name of one of twelve months. The first letter is uppercase, the rest are lowercase. The second line contains integer k (0 ≀ k ≀ 100) β€” the number of months left till the appearance of Codecraft III. Output Print starting from an uppercase letter the name of the month in which the continuation of Codeforces II will appear. The printed name must be contained in the list January, February, March, April, May, June, July, August, September, October, November, December. Examples Input November 3 Output February Input May 24 Output May Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. For a set $S$ of integers, perform a sequence of the following operations. Note that multiple elements can have equivalent values in $S$. * insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation. * find($x$): Report the number of $x$ in $S$. * delete($x$): Delete all $x$ from $S$. * dump($L$, $R$): Print elements $x$ in $S$ such that $L \leq x \leq R$. Constraints * $1 \leq q \leq 200,000$ * $0 \leq x \leq 1,000,000,000$ * The total number of elements printed by dump operations does not exceed $1,000,000$ * The sum of numbers printed by find operations does not exceed $2,000,000$ Input The input is given in the following format. $q$ $query_1$ $query_2$ : $query_q$ Each query $query_i$ is given by 0 $x$ or 1 $x$ or 2 $x$ or 3 $L$ $R$ where the first digits 0, 1, 2 and 3 represent insert, find, delete and dump operations respectively. Output For each insert operation, print the number of elements in $S$. For each find operation, print the number of specified elements in $S$. For each dump operation, print the corresponding elements in ascending order. Print an element in a line. Example Input 10 0 1 0 1 0 2 0 3 2 2 1 1 1 2 1 3 0 4 3 1 4 Output 1 2 3 4 2 0 1 4 1 1 3 4 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given is a string S of length N consisting of lowercase English letters. Snuke can do this operation any number of times: remove fox occurring as a substring from s and concatenate the remaining parts of s. What is the minimum possible length of s after some number of operations by Snuke? -----Constraints----- - 1 \leq N \leq 2 \times 10^{5} - s is a string of length N consisting of lowercase English letters. -----Input----- Input is given from Standard Input in the following format: N s -----Print----- Print the minimum possible length of s after some number of operations by Snuke. -----Sample Input----- 6 icefox -----Sample Output----- 3 - By removing the fox at the end of icefox, we can turn s into ice. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. She does her utmost to flawlessly carry out a person's last rites and preserve the world's balance of yin and yang. Hu Tao, being the little prankster she is, has tried to scare you with this graph problem! You are given a connected undirected graph of n nodes with m edges. You also have q queries. Each query consists of two nodes a and b. Initially, all edges in the graph have a weight of 0. For each query, you must choose a simple path starting from a and ending at b. Then you add 1 to every edge along this path. Determine if it's possible, after processing all q queries, for all edges in this graph to have an even weight. If so, output the choice of paths for each query. If it is not possible, determine the smallest number of extra queries you could add to make it possible. It can be shown that this number will not exceed 10^{18} under the given constraints. A simple path is defined as any path that does not visit a node more than once. An edge is said to have an even weight if its value is divisible by 2. Input The first line contains two integers n and m (2 ≀ n ≀ 3 β‹… 10^5, n-1 ≀ m ≀ min{\left((n(n-1))/(2), 3 β‹… 10^5\right)}). Each of the next m lines contains two integers x and y (1 ≀ x, y ≀ n, xβ‰  y) indicating an undirected edge between node x and y. The input will not contain self-loops or duplicate edges, and the provided graph will be connected. The next line contains a single integer q (1 ≀ q ≀ 3 β‹… 10^5). Each of the next q lines contains two integers a and b (1 ≀ a, b ≀ n, a β‰  b), the description of each query. It is guaranteed that nq ≀ 3 β‹… 10^5. Output If it is possible to force all edge weights to be even, print "YES" on the first line, followed by 2q lines indicating the choice of path for each query in the same order the queries are given. For each query, the first line should contain a single integer x: the number of nodes in the chosen path. The next line should then contain x spaced separated integers p_i indicating the path you take (p_1 = a, p_x = b and all numbers should fall between 1 and n). This path cannot contain duplicate nodes and must be a valid simple path in the graph. If it is impossible to force all edge weights to be even, print "NO" on the first line and the minimum number of added queries on the second line. Examples Input 6 7 2 1 2 3 3 5 1 4 6 1 5 6 4 5 3 1 4 5 1 4 5 Output YES 2 1 4 4 5 3 2 1 5 4 1 2 3 5 Input 5 7 4 3 4 5 2 1 1 4 1 3 3 5 3 2 4 4 2 3 5 5 1 4 5 Output NO 2 Note Here is what the queries look like for the first test case (red corresponds to the 1st query, blue 2nd query, and green 3rd query): <image> Notice that every edge in the graph is part of either 0 or 2 colored query edges. The graph in the second test case looks like this: <image> There does not exist an assignment of paths that will force all edges to have even weights with the given queries. One must add at least 2 new queries to obtain a set of queries that can satisfy the condition. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Madoka decided to entrust the organization of a major computer game tournament "OSU"! In this tournament, matches are held according to the "Olympic system". In other words, there are $2^n$ participants in the tournament, numbered with integers from $1$ to $2^n$. There are $n$ rounds in total in the tournament. In the $i$-th round there are $2^{n - i}$ matches between two players (one of whom is right, the other is left), after which the winners go further along the tournament grid, and the losing participants are eliminated from the tournament. Herewith, the relative order in the next round does not change. And the winner of the tournament β€” is the last remaining participant. But the smaller the participant's number, the more he will pay Madoka if he wins, so Madoka wants the participant with the lowest number to win. To do this, she can arrange the participants in the first round as she likes, and also determine for each match who will win β€” the participant on the left or right. But Madoka knows that tournament sponsors can change the winner in matches no more than $k$ times. (That is, if the participant on the left won before the change, then the participant on the right will win after the change, and if the participant on the right won, then the participant on the left will win after the change). So, the first image shows the tournament grid that Madoka made, where the red lines denote who should win the match. And the second one shows the tournament grid, after one change in the outcome of the match by sponsors (a match between $1$ and $3$ players). Print the minimum possible number of the winner in the tournament, which Madoka can get regardless of changes in sponsors. But since the answer can be very large, output it modulo $10^9 + 7$. Note that we need to minimize the answer, and only then take it modulo. -----Input----- The first and the only line contains two integers $n$ and $k$ ($1 \le n \le 10^5, 1 \le k \le \min(2^n - 1, 10^9)$) β€” the number of rounds in the tournament and the number of outcomes that sponsors can change. -----Output----- Print exactly one integer β€” the minimum number of the winner modulo $10^9 + 7$ -----Examples----- Input 1 1 Output 2 Input 2 1 Output 3 Input 3 2 Output 7 -----Note----- In the first example, there is only one match between players $1$ and $2$, so the sponsors can always make player $2$ wins. The tournament grid from the second example is shown in the picture in the statement. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 gems. The value of the i-th gem is V_i. You will choose some of these gems, possibly all or none, and get them. However, you need to pay a cost of C_i to get the i-th gem. Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid. Find the maximum possible value of X-Y. -----Constraints----- - All values in input are integers. - 1 \leq N \leq 20 - 1 \leq C_i, V_i \leq 50 -----Input----- Input is given from Standard Input in the following format: N V_1 V_2 ... V_N C_1 C_2 ... C_N -----Output----- Print the maximum possible value of X-Y. -----Sample Input----- 3 10 2 5 6 3 4 -----Sample Output----- 5 If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10. We have X-Y = 5 here, which is the maximum possible value. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 know a story about the three musketeers? Anyway, you will learn about its origins now. Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys. There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers. Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions. -----Input----- The first line contains two space-separated integers, n and m (3 ≀ n ≀ 4000, 0 ≀ m ≀ 4000) β€” respectively number of warriors and number of pairs of warriors knowing each other. i-th of the following m lines contains two space-separated integers a_{i} and b_{i} (1 ≀ a_{i}, b_{i} ≀ n, a_{i} β‰  b_{i}). Warriors a_{i} and b_{i} know each other. Each pair of warriors will be listed at most once. -----Output----- If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print "-1" (without the quotes). -----Examples----- Input 5 6 1 2 1 3 2 3 2 4 3 4 4 5 Output 2 Input 7 4 2 1 3 6 5 1 1 7 Output -1 -----Note----- In the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1 because he knows warrior 4. Sum of recognitions is 0 + 1 + 1 = 2. The other possible triple is 2, 3, 4 but it has greater sum of recognitions, equal to 1 + 1 + 1 = 3. In the second sample there is no triple of warriors knowing each other. Read the inputs from stdin solve the problem and write the answer to stdout (do 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$ models in the shop numbered from $1$ to $n$, with sizes $s_1, s_2, \ldots, s_n$. Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes). Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices $i_j$ and $i_{j+1}$ (note that $i_j < i_{j+1}$, because Orac arranged them properly), $i_{j+1}$ is divisible by $i_j$ and $s_{i_j} < s_{i_{j+1}}$. For example, for $6$ models with sizes $\{3, 6, 7, 7, 7, 7\}$, he can buy models with indices $1$, $2$, and $6$, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful. Orac wants to know the maximum number of models that he can buy, and he may ask you these queries many times. -----Input----- The first line contains one integer $t\ (1 \le t\le 100)$: the number of queries. Each query contains two lines. The first line contains one integer $n\ (1\le n\le 100\,000)$: the number of models in the shop, and the second line contains $n$ integers $s_1,\dots,s_n\ (1\le s_i\le 10^9)$: the sizes of models. It is guaranteed that the total sum of $n$ is at most $100\,000$. -----Output----- Print $t$ lines, the $i$-th of them should contain the maximum number of models that Orac can buy for the $i$-th query. -----Example----- Input 4 4 5 3 4 6 7 1 4 2 3 6 4 9 5 5 4 3 2 1 1 9 Output 2 3 1 1 -----Note----- In the first query, for example, Orac can buy models with indices $2$ and $4$, the arrangement will be beautiful because $4$ is divisible by $2$ and $6$ is more than $3$. By enumerating, we can easily find that there are no beautiful arrangements with more than two models. In the second query, Orac can buy models with indices $1$, $3$, and $6$. By enumerating, we can easily find that there are no beautiful arrangements with more than three models. In the third query, there are no beautiful arrangements with more than one model. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not. First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p_1, the glass from the second position to position p_2 and so on. That is, a glass goes from position i to position p_{i}. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in. After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t. -----Input----- The first line contains three integers: n, s, t (1 ≀ n ≀ 10^5;Β 1 ≀ s, t ≀ n) β€” the number of glasses, the ball's initial and final position. The second line contains n space-separated integers: p_1, p_2, ..., p_{n} (1 ≀ p_{i} ≀ n) β€” the shuffling operation parameters. It is guaranteed that all p_{i}'s are distinct. Note that s can equal t. -----Output----- If the marble can move from position s to position t, then print on a single line a non-negative integer β€” the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1. -----Examples----- Input 4 2 1 2 3 4 1 Output 3 Input 4 3 3 4 1 3 2 Output 0 Input 4 3 4 1 2 3 4 Output -1 Input 3 1 3 2 1 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. A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≀ pi ≀ n). A lucky permutation is such permutation p, that any integer i (1 ≀ i ≀ n) meets this condition ppi = n - i + 1. You have integer n. Find some lucky permutation p of size n. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the required permutation size. Output Print "-1" (without the quotes) if the lucky permutation p of size n doesn't exist. Otherwise, print n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) after a space β€” the required permutation. If there are multiple answers, you can print any of them. Examples Input 1 Output 1 Input 2 Output -1 Input 4 Output 2 4 1 3 Input 5 Output 2 5 3 1 4 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have $n$ students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the $i$-th student skill is denoted by an integer $a_i$ (different students can have the same skills). So, about the teams. Firstly, these two teams should have the same size. Two more constraints: The first team should consist of students with distinct skills (i.e. all skills in the first team are unique). The second team should consist of students with the same skills (i.e. all skills in the second team are equal). Note that it is permissible that some student of the first team has the same skill as a student of the second team. Consider some examples (skills are given): $[1, 2, 3]$, $[4, 4]$ is not a good pair of teams because sizes should be the same; $[1, 1, 2]$, $[3, 3, 3]$ is not a good pair of teams because the first team should not contain students with the same skills; $[1, 2, 3]$, $[3, 4, 4]$ is not a good pair of teams because the second team should contain students with the same skills; $[1, 2, 3]$, $[3, 3, 3]$ is a good pair of teams; $[5]$, $[6]$ is a good pair of teams. Your task is to find the maximum possible size $x$ for which it is possible to compose a valid pair of teams, where each team size is $x$ (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) β€” the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β€” the number of students. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the skill of the $i$-th student. Different students can have the same skills. It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$). -----Output----- For each test case, print the answer β€” the maximum possible size $x$ for which it is possible to compose a valid pair of teams, where each team size is $x$. -----Example----- Input 4 7 4 2 4 1 4 3 4 5 2 1 5 4 3 1 1 4 1 1 1 3 Output 3 1 0 2 -----Note----- In the first test case of the example, it is possible to construct two teams of size $3$: the first team is $[1, 2, 4]$ and the second team is $[4, 4, 4]$. Note, that there are some other ways to construct two valid teams of size $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. Natsuki and her friends were taken to the space by an alien and made friends with a lot of aliens. During the space travel, she discovered that aliens’ hands were often very different from humans’. Generally speaking, in a kind of aliens, there are N fingers and M bend rules on a hand. Each bend rule describes that a finger A always bends when a finger B bends. However, this rule does not always imply that the finger B bends when the finger A bends. When she were counting numbers with the fingers, she was anxious how many numbers her alien friends can count with the fingers. However, because some friends had too complicated rule sets, she could not calculate those. Would you write a program for her? Input N M S1 D1 S2 D2 . . . SM DM The first line contains two integers N and M (1 ≀ N ≀ 1000, 0 ≀ M ≀ 1000) in this order. The following M lines mean bend rules. Each line contains two integers Si and Di in this order, which mean that the finger Di always bends when the finger Si bends. Any finger appears at most once in S. Output Calculate how many numbers her alien friends can count with the fingers. Print the answer modulo 1000000007 in a line. Examples Input 5 4 2 3 3 4 4 3 5 4 Output 10 Input 5 5 1 2 2 3 3 4 4 5 5 1 Output 2 Input 5 0 Output 32 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an array of $n$ integers $a_1$, $a_2$, ..., $a_n$, and a set $b$ of $k$ distinct integers from $1$ to $n$. In one operation, you may choose two integers $i$ and $x$ ($1 \le i \le n$, $x$ can be any integer) and assign $a_i := x$. This operation can be done only if $i$ does not belong to the set $b$. Calculate the minimum number of operations you should perform so the array $a$ is increasing (that is, $a_1 < a_2 < a_3 < \dots < a_n$), or report that it is impossible. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le n \le 5 \cdot 10^5$, $0 \le k \le n$) β€” the size of the array $a$ and the set $b$, respectively. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$). Then, if $k \ne 0$, the third line follows, containing $k$ integers $b_1$, $b_2$, ..., $b_k$ ($1 \le b_1 < b_2 < \dots < b_k \le n$). If $k = 0$, this line is skipped. -----Output----- If it is impossible to make the array $a$ increasing using the given operations, print $-1$. Otherwise, print one integer β€” the minimum number of operations you have to perform. -----Examples----- Input 7 2 1 2 1 1 3 5 1 3 5 Output 4 Input 3 3 1 3 2 1 2 3 Output -1 Input 5 0 4 3 1 2 3 Output 2 Input 10 3 1 3 5 6 12 9 8 10 13 15 2 4 9 Output 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction. Pavel has a plan: a permutation p and a sequence b_1, b_2, ..., b_{n}, consisting of zeros and ones. Each second Pavel move skewer on position i to position p_{i}, and if b_{i} equals 1 then he reverses it. So he hope that every skewer will visit every position in both directions. Unfortunately, not every pair of permutation p and sequence b suits Pavel. What is the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements? Note that after changing the permutation should remain a permutation as well. There is no problem for Pavel, if some skewer visits some of the placements several times before he ends to cook. In other words, a permutation p and a sequence b suit him if there is an integer k (k β‰₯ 2n), so that after k seconds each skewer visits each of the 2n placements. It can be shown that some suitable pair of permutation p and sequence b exists for any n. -----Input----- The first line contain the integer n (1 ≀ n ≀ 2Β·10^5)Β β€” the number of skewers. The second line contains a sequence of integers p_1, p_2, ..., p_{n} (1 ≀ p_{i} ≀ n)Β β€” the permutation, according to which Pavel wants to move the skewers. The third line contains a sequence b_1, b_2, ..., b_{n} consisting of zeros and ones, according to which Pavel wants to reverse the skewers. -----Output----- Print single integerΒ β€” the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements. -----Examples----- Input 4 4 3 2 1 0 1 1 1 Output 2 Input 3 2 3 1 0 0 0 Output 1 -----Note----- In the first example Pavel can change the permutation to 4, 3, 1, 2. In the second example Pavel can change any element of b to 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. In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game. Tzuyu gave Sana two integers $a$ and $b$ and a really important quest. In order to complete the quest, Sana has to output the smallest possible value of ($a \oplus x$) + ($b \oplus x$) for any given $x$, where $\oplus$ denotes the bitwise XOR operation. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^{4}$). Description of the test cases follows. The only line of each test case contains two integers $a$ and $b$ ($1 \le a, b \le 10^{9}$). -----Output----- For each testcase, output the smallest possible value of the given expression. -----Example----- Input 6 6 12 4 9 59 832 28 14 4925 2912 1 1 Output 10 13 891 18 6237 0 -----Note----- For the first test case Sana can choose $x=4$ and the value will be ($6 \oplus 4$) + ($12 \oplus 4$) = $2 + 8$ = $10$. It can be shown that this is the smallest possible value. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.