question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset. Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types: 1. Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. 2. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. 3. Count the number of instances of the given integer that are stored in the multiset. But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example. * First Artem adds integer 5 to the multiset at the 1-st moment of time. * Then Artem adds integer 3 to the multiset at the moment 5. * Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. * Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. * Then Artem goes back in time again and removes 5 from the multiset at moment 3. * Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3. Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes. Help Artem implement time travellers multiset. Input The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries. Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent. Output For each ask operation output the number of instances of integer being queried at the given moment of time. Examples Input 6 1 1 5 3 5 5 1 2 5 3 6 5 2 3 5 3 7 5 Output 1 2 1 Input 3 1 1 1 2 2 1 3 3 1 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number n. There are m buses running between the house and the school: the i-th bus goes from stop si to ti (si < ti), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the i-th bus on any stop numbered from si to ti - 1 inclusive, but he can get off the i-th bus only on the bus stop ti. Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house. Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109 + 7). Input The first line contains two space-separated integers: n and m (1 ≤ n ≤ 109, 0 ≤ m ≤ 105). Then follow m lines each containing two integers si, ti. They are the numbers of starting stops and end stops of the buses (0 ≤ si < ti ≤ n). Output Print the only number — the number of ways to get to the school modulo 1000000007 (109 + 7). Examples Input 2 2 0 1 1 2 Output 1 Input 3 2 0 1 1 2 Output 0 Input 5 5 0 1 0 2 0 3 0 4 0 5 Output 16 Note The first test has the only variant to get to school: first on bus number one to the bus stop number one; then on bus number two to the bus stop number two. In the second test no bus goes to the third bus stop, where the school is positioned. Thus, the correct answer is 0. In the third test Gerald can either get or not on any of the first four buses to get closer to the school. Thus, the correct answer is 24 = 16. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase. Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys. Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips. You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand. Input The first line contains three integers n, m, x (1 ≤ n, m ≤ 30, 1 ≤ x ≤ 50). Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol. Then follow the length of the text q (1 ≤ q ≤ 5·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters. Output If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes). Examples Input 2 2 1 ab cd 1 A Output -1 Input 2 2 1 ab cd 1 e Output -1 Input 2 2 1 ab cS 5 abcBA Output 1 Input 3 9 4 qwertyuio asdfghjkl SzxcvbnmS 35 TheQuIcKbRoWnFOXjummsovertHeLazYDOG Output 2 Note In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard. In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard. In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them. Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted. Road repairs are planned for n^2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads. According to the schedule of road works tell in which days at least one road will be asphalted. -----Input----- The first line contains integer n (1 ≤ n ≤ 50) — the number of vertical and horizontal roads in the city. Next n^2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers h_{i}, v_{i} (1 ≤ h_{i}, v_{i} ≤ n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the h_{i}-th horizontal and v_{i}-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct. -----Output----- In the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1. -----Examples----- Input 2 1 1 1 2 2 1 2 2 Output 1 4 Input 1 1 1 Output 1 -----Note----- In the sample the brigade acts like that: On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road; On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been asphalted, but as the 1-st horizontal road has been asphalted on the first day, the workers leave and do not asphalt anything; On the third day the brigade of the workers come to the intersection of the 2-nd horizontal and the 1-st vertical road. The 2-nd horizontal road hasn't been asphalted but as the 1-st vertical road has been asphalted on the first day, the workers leave and do not asphalt anything; On the fourth day the brigade come to the intersection formed by the intersection of the 2-nd horizontal and 2-nd vertical road. As none of them has been asphalted, the workers asphalt the 2-nd vertical and the 2-nd horizontal road. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half. [Image] English alphabet You are given a string s. Check if the string is "s-palindrome". -----Input----- The only line contains the string s (1 ≤ |s| ≤ 1000) which consists of only English letters. -----Output----- Print "TAK" if the string s is "s-palindrome" and "NIE" otherwise. -----Examples----- Input oXoxoXo Output TAK Input bod Output TAK Input ER Output NIE Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have a team of N people. For a particular task, you can pick any non-empty subset of people. The cost of having x people for the task is x^{k}. Output the sum of costs over all non-empty subsets of people. -----Input----- Only line of input contains two integers N (1 ≤ N ≤ 10^9) representing total number of people and k (1 ≤ k ≤ 5000). -----Output----- Output the sum of costs for all non empty subsets modulo 10^9 + 7. -----Examples----- Input 1 1 Output 1 Input 3 2 Output 24 -----Note----- In the first example, there is only one non-empty subset {1} with cost 1^1 = 1. In the second example, there are seven non-empty subsets. - {1} with cost 1^2 = 1 - {2} with cost 1^2 = 1 - {1, 2} with cost 2^2 = 4 - {3} with cost 1^2 = 1 - {1, 3} with cost 2^2 = 4 - {2, 3} with cost 2^2 = 4 - {1, 2, 3} with cost 3^2 = 9 The total cost is 1 + 1 + 4 + 1 + 4 + 4 + 9 = 24. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a polynomial of degree N with integer coefficients: f(x)=a_Nx^N+a_{N-1}x^{N-1}+...+a_0. Find all prime numbers p that divide f(x) for every integer x. Constraints * 0 \leq N \leq 10^4 * |a_i| \leq 10^9(0\leq i\leq N) * a_N \neq 0 * All values in input are integers. Input Input is given from Standard Input in the following format: N a_N : a_0 Output Print all prime numbers p that divide f(x) for every integer x, in ascending order. Examples Input 2 7 -7 14 Output 2 7 Input 3 1 4 1 5 Output Input 0 998244353 Output 998244353 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sitting in a station waiting room, Joisino is gazing at her train ticket. The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive). In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with + or - so that the formula holds. The given input guarantees that there is a solution. If there are multiple solutions, any of them will be accepted. -----Constraints----- - 0≤A,B,C,D≤9 - All input values are integers. - It is guaranteed that there is a solution. -----Input----- Input is given from Standard Input in the following format: ABCD -----Output----- Print the formula you made, including the part =7. Use the signs + and -. Do not print a space between a digit and a sign. -----Sample Input----- 1222 -----Sample Output----- 1+2+2+2=7 This is the only valid solution. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ## Task You will receive a string consisting of lowercase letters, uppercase letters and digits as input. Your task is to return this string as blocks separated by dashes (`"-"`). The elements of a block should be sorted with respect to the hierarchy listed below, and each block cannot contain multiple instances of the same character. Elements should be put into the first suitable block. The hierarchy is: 1. lowercase letters (`a - z`), in alphabetical order 2. uppercase letters (`A - Z`), in alphabetical order 3. digits (`0 - 9`), in ascending order ## Examples * `"21AxBz" -> "xzAB12"` - since input does not contain repeating characters, you only need 1 block * `"abacad" -> "abcd-a-a"` - character "a" repeats 3 times, thus 3 blocks are needed * `"" -> ""` - an empty input should result in an empty output * `"hbh420sUUW222IWOxndjn93cdop69NICEep832" -> "bcdehjnopsxCEINOUW0234689-dhnpIUW239-2-2-2"` - a more sophisticated example Good luck! Write your solution by modifying this code: ```python def blocks(s): ``` Your solution should implemented in the function "blocks". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Amidakuji is a traditional method of lottery in Japan. To make an amidakuji, we first draw W parallel vertical lines, and then draw horizontal lines that connect them. The length of each vertical line is H+1 [cm], and the endpoints of the horizontal lines must be at 1, 2, 3, ..., or H [cm] from the top of a vertical line. A valid amidakuji is an amidakuji that satisfies the following conditions: - No two horizontal lines share an endpoint. - The two endpoints of each horizontal lines must be at the same height. - A horizontal line must connect adjacent vertical lines. Find the number of the valid amidakuji that satisfy the following condition, modulo 1\ 000\ 000\ 007: if we trace the path from the top of the leftmost vertical line to the bottom, always following horizontal lines when we encounter them, we reach the bottom of the K-th vertical line from the left. For example, in the following amidakuji, we will reach the bottom of the fourth vertical line from the left. -----Constraints----- - H is an integer between 1 and 100 (inclusive). - W is an integer between 1 and 8 (inclusive). - K is an integer between 1 and W (inclusive). -----Input----- Input is given from Standard Input in the following format: H W K -----Output----- Print the number of the amidakuji that satisfy the condition, modulo 1\ 000\ 000\ 007. -----Sample Input----- 1 3 2 -----Sample Output----- 1 Only the following one amidakuji satisfies 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. Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1 ≤ p < |s|) and perform one of the following actions: * either replace letter sp with the one that alphabetically follows it and replace letter sp + 1 with the one that alphabetically precedes it; * or replace letter sp with the one that alphabetically precedes it and replace letter sp + 1 with the one that alphabetically follows it. Let us note that letter "z" doesn't have a defined following letter and letter "a" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed. Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations. Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109 + 7). Input The input data contains several tests. The first line contains the only integer t (1 ≤ t ≤ 104) — the number of tests. Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ. Output For each word you should print the number of different other words that coincide with it in their meaning — not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109 + 7). Examples Input 1 ab Output 1 Input 1 aaaaaaaaaaa Output 0 Input 2 ya klmbfxzb Output 24 320092793 Note Some explanations about the operation: * Note that for each letter, we can clearly define the letter that follows it. Letter "b" alphabetically follows letter "a", letter "c" follows letter "b", ..., "z" follows letter "y". * Preceding letters are defined in the similar manner: letter "y" precedes letter "z", ..., "a" precedes letter "b". * Note that the operation never changes a word's length. In the first sample you can obtain the only other word "ba". In the second sample you cannot obtain any other word, so the correct answer is 0. Consider the third sample. One operation can transform word "klmbfxzb" into word "klmcexzb": we should choose p = 4, and replace the fourth letter with the following one ("b" → "c"), and the fifth one — with the preceding one ("f" → "e"). Also, we can obtain many other words from this one. An operation can transform word "ya" only into one other word "xb". Word "ya" coincides in its meaning with words "xb", "wc", "vd", ..., "ay" (overall there are 24 other words). The word "klmbfxzb has many more variants — there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 — the number 3320092814 modulo 109 + 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. The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills. The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of $5 = 101_2$ and $14 = 1110_2$ equals to $3$, since $0101$ and $1110$ differ in $3$ positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants. Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from $0$ to $n$. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers. -----Input----- The input consists of multiple test cases. The first line contains one integer $t$ ($1 \leq t \leq 10\,000$) — the number of test cases. The following $t$ lines contain a description of test cases. The first and only line in each test case contains a single integer $n$ ($1 \leq n \leq 10^{18})$. -----Output----- Output $t$ lines. For each test case, you should output a single line with one integer — the unfairness of the contest if the rating sequence equals to $0$, $1$, ..., $n - 1$, $n$. -----Example----- Input 5 5 7 11 1 2000000000000 Output 8 11 19 1 3999999999987 -----Note----- For $n = 5$ we calculate unfairness of the following sequence (numbers from $0$ to $5$ written in binary with extra leading zeroes, so they all have the same length): $000$ $001$ $010$ $011$ $100$ $101$ The differences are equal to $1$, $2$, $1$, $3$, $1$ respectively, so unfairness is equal to $1 + 2 + 1 + 3 + 1 = 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. Authors have come up with the string $s$ consisting of $n$ lowercase Latin letters. You are given two permutations of its indices (not necessary equal) $p$ and $q$ (both of length $n$). Recall that the permutation is the array of length $n$ which contains each integer from $1$ to $n$ exactly once. For all $i$ from $1$ to $n-1$ the following properties hold: $s[p_i] \le s[p_{i + 1}]$ and $s[q_i] \le s[q_{i + 1}]$. It means that if you will write down all characters of $s$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order. Your task is to restore any such string $s$ of length $n$ consisting of at least $k$ distinct lowercase Latin letters which suits the given permutations. If there are multiple answers, you can print any of them. -----Input----- The first line of the input contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5, 1 \le k \le 26$) — the length of the string and the number of distinct characters required. The second line of the input contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ are distinct integers from $1$ to $n$) — the permutation $p$. The third line of the input contains $n$ integers $q_1, q_2, \dots, q_n$ ($1 \le q_i \le n$, all $q_i$ are distinct integers from $1$ to $n$) — the permutation $q$. -----Output----- If it is impossible to find the suitable string, print "NO" on the first line. Otherwise print "YES" on the first line and string $s$ on the second line. It should consist of $n$ lowercase Latin letters, contain at least $k$ distinct characters and suit the given permutations. If there are multiple answers, you can print any of them. -----Example----- Input 3 2 1 2 3 1 3 2 Output YES abb Read the inputs from stdin solve the problem and write the answer to stdout (do 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 $2n+1$ integer points on a Cartesian plane. Points are numbered from $0$ to $2n$ inclusive. Let $P_i$ be the $i$-th point. The $x$-coordinate of the point $P_i$ equals $i$. The $y$-coordinate of the point $P_i$ equals zero (initially). Thus, initially $P_i=(i,0)$. The given points are vertices of a plot of a piecewise function. The $j$-th piece of the function is the segment $P_{j}P_{j + 1}$. In one move you can increase the $y$-coordinate of any point with odd $x$-coordinate (i.e. such points are $P_1, P_3, \dots, P_{2n-1}$) by $1$. Note that the corresponding segments also change. For example, the following plot shows a function for $n=3$ (i.e. number of points is $2\cdot3+1=7$) in which we increased the $y$-coordinate of the point $P_1$ three times and $y$-coordinate of the point $P_5$ one time: [Image] Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it). Let the height of the plot be the maximum $y$-coordinate among all initial points in the plot (i.e. points $P_0, P_1, \dots, P_{2n}$). The height of the plot on the picture above is 3. Your problem is to say which minimum possible height can have the plot consisting of $2n+1$ vertices and having an area equal to $k$. Note that it is unnecessary to minimize the number of moves. It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $10^{18}$. -----Input----- The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 10^{18}$) — the number of vertices in a plot of a piecewise function and the area we need to obtain. -----Output----- Print one integer — the minimum possible height of a plot consisting of $2n+1$ vertices and with an area equals $k$. It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $10^{18}$. -----Examples----- Input 4 3 Output 1 Input 4 12 Output 3 Input 999999999999999999 999999999999999986 Output 1 -----Note----- One of the possible answers to the first example: [Image] The area of this plot is 3, the height of this plot is 1. There is only one possible answer to the second example: $M M$ The area of this plot is 12, the height of this plot is 3. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. An AI has infected a text with a character!! This text is now **fully mutated** to this character. If the text or the character are empty, return an empty string. There will never be a case when both are empty as nothing is going on!! **Note:** The character is a string of length 1 or an empty string. # Example ```python text before = "abc" character = "z" text after = "zzz" ``` Write your solution by modifying this code: ```python def contamination(text, char): ``` Your solution should implemented in the function "contamination". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Kostya likes the number 4 much. Of course! This number has such a lot of properties, like: - Four is the smallest composite number; - It is also the smallest Smith number; - The smallest non-cyclic group has four elements; - Four is the maximal degree of the equation that can be solved in radicals; - There is four-color theorem that states that any map can be colored in no more than four colors in such a way that no two adjacent regions are colored in the same color; - Lagrange's four-square theorem states that every positive integer can be written as the sum of at most four square numbers; - Four is the maximum number of dimensions of a real division algebra; - In bases 6 and 12, 4 is a 1-automorphic number; - And there are a lot more cool stuff about this number! Impressed by the power of this number, Kostya has begun to look for occurrences of four anywhere. He has a list of T integers, for each of them he wants to calculate the number of occurrences of the digit 4 in the decimal representation. He is too busy now, so please help him. -----Input----- The first line of input consists of a single integer T, denoting the number of integers in Kostya's list. Then, there are T lines, each of them contain a single integer from the list. -----Output----- Output T lines. Each of these lines should contain the number of occurences of the digit 4 in the respective integer from Kostya's list. -----Constraints----- - 1 ≤ T ≤ 105 - (Subtask 1): 0 ≤ Numbers from the list ≤ 9 - 33 points. - (Subtask 2): 0 ≤ Numbers from the list ≤ 109 - 67 points. -----Example----- Input: 5 447474 228 6664 40 81 Output: 4 0 1 1 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time. Polycarp is good at marketing, so he has already collected n requests from clients. The requests are numbered from 1 to n in order they came. The i-th request is characterized by two values: s_{i} — the day when a client wants to start the repair of his car, d_{i} — duration (in days) to repair the car. The days are enumerated from 1, the first day is tomorrow, the second day is the day after tomorrow and so on. Polycarp is making schedule by processing requests in the order from the first to the n-th request. He schedules the i-th request as follows: If the car repair shop is idle for d_{i} days starting from s_{i} (s_{i}, s_{i} + 1, ..., s_{i} + d_{i} - 1), then these days are used to repair a car of the i-th client. Otherwise, Polycarp finds the first day x (from 1 and further) that there are d_{i} subsequent days when no repair is scheduled starting from x. In other words he chooses the smallest positive x that all days x, x + 1, ..., x + d_{i} - 1 are not scheduled for repair of any car. So, the car of the i-th client will be repaired in the range [x, x + d_{i} - 1]. It is possible that the day x when repair is scheduled to start will be less than s_{i}. Given n requests, you are asked to help Polycarp schedule all of them according to the rules above. -----Input----- The first line contains integer n (1 ≤ n ≤ 200) — the number of requests from clients. The following n lines contain requests, one request per line. The i-th request is given as the pair of integers s_{i}, d_{i} (1 ≤ s_{i} ≤ 10^9, 1 ≤ d_{i} ≤ 5·10^6), where s_{i} is the preferred time to start repairing the i-th car, d_{i} is the number of days to repair the i-th car. The requests should be processed in the order they are given in the input. -----Output----- Print n lines. The i-th line should contain two integers — the start day to repair the i-th car and the finish day to repair the i-th car. -----Examples----- Input 3 9 2 7 3 2 4 Output 9 10 1 3 4 7 Input 4 1000000000 1000000 1000000000 1000000 100000000 1000000 1000000000 1000000 Output 1000000000 1000999999 1 1000000 100000000 100999999 1000001 2000000 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical! She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order. Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet. Input The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different. Output If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes). Examples Input 3 rivest shamir adleman Output bcdefghijklmnopqrsatuvwxyz Input 10 tourist petr wjmzbmr yeputons vepifanov scottwu oooooooooooooooo subscriber rowdark tankengineer Output Impossible Input 10 petr egor endagorion feferivan ilovetanyaromanova kostka dmitriyh maratsnowbear bredorjaguarturnik cgyforever Output aghjlnopefikdmbcqrstuvwxyz Input 7 car care careful carefully becarefuldontforgetsomething otherwiseyouwillbehacked goodluck Output acbdefhijklmnogpqrstuvwxyz Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ### Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto (2n-1) rows, where n is parameter. * Note:`Returning` the pattern is not the same as `Printing` the pattern. #### Parameters: pattern( n ); ^ | Term upto which Basic Pattern(this) should be created #### Rules/Note: * If `n < 1` then it should return "" i.e. empty string. * `The length of each line is same`, and is equal to the length of longest line in the pattern i.e (2n-1). * Range of Parameters (for the sake of CW Compiler) : + `n ∈ (-∞,100]` ### Examples: * pattern(5): 1 1 2 2 3 3 4 4 5 4 4 3 3 2 2 1 1 * pattern(10): 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 0 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 * pattern(15): 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 0 0 1 1 2 2 3 3 4 4 5 4 4 3 3 2 2 1 1 0 0 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 [List of all my katas]("http://www.codewars.com/users/curious_db97/authored") Write your solution by modifying this code: ```python def pattern(n): ``` Your solution should implemented in the function "pattern". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this polyline may consist of. -----Input----- Each of the three lines of the input contains two integers. The i-th line contains integers x_{i} and y_{i} ( - 10^9 ≤ x_{i}, y_{i} ≤ 10^9) — the coordinates of the i-th point. It is guaranteed that all points are distinct. -----Output----- Print a single number — the minimum possible number of segments of the polyline. -----Examples----- Input 1 -1 1 1 1 2 Output 1 Input -1 -1 -1 3 4 3 Output 2 Input 1 1 2 3 3 2 Output 3 -----Note----- The variant of the polyline in the first sample: [Image] The variant of the polyline in the second sample: $1$ The variant of the polyline in the third sample: $\because$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Introduction Fish are an integral part of any ecosystem. Unfortunately, fish are often seen as high maintenance. Contrary to popular belief, fish actually reduce pond maintenance as they graze on string algae and bottom feed from the pond floor. They also make very enjoyable pets, providing hours of natural entertainment. # Task In this Kata you are fish in a pond that needs to survive by eating other fish. You can only eat fish that are the same size or smaller than yourself. You must create a function called fish that takes a shoal of fish as an input string. From this you must work out how many fish you can eat and ultimately the size you will grow to. # Rules 1.  Your size starts at 1 2.  The shoal string will contain fish integers between 0-9 3.  0 = algae and wont help you feed. 4.  The fish integer represents the size of the fish (1-9). 5.  You can only eat fish the same size or less than yourself. 6.  You can eat the fish in any order you choose to maximize your size. 7   You can and only eat each fish once. 8.  The bigger fish you eat, the faster you grow. A size 2 fish equals two size 1 fish, size 3 fish equals three size 1 fish, and so on. 9.  Your size increments by one each time you reach the amounts below. # Increase your size Your size will increase depending how many fish you eat and on the size of the fish. This chart shows the amount of size 1 fish you have to eat in order to increase your size. Current size Amount extra needed for next size Total size 1 fish Increase to size 1 4 4 2 2 8 12 3 3 12 24 4 4 16 40 5 5 20 60 6 6 24 84 7   Please note: The chart represents fish of size 1 # Returns Return an integer of the maximum size you could be. # Example 1 You eat the 4 fish of size 1 (4 * 1 = 4) which increases your size to 2 Now that you are size 2 you can eat the fish that are sized 1 or 2. You then eat the 4 fish of size 2 (4 * 2 = 8) which increases your size to 3 ```python fish("11112222") => 3 ``` # Example 2 You eat the 4 fish of size 1 (4 * 1 = 4) which increases your size to 2 You then eat the remainding 8 fish of size 1 (8 * 1 = 8) which increases your size to 3 ```python fish("111111111111") => 3 ``` Good luck and enjoy! # Kata Series If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.  Maze Runner  Scooby Doo Puzzle  Driving License  Connect 4  Vending Machine  Snakes and Ladders  Mastermind  Guess Who?  Am I safe to drive?  Mexican Wave  Pigs in a Pen  Hungry Hippos  Plenty of Fish in the Pond  Fruit Machine  Car Park Escape Write your solution by modifying this code: ```python def fish(shoal): ``` Your solution should implemented in the function "fish". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Gigi is a clever monkey, living in the zoo, his teacher (animal keeper) recently taught him some knowledge of "0". In Gigi's eyes, "0" is a character contains some circle(maybe one, maybe two). So, a is a "0",b is a "0",6 is also a "0",and 8 have two "0" ,etc... Now, write some code to count how many "0"s in the text. Let us see who is smarter? You ? or monkey? Input always be a string(including words numbers and symbols),You don't need to verify it, but pay attention to the difference between uppercase and lowercase letters. Here is a table of characters: one zeroabdegopq069DOPQR         () <-- A pair of braces as a zerotwo zero%&B8 Output will be a number of "0". Write your solution by modifying this code: ```python def countzero(string): ``` Your solution should implemented in the function "countzero". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Create a function that will return true if all numbers in the sequence follow the same counting pattern. If the sequence of numbers does not follow the same pattern, the function should return false. Sequences will be presented in an array of varied length. Each array will have a minimum of 3 numbers in it. The sequences are all simple and will not step up in varying increments such as a Fibonacci sequence. JavaScript examples: Write your solution by modifying this code: ```python def validate_sequence(sequence): ``` Your solution should implemented in the function "validate_sequence". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Wherever the destination is, whoever we meet, let's render this song together. On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage. On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups: * Vertical: stands at (xi, 0), moves in positive y direction (upwards); * Horizontal: stands at (0, yi), moves in positive x direction (rightwards). <image> According to choreography, the i-th dancer should stand still for the first ti milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time. When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on. <image> Dancers stop when a border of the stage is reached. Find out every dancer's stopping position. Input The first line of input contains three space-separated positive integers n, w and h (1 ≤ n ≤ 100 000, 2 ≤ w, h ≤ 100 000) — the number of dancers and the width and height of the stage, respectively. The following n lines each describes a dancer: the i-th among them contains three space-separated integers gi, pi, and ti (1 ≤ gi ≤ 2, 1 ≤ pi ≤ 99 999, 0 ≤ ti ≤ 100 000), describing a dancer's group gi (gi = 1 — vertical, gi = 2 — horizontal), position, and waiting time. If gi = 1 then pi = xi; otherwise pi = yi. It's guaranteed that 1 ≤ xi ≤ w - 1 and 1 ≤ yi ≤ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time. Output Output n lines, the i-th of which contains two space-separated integers (xi, yi) — the stopping position of the i-th dancer in the input. Examples Input 8 10 8 1 1 10 1 4 13 1 7 1 1 8 2 2 2 0 2 5 14 2 6 0 2 6 1 Output 4 8 10 5 8 8 10 6 10 2 1 8 7 8 10 6 Input 3 2 3 1 1 2 2 1 1 1 1 5 Output 1 3 2 1 1 3 Note The first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure. <image> In the second example, no dancers collide. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. XXI Berland Annual Fair is coming really soon! Traditionally fair consists of $n$ booths, arranged in a circle. The booths are numbered $1$ through $n$ clockwise with $n$ being adjacent to $1$. The $i$-th booths sells some candies for the price of $a_i$ burles per item. Each booth has an unlimited supply of candies. Polycarp has decided to spend at most $T$ burles at the fair. However, he has some plan in mind for his path across the booths: at first, he visits booth number $1$; if he has enough burles to buy exactly one candy from the current booth, then he buys it immediately; then he proceeds to the next booth in the clockwise order (regardless of if he bought a candy or not). Polycarp's money is finite, thus the process will end once he can no longer buy candy at any booth. Calculate the number of candies Polycarp will buy. -----Input----- The first line contains two integers $n$ and $T$ ($1 \le n \le 2 \cdot 10^5$, $1 \le T \le 10^{18}$) — the number of booths at the fair and the initial amount of burles Polycarp has. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the price of the single candy at booth number $i$. -----Output----- Print a single integer — the total number of candies Polycarp will buy. -----Examples----- Input 3 38 5 2 5 Output 10 Input 5 21 2 4 100 2 6 Output 6 -----Note----- Let's consider the first example. Here are Polycarp's moves until he runs out of money: Booth $1$, buys candy for $5$, $T = 33$; Booth $2$, buys candy for $2$, $T = 31$; Booth $3$, buys candy for $5$, $T = 26$; Booth $1$, buys candy for $5$, $T = 21$; Booth $2$, buys candy for $2$, $T = 19$; Booth $3$, buys candy for $5$, $T = 14$; Booth $1$, buys candy for $5$, $T = 9$; Booth $2$, buys candy for $2$, $T = 7$; Booth $3$, buys candy for $5$, $T = 2$; Booth $1$, buys no candy, not enough money; Booth $2$, buys candy for $2$, $T = 0$. No candy can be bought later. The total number of candies bought is $10$. In the second example he has $1$ burle left at the end of his path, no candy can be bought with this amount. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Frog Gorf is traveling through Swamp kingdom. Unfortunately, after a poor jump, he fell into a well of $n$ meters depth. Now Gorf is on the bottom of the well and has a long way up. The surface of the well's walls vary in quality: somewhere they are slippery, but somewhere have convenient ledges. In other words, if Gorf is on $x$ meters below ground level, then in one jump he can go up on any integer distance from $0$ to $a_x$ meters inclusive. (Note that Gorf can't jump down, only up). Unfortunately, Gorf has to take a break after each jump (including jump on $0$ meters). And after jumping up to position $x$ meters below ground level, he'll slip exactly $b_x$ meters down while resting. Calculate the minimum number of jumps Gorf needs to reach ground level. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 300000$) — the depth of the well. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le i$), where $a_i$ is the maximum height Gorf can jump from $i$ meters below ground level. The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($0 \le b_i \le n - i$), where $b_i$ is the distance Gorf will slip down if he takes a break on $i$ meters below ground level. -----Output----- If Gorf can't reach ground level, print $-1$. Otherwise, firstly print integer $k$ — the minimum possible number of jumps. Then print the sequence $d_1,\,d_2,\,\ldots,\,d_k$ where $d_j$ is the depth Gorf'll reach after the $j$-th jump, but before he'll slip down during the break. Ground level is equal to $0$. If there are multiple answers, print any of them. -----Examples----- Input 3 0 2 2 1 1 0 Output 2 1 0 Input 2 1 1 1 0 Output -1 Input 10 0 1 2 3 5 5 6 7 8 5 9 8 7 1 5 4 3 2 0 0 Output 3 9 4 0 -----Note----- In the first example, Gorf is on the bottom of the well and jump to the height $1$ meter below ground level. After that he slip down by meter and stays on height $2$ meters below ground level. Now, from here, he can reach ground level in one jump. In the second example, Gorf can jump to one meter below ground level, but will slip down back to the bottom of the well. That's why he can't reach ground level. In the third example, Gorf can reach ground level only from the height $5$ meters below the ground level. And Gorf can reach this height using a series of jumps $10 \Rightarrow 9 \dashrightarrow 9 \Rightarrow 4 \dashrightarrow 5$ where $\Rightarrow$ is the jump and $\dashrightarrow$ is slipping during breaks. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string t_{i} occurs in string s at least k_{i} times or more, he also remembers exactly k_{i} positions where the string t_{i} occurs in string s: these positions are x_{i}, 1, x_{i}, 2, ..., x_{i}, k_{i}. He remembers n such strings t_{i}. You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings t_{i} and string s consist of small English letters only. -----Input----- The first line contains single integer n (1 ≤ n ≤ 10^5) — the number of strings Ivan remembers. The next n lines contain information about the strings. The i-th of these lines contains non-empty string t_{i}, then positive integer k_{i}, which equal to the number of times the string t_{i} occurs in string s, and then k_{i} distinct positive integers x_{i}, 1, x_{i}, 2, ..., x_{i}, k_{i} in increasing order — positions, in which occurrences of the string t_{i} in the string s start. It is guaranteed that the sum of lengths of strings t_{i} doesn't exceed 10^6, 1 ≤ x_{i}, j ≤ 10^6, 1 ≤ k_{i} ≤ 10^6, and the sum of all k_{i} doesn't exceed 10^6. The strings t_{i} can coincide. It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists. -----Output----- Print lexicographically minimal string that fits all the information Ivan remembers. -----Examples----- Input 3 a 4 1 3 5 7 ab 2 1 5 ca 1 4 Output abacaba Input 1 a 1 3 Output aaa Input 3 ab 1 1 aba 1 3 ab 2 3 5 Output 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. Write a program which reads $n$ dices constructed in the same way as Dice I, and determines whether they are all different. For the determination, use the same way as Dice III. Constraints * $2 \leq n \leq 100$ * $0 \leq $ the integer assigned to a face $ \leq 100$ Input In the first line, the number of dices $n$ is given. In the following $n$ lines, six integers assigned to the dice faces are given respectively in the same way as Dice III. Output Print "Yes" if given dices are all different, otherwise "No" in a line. Examples Input 3 1 2 3 4 5 6 6 2 4 3 5 1 6 5 4 3 2 1 Output No Input 3 1 2 3 4 5 6 6 5 4 3 2 1 5 4 3 2 1 6 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. Polycarp was given an array of $a[1 \dots n]$ of $n$ integers. He can perform the following operation with the array $a$ no more than $n$ times: Polycarp selects the index $i$ and adds the value $a_i$ to one of his choice of its neighbors. More formally, Polycarp adds the value of $a_i$ to $a_{i-1}$ or to $a_{i+1}$ (if such a neighbor does not exist, then it is impossible to add to it). After adding it, Polycarp removes the $i$-th element from the $a$ array. During this step the length of $a$ is decreased by $1$. The two items above together denote one single operation. For example, if Polycarp has an array $a = [3, 1, 6, 6, 2]$, then it can perform the following sequence of operations with it: Polycarp selects $i = 2$ and adds the value $a_i$ to $(i-1)$-th element: $a = [4, 6, 6, 2]$. Polycarp selects $i = 1$ and adds the value $a_i$ to $(i+1)$-th element: $a = [10, 6, 2]$. Polycarp selects $i = 3$ and adds the value $a_i$ to $(i-1)$-th element: $a = [10, 8]$. Polycarp selects $i = 2$ and adds the value $a_i$ to $(i-1)$-th element: $a = [18]$. Note that Polycarp could stop performing operations at any time. Polycarp wondered how many minimum operations he would need to perform to make all the elements of $a$ equal (i.e., he wants all $a_i$ are equal to each other). -----Input----- The first line contains a single integer $t$ ($1 \leq t \leq 3000$) — the number of test cases in the test. Then $t$ test cases follow. The first line of each test case contains a single integer $n$ ($1 \leq n \leq 3000$) — the length of the array. The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^5$) — array $a$. It is guaranteed that the sum of $n$ over all test cases does not exceed $3000$. -----Output----- For each test case, output a single number — the minimum number of operations that Polycarp needs to perform so that all elements of the $a$ array are the same (equal). -----Examples----- Input 4 5 3 1 6 6 2 4 1 2 2 1 3 2 2 2 4 6 3 2 1 Output 4 2 0 2 -----Note----- In the first test case of the example, the answer can be constructed like this (just one way among many other ways): $[3, 1, 6, 6, 2]$ $\xrightarrow[]{i=4,~add~to~left}$ $[3, 1, 12, 2]$ $\xrightarrow[]{i=2,~add~to~right}$ $[3, 13, 2]$ $\xrightarrow[]{i=1,~add~to~right}$ $[16, 2]$ $\xrightarrow[]{i=2,~add~to~left}$ $[18]$. All elements of the array $[18]$ are the same. In the second test case of the example, the answer can be constructed like this (just one way among other ways): $[1, 2, 2, 1]$ $\xrightarrow[]{i=1,~add~to~right}$ $[3, 2, 1]$ $\xrightarrow[]{i=3,~add~to~left}$ $[3, 3]$. All elements of the array $[3, 3]$ are the same. In the third test case of the example, Polycarp doesn't need to perform any operations since $[2, 2, 2]$ contains equal (same) elements only. In the fourth test case of the example, the answer can be constructed like this (just one way among other ways): $[6, 3, 2, 1]$ $\xrightarrow[]{i=3,~add~to~right}$ $[6, 3, 3]$ $\xrightarrow[]{i=3,~add~to~left}$ $[6, 6]$. All elements of the array $[6, 6]$ are the same. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm! Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen. The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac. Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations. Input The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000). After that, there are two strings s and t, consisting of n lowercase Latin letters each. Output If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1. Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied. Examples Input 6 abacbb babcba Output 4 6 3 2 3 Input 3 aba bba 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. Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too. An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex. The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant. Input The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once. Output If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index. Examples Input 3 1 2 2 3 3 Output 1 2 3 2 1 Input 6 1 2 1 3 2 4 4 5 4 6 5 6 3 Output 1 2 4 5 4 6 4 2 1 3 1 Input 6 1 2 1 3 2 4 4 5 4 6 5 3 6 Output -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem. Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other. A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself. -----Input----- The first line contains string a, and the second line — string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 10^5 characters. -----Output----- If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b. -----Examples----- Input abcd defgh Output 5 Input a a Output -1 -----Note----- In the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The [Chinese zodiac](https://en.wikipedia.org/wiki/Chinese_zodiac) is a repeating cycle of 12 years, with each year being represented by an animal and its reputed attributes. The lunar calendar is divided into cycles of 60 years each, and each year has a combination of an animal and an element. There are 12 animals and 5 elements; the animals change each year, and the elements change every 2 years. The current cycle was initiated in the year of 1984 which was the year of the Wood Rat. Since the current calendar is Gregorian, I will only be using years from the epoch 1924. *For simplicity I am counting the year as a whole year and not from January/February to the end of the year.* ##Task Given a year, return the element and animal that year represents ("Element Animal"). For example I'm born in 1998 so I'm an "Earth Tiger". ```animals``` (or ```$animals``` in Ruby) is a preloaded array containing the animals in order: ```['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']``` ```elements``` (or ```$elements``` in Ruby) is a preloaded array containing the elements in order: ```['Wood', 'Fire', 'Earth', 'Metal', 'Water']``` Tell me your zodiac sign and element in the comments. Happy coding :) Write your solution by modifying this code: ```python def chinese_zodiac(year): ``` Your solution should implemented in the function "chinese_zodiac". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Taro is addicted to a novel. The novel has n volumes in total, and each volume has a different thickness. Taro likes this novel so much that he wants to buy a bookshelf dedicated to it. However, if you put a large bookshelf in the room, it will be quite small, so you have to devise to make the width of the bookshelf as small as possible. When I measured the height from the floor to the ceiling, I found that an m-level bookshelf could be placed. So, how can we divide the n volumes of novels to minimize the width of the bookshelf in m columns? Taro is particular about it, and the novels to be stored in each column must be arranged in the order of the volume numbers. .. Enter the number of bookshelves, the number of volumes of the novel, and the thickness of each book as input, and create a program to find the width of the bookshelf that has the smallest width that can accommodate all volumes in order from one volume. However, the size of the bookshelf frame is not included in the width. <image> Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: m n w1 w2 :: wn The first line gives m (1 ≤ m ≤ 20) the number of bookshelves that can be placed in the room and n (1 ≤ n ≤ 100) the number of volumes in the novel. The next n lines are given the integer wi (1 ≤ wi ≤ 1000000), which represents the thickness of the book in Volume i. However, the width of the bookshelf shall not exceed 1500000. The number of datasets does not exceed 50. Output Outputs the minimum bookshelf width for each dataset on one line. Example Input 3 9 500 300 800 200 100 600 900 700 400 4 3 1000 1000 1000 0 0 Output 1800 1000 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself. Here is an example of a max-heap. <image> Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code. $maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap. 1 maxHeapify(A, i) 2 l = left(i) 3 r = right(i) 4 // select the node which has the maximum value 5 if l ≤ H and A[l] > A[i] 6 largest = l 7 else 8 largest = i 9 if r ≤ H and A[r] > A[largest] 10 largest = r 11 12 if largest ≠ i // value of children is larger than that of i 13 swap A[i] and A[largest] 14 maxHeapify(A, largest) // call recursively The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner. 1 buildMaxHeap(A) 2 for i = H/2 downto 1 3 maxHeapify(A, i) Input In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$). Output Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value. Example Input 10 4 1 3 2 16 9 10 14 8 7 Output 16 14 10 8 7 9 3 2 4 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The store sells $n$ beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them. A necklace is a set of beads connected in a circle. For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemble the following necklaces (these are not all possible options): [Image] And the following necklaces cannot be assembled from beads sold in the store: [Image] The first necklace cannot be assembled because it has three beads "a" (of the two available). The second necklace cannot be assembled because it contains a bead "d", which is not sold in the store. We call a necklace $k$-beautiful if, when it is turned clockwise by $k$ beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace. [Image] As you can see, this necklace is, for example, $3$-beautiful, $6$-beautiful, $9$-beautiful, and so on, but it is not $1$-beautiful or $2$-beautiful. In particular, a necklace of length $1$ is $k$-beautiful for any integer $k$. A necklace that consists of beads of the same color is also beautiful for any $k$. You are given the integers $n$ and $k$, and also the string $s$ containing $n$ lowercase letters of the English alphabet — each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a $k$-beautiful necklace you can assemble. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases in the test. Then $t$ test cases follow. The first line of each test case contains two integers $n$ and $k$ ($1 \le n, k \le 2000$). The second line of each test case contains the string $s$ containing $n$ lowercase English letters — the beads in the store. It is guaranteed that the sum of $n$ for all test cases does not exceed $2000$. -----Output----- Output $t$ answers to the test cases. Each answer is a positive integer — the maximum length of the $k$-beautiful necklace you can assemble. -----Example----- Input 6 6 3 abcbac 3 6 aaa 7 1000 abczgyo 5 4 ababa 20 10 aaebdbabdbbddaadaadc 20 5 ecbedececacbcbccbdec Output 6 3 5 4 15 10 -----Note----- The first test case is explained in the statement. In the second test case, a $6$-beautiful necklace can be assembled from all the letters. In the third test case, a $1000$-beautiful necklace can be assembled, for example, from beads "abzyo". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task: This kata asks you to make a custom esolang interpreter for the language [MiniBitMove](https://esolangs.org/wiki/MiniBitMove). MiniBitMove has only two commands and operates on a array of bits. It works like this: - `1`: Flip the bit at the current cell - `0`: Move selector by 1 It takes two inputs, the program and the bits in needs to operate on. The program returns the modified bits. The program stops when selector reaches the end of the array. Otherwise the program repeats itself. **Note: This means that if a program does not have any zeros it is an infinite loop** Example of a program that flips all bits in an array: ``` Code: 10 Bits: 11001001001010 Result: 00110110110101 ``` After you're done, feel free to make translations and discuss this kata. Write your solution by modifying this code: ```python def interpreter(tape, array): ``` Your solution should implemented in the function "interpreter". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it. Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same? -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of participants Anton has outscored in this contest . The next n lines describe participants results: the i-th of them consists of a participant handle name_{i} and two integers before_{i} and after_{i} ( - 4000 ≤ before_{i}, after_{i} ≤ 4000) — participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters «_» and «-» characters. It is guaranteed that all handles are distinct. -----Output----- Print «YES» (quotes for clarity), if Anton has performed good in the contest and «NO» (quotes for clarity) otherwise. -----Examples----- Input 3 Burunduk1 2526 2537 BudAlNik 2084 2214 subscriber 2833 2749 Output YES Input 3 Applejack 2400 2400 Fluttershy 2390 2431 Pinkie_Pie -2500 -2450 Output NO -----Note----- In the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest. In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. Input The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters. Output Print the given string after it is processed. It is guaranteed that the result will contain at least one character. Examples Input hhoowaaaareyyoouu Output wre Input reallazy Output rezy Input abacabaabacabaa Output a Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn. Input The first line contains two space-separated integers n and m (1 ≤ m ≤ n ≤ 100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai ( - 1000 ≤ ai ≤ 1000) — prices of the TV sets. Output Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most m TV sets. Examples Input 5 3 -6 0 35 -2 4 Output 8 Input 4 2 7 0 0 -7 Output 7 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself. The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move. Input The first line contains the only integer q (1 ≤ q ≤ 1013). Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator. Output In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer — his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them. Examples Input 6 Output 2 Input 30 Output 1 6 Input 1 Output 1 0 Note Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 creating the following number pattern. 4 8 2 3 1 0 8 3 7 6 2 0 5 4 1 8 1 0 3 2 5 9 5 9 9 1 3 7 4 4 4 8 0 4 1 8 8 2 8 4 9 6 0 0 2 5 6 0 2 1 6 2 7 8 Five This pattern follows the rules below. A B C In the sequence of numbers, C is the ones digit of A + B. For example 9 5 Four Now, the ones digit of 9 + 5 = 14, or 4 is placed diagonally below 9 and 5. Also, twenty three Five Now, the ones digit of 2 + 3 = 5, that is, 5 is placed diagonally below 2 and 3. Write a program that reads the 10 integers in the top line and outputs one number in the bottom line. Input The input consists of multiple datasets. For each dataset, the top 10 numbers are given as strings on one line. The number of datasets does not exceed 20. Output Outputs the numbers in the bottom line to one line for each dataset. Example Input 4823108376 1234567890 0123456789 Output 5 6 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 is a directed graph with N vertices numbered 1 to N and M edges. The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge. Additionally, there is a button on Vertex N. We will play a game on this graph. You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins. It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it. As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again. When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.) However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead. Your score will be the number of coins you have after this payment. Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value. -----Constraints----- - 2 \leq N \leq 2500 - 1 \leq M \leq 5000 - 1 \leq A_i, B_i \leq N - 1 \leq C_i \leq 10^5 - 0 \leq P \leq 10^5 - All values in input are integers. - Vertex N can be reached from Vertex 1. -----Input----- Input is given from Standard Input in the following format: N M P A_1 B_1 C_1 : A_M B_M C_M -----Output----- If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1. -----Sample Input----- 3 3 10 1 2 20 2 3 30 1 3 45 -----Sample Output----- 35 There are two ways to travel from Vertex 1 to Vertex 3: - Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left. - Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left. Thus, the maximum score that can be obtained is 35. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task The sequence of `Chando` is an infinite sequence of all Chando's numbers in ascending order. A number is called `Chando's` if it is an integer that can be represented as a sum of different positive integer powers of 5. The first Chando's numbers is 5 (5^1). And the following nth Chando's numbers are: ``` 25 (5^2) 30 (5^1 + 5^2) 125 (5^3) 130 (5^1 + 5^3) 150 (5^2 + 5^3) ... ... ``` Your task is to find the Chando's nth number for a given `n`. # Input/Output - `[input]` integer `n` `1 <= n <= 7000` - `[output]` an integer nth Chando's number Write your solution by modifying this code: ```python def nth_chandos_number(n): ``` Your solution should implemented in the function "nth_chandos_number". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. For given two segments s1 and s2, print the distance between them. s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3. Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xpi, ypi ≤ 10000 * p0 ≠ p1 and p2 ≠ p3. Input The entire input looks like: q (the number of queries) 1st query 2nd query ... qth query Each query consists of integer coordinates of end points of s1 and s2 in the following format: xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3 Output For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001. Example Input 3 0 0 1 0 0 1 1 1 0 0 1 0 2 1 1 2 -1 0 1 0 0 1 0 -1 Output 1.0000000000 1.4142135624 0.0000000000 Read the inputs from stdin solve the problem and write the answer to stdout (do 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, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (`HH:MM:SS`) * `HH` = hours, padded to 2 digits, range: 00 - 99 * `MM` = minutes, padded to 2 digits, range: 00 - 59 * `SS` = seconds, padded to 2 digits, range: 00 - 59 The maximum time never exceeds 359999 (`99:59:59`) You can find some examples in the test fixtures. Write your solution by modifying this code: ```python def make_readable(seconds): ``` Your solution should implemented in the function "make_readable". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Taro is playing with a puzzle that places numbers 1-9 in 9x9 squares. In this puzzle, you have to arrange the numbers according to the following rules. * One number appears exactly once in the same column * A number appears exactly once on the same line * In each of the 3x3 ranges separated by double lines, a number appears exactly once. For example, Figure 1 below is one arrangement that meets such a rule. However, Taro often creates an arrangement that violates the rules, as shown in Figure 2. The "2" appears twice in the leftmost column, the "1" never appears, the "1" appears twice in the second column from the left, and the "2" never appears. .. <image> | <image> --- | --- Figure 1 | Figure 2 To help Taro, write a program that reads the arrangement of numbers, checks if the arrangement meets the rules, and outputs the location if it violates the rules. Please display * (half-width asterisk) before the number that is incorrect (appears more than once) according to the three rules, and blank before the number that is not incorrect. Input Given multiple datasets. The first row gives the number of datasets n (n ≤ 20). Each dataset is given a 9-character, 9-line numeric string that indicates the state of the puzzle. Output Output the following for each dataset. Given number, * (half-width asterisk) and blank. Add * before the wrong number and a half-width space before the wrong number. Insert a blank line between the datasets. Example Input 2 2 1 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 2 3 4 5 6 7 8 9 1 5 6 7 8 9 1 2 3 4 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 6 7 8 9 1 2 3 4 5 9 1 2 3 4 5 6 7 8 2 1 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 2 3 4 5 6 7 8 9 1 5 6 7 8 9 1 2 3 4 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 6 7 8 9 1 2 3 4 5 9 1 2 3 4 5 6 7 8 Output *2*1 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 *2 3 4 5 6 7 8 9 1 5 6 7 8 9 1 2 3 4 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 6 7 8 9 1 2 3 4 5 9*1 2 3 4 5 6 7 8 *2*1 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 *2 3 4 5 6 7 8 9 1 5 6 7 8 9 1 2 3 4 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 6 7 8 9 1 2 3 4 5 9*1 2 3 4 5 6 7 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. Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used. For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen w_{i} seconds after midnight, all w_{i}'s are distinct. Each visit lasts exactly one second. What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time. -----Input----- The first line contains three integers m, t, r (1 ≤ m, t, r ≤ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit. The next line contains m space-separated numbers w_{i} (1 ≤ i ≤ m, 1 ≤ w_{i} ≤ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All w_{i}'s are distinct, they follow in the strictly increasing order. -----Output----- If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that. If that is impossible, print - 1. -----Examples----- Input 1 8 3 10 Output 3 Input 2 10 1 5 8 Output 1 Input 1 1 3 10 Output -1 -----Note----- Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit. It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively. In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight. In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight. In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 search for Heidi is over – you finally found her at a library, dressed up as a human. In fact, she has spent so much time there that she now runs the place! Her job is to buy books and keep them at the library so that people can borrow and read them. There are n different books, numbered 1 through n. We will look at the library's operation during n consecutive days. Heidi knows in advance that on the i-th day (1 ≤ i ≤ n) precisely one person will come to the library, request to borrow the book a_{i}, read it in a few hours, and return the book later on the same day. Heidi desperately wants to please all her guests, so she will make sure to always have the book a_{i} available in the library on the i-th day. During the night before the i-th day, she has the option of going to the bookstore (which operates at nights to avoid competition with the library) and buying any book for the price of 1 CHF. Of course, if she already has a book at the library, she does not need to buy it again. Initially, the library contains no books. There is a problem, though. The capacity of the library is k – this means that at any time, there can be at most k books at the library. If buying a new book would cause Heidi to have more than k books, she must first get rid of some book that she already has, in order to make room for the new book. If she later needs a book that she got rid of, she will need to buy that book again. You are given k and the sequence of requests for books a_1, a_2, ..., a_{n}. What is the minimum cost (in CHF) of buying new books to satisfy all the requests? -----Input----- The first line of input will contain two integers n and k (1 ≤ n, k ≤ 80). The second line will contain n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) – the sequence of book requests. -----Output----- On a single line print the minimum cost of buying books at the store so as to satisfy all requests. -----Examples----- Input 4 80 1 2 2 1 Output 2 Input 4 1 1 2 2 1 Output 3 Input 4 2 1 2 3 1 Output 3 -----Note----- In the first test case, Heidi is able to keep all books forever. Therefore, she only needs to buy the book 1 before the first day and the book 2 before the second day. In the second test case, she can only keep one book at a time. Therefore she will need to buy new books on the first, second and fourth day. In the third test case, before buying book 3 on the third day, she must decide which of the books 1 and 2 she should get rid of. Of course, she should keep the book 1, which will be requested on the fourth day. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 robot is placed in the top left corner of a grid, consisting of $n$ rows and $m$ columns, in a cell $(1, 1)$. In one step, it can move into a cell, adjacent by a side to the current one: $(x, y) \rightarrow (x, y + 1)$; $(x, y) \rightarrow (x + 1, y)$; $(x, y) \rightarrow (x, y - 1)$; $(x, y) \rightarrow (x - 1, y)$. The robot can't move outside the grid. The cell $(s_x, s_y)$ contains a deadly laser. If the robot comes into some cell that has distance less than or equal to $d$ to the laser, it gets evaporated. The distance between two cells $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$. Print the smallest number of steps that the robot can take to reach the cell $(n, m)$ without getting evaporated or moving outside the grid. If it's not possible to reach the cell $(n, m)$, print -1. The laser is neither in the starting cell, nor in the ending cell. The starting cell always has distance greater than $d$ to the laser. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases. The only line of each testcase contains five integers $n, m, s_x, s_y, d$ ($2 \le n, m \le 1000$; $1 \le s_x \le n$; $1 \le s_y \le m$; $0 \le d \le n + m$) — the size of the grid, the cell that contains the laser and the evaporating distance of the laser. The laser is neither in the starting cell, nor in the ending cell ($(s_x, s_y) \neq (1, 1)$ and $(s_x, s_y) \neq (n, m)$). The starting cell $(1, 1)$ always has distance greater than $d$ to the laser ($|s_x - 1| + |s_y - 1| > d$). -----Output----- For each testcase, print a single integer. If it's possible to reach the cell $(n, m)$ from $(1, 1)$ without getting evaporated or moving outside the grid, then print the smallest amount of steps it can take the robot to reach it. Otherwise, print -1. -----Examples----- Input 3 2 3 1 3 0 2 3 1 3 1 5 5 3 4 1 Output 3 -1 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. You are given two strings s and t consisting of small Latin letters, string s can also contain '?' characters. Suitability of string s is calculated by following metric: Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings s, you choose the one with the largest number of non-intersecting occurrences of string t. Suitability is this number of occurrences. You should replace all '?' characters with small Latin letters in such a way that the suitability of string s is maximal. -----Input----- The first line contains string s (1 ≤ |s| ≤ 10^6). The second line contains string t (1 ≤ |t| ≤ 10^6). -----Output----- Print string s with '?' replaced with small Latin letters in such a way that suitability of that string is maximal. If there are multiple strings with maximal suitability then print any of them. -----Examples----- Input ?aa? ab Output baab Input ??b? za Output azbz Input abcd abacaba Output abcd -----Note----- In the first example string "baab" can be transformed to "abab" with swaps, this one has suitability of 2. That means that string "baab" also has suitability of 2. In the second example maximal suitability you can achieve is 1 and there are several dozens of such strings, "azbz" is just one of them. In the third example there are no '?' characters and the suitability of the string 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. Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class. Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each student’s laziness level is equal to their task’s difficulty level. Both sets of values are given by the sequence a, where a_{i} represents both the laziness level of the i-th student and the difficulty of his task. The time a student needs to finish a task is equal to the product of their laziness level and the task’s difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007. -----Input----- The first line of input contains integer n (1 ≤ n ≤ 100 000) — the number of tasks. The next n lines contain exactly one integer number a_{i} (1 ≤ a_{i} ≤ 100 000) — both the difficulty of the initial task and the laziness of the i-th students. -----Output----- Print the minimum total time to finish all tasks modulo 10 007. -----Example----- Input 2 1 3 Output 6 -----Note----- In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has n cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from 1 to n from the left to the right. Unfortunately, Joe didn't switch the last security system off. On the plus side, he knows the way it works. Every minute the security system calculates the total amount of diamonds for each two adjacent cells (for the cells between whose numbers difference equals 1). As a result of this check we get an n - 1 sums. If at least one of the sums differs from the corresponding sum received during the previous check, then the security system is triggered. Joe can move the diamonds from one cell to another between the security system's checks. He manages to move them no more than m times between two checks. One of the three following operations is regarded as moving a diamond: moving a diamond from any cell to any other one, moving a diamond from any cell to Joe's pocket, moving a diamond from Joe's pocket to any cell. Initially Joe's pocket is empty, and it can carry an unlimited amount of diamonds. It is considered that before all Joe's actions the system performs at least one check. In the morning the bank employees will come, which is why Joe has to leave the bank before that moment. Joe has only k minutes left before morning, and on each of these k minutes he can perform no more than m operations. All that remains in Joe's pocket, is considered his loot. Calculate the largest amount of diamonds Joe can carry with him. Don't forget that the security system shouldn't be triggered (even after Joe leaves the bank) and Joe should leave before morning. Input The first line contains integers n, m and k (1 ≤ n ≤ 104, 1 ≤ m, k ≤ 109). The next line contains n numbers. The i-th number is equal to the amount of diamonds in the i-th cell — it is an integer from 0 to 105. Output Print a single number — the maximum number of diamonds Joe can steal. Examples Input 2 3 1 2 3 Output 0 Input 3 2 2 4 1 3 Output 2 Note In the second sample Joe can act like this: The diamonds' initial positions are 4 1 3. During the first period of time Joe moves a diamond from the 1-th cell to the 2-th one and a diamond from the 3-th cell to his pocket. By the end of the first period the diamonds' positions are 3 2 2. The check finds no difference and the security system doesn't go off. During the second period Joe moves a diamond from the 3-rd cell to the 2-nd one and puts a diamond from the 1-st cell to his pocket. By the end of the second period the diamonds' positions are 2 3 1. The check finds no difference again and the security system doesn't go off. Now Joe leaves with 2 diamonds in his pocket. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 ```convert_temp(temp, from_scale, to_scale)``` converting temperature from one scale to another. Return converted temp value. Round converted temp value to an integer(!). Reading: http://en.wikipedia.org/wiki/Conversion_of_units_of_temperature ``` possible scale inputs: "C" for Celsius "F" for Fahrenheit "K" for Kelvin "R" for Rankine "De" for Delisle "N" for Newton "Re" for Réaumur "Ro" for Rømer ``` ```temp``` is a number, ```from_scale``` and ```to_scale``` are strings. ```python convert_temp( 100, "C", "F") # => 212 convert_temp( 40, "Re", "C") # => 50 convert_temp( 60, "De", "F") # => 140 convert_temp(373.15, "K", "N") # => 33 convert_temp( 666, "K", "K") # => 666 ``` Write your solution by modifying this code: ```python def convert_temp(temp, from_scale, to_scale): ``` Your solution should implemented in the function "convert_temp". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Metropolis computer network consists of n servers, each has an encryption key in the range from 0 to 2^k - 1 assigned to it. Let c_i be the encryption key assigned to the i-th server. Additionally, m pairs of servers are directly connected via a data communication channel. Because of the encryption algorithms specifics, a data communication channel can only be considered safe if the two servers it connects have distinct encryption keys. The initial assignment of encryption keys is guaranteed to keep all data communication channels safe. You have been informed that a new virus is actively spreading across the internet, and it is capable to change the encryption key of any server it infects. More specifically, the virus body contains some unknown number x in the same aforementioned range, and when server i is infected, its encryption key changes from c_i to c_i ⊕ x, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Sadly, you know neither the number x nor which servers of Metropolis are going to be infected by the dangerous virus, so you have decided to count the number of such situations in which all data communication channels remain safe. Formally speaking, you need to find the number of pairs (A, x), where A is some (possibly empty) subset of the set of servers and x is some number in the range from 0 to 2^k - 1, such that when all servers from the chosen subset A and none of the others are infected by a virus containing the number x, all data communication channels remain safe. Since this number can be quite big, you are asked to find its remainder modulo 10^9 + 7. Input The first line of input contains three integers n, m and k (1 ≤ n ≤ 500 000, 0 ≤ m ≤ min((n(n - 1))/(2), 500 000), 0 ≤ k ≤ 60) — the number of servers, the number of pairs of servers directly connected by a data communication channel, and the parameter k, which defines the range of possible values for encryption keys. The next line contains n integers c_i (0 ≤ c_i ≤ 2^k - 1), the i-th of which is the encryption key used by the i-th server. The next m lines contain two integers u_i and v_i each (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) denoting that those servers are connected by a data communication channel. It is guaranteed that each pair of servers appears in this list at most once. Output The only output line should contain a single integer — the number of safe infections of some subset of servers by a virus with some parameter, modulo 10^9 + 7. Examples Input 4 4 2 0 1 0 1 1 2 2 3 3 4 4 1 Output 50 Input 4 5 3 7 1 7 2 1 2 2 3 3 4 4 1 2 4 Output 96 Note Consider the first example. Possible values for the number x contained by the virus are 0, 1, 2 and 3. For values 0, 2 and 3 the virus can infect any subset of the set of servers, which gives us 16 pairs for each values. A virus containing the number 1 can infect either all of the servers, or none. This gives us 16 + 2 + 16 + 16 = 50 pairs 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. Unscramble the eggs. The string given to your function has had an "egg" inserted directly after each consonant. You need to return the string before it became eggcoded. ## Example Kata is supposed to be for beginners to practice regular expressions, so commenting would be appreciated. Write your solution by modifying this code: ```python def unscramble_eggs(word): ``` Your solution should implemented in the function "unscramble_eggs". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it. However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to figure out whether the document has malfunctioned. Specifically, he is given a string of length $n$ whose characters are all either T or M, and he wants to figure out if it is possible to partition it into some number of disjoint subsequences, all of which are equal to TMT. That is, each character of the string should belong to exactly one of the subsequences. A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero) characters. -----Input----- The first line contains an integer $t$ ($1 \le t \le 5000$) — the number of test cases. The first line of each test case contains an integer $n$ ($3 \le n < 10^5$), the number of characters in the string entered in the document. It is guaranteed that $n$ is divisible by $3$. The second line of each test case contains a string of length $n$ consisting of only the characters T and M. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case, print a single line containing YES if the described partition exists, and a single line containing NO otherwise. -----Examples----- Input 5 3 TMT 3 MTT 6 TMTMTT 6 TMTTTT 6 TTMMTT Output YES NO YES NO YES -----Note----- In the first test case, the string itself is already a sequence equal to TMT. In the third test case, we may partition the string into the subsequences TMTMTT. Both the bolded and the non-bolded subsequences are equal to TMT. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav. Input The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value. Output In a single line print the answer to the problem — the maximum sum that Yaroslav can get. Examples Input 2 50 50 50 Output 150 Input 2 -1 -100 -1 Output 100 Note In the first sample you do not need to change anything. The sum of elements equals 150. In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 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. There are $n$ people who want to participate in a boat competition. The weight of the $i$-th participant is $w_i$. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight. So, if there are $k$ teams $(a_1, b_1)$, $(a_2, b_2)$, $\dots$, $(a_k, b_k)$, where $a_i$ is the weight of the first participant of the $i$-th team and $b_i$ is the weight of the second participant of the $i$-th team, then the condition $a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s$, where $s$ is the total weight of each team, should be satisfied. Your task is to choose such $s$ that the number of teams people can create is the maximum possible. Note that each participant can be in no 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 1000$) — 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 50$) — the number of participants. The second line of the test case contains $n$ integers $w_1, w_2, \dots, w_n$ ($1 \le w_i \le n$), where $w_i$ is the weight of the $i$-th participant. -----Output----- For each test case, print one integer $k$: the maximum number of teams people can compose with the total weight $s$, if you choose $s$ optimally. -----Example----- Input 5 5 1 2 3 4 5 8 6 6 6 6 6 6 8 8 8 1 2 2 1 2 1 1 2 3 1 3 3 6 1 1 3 4 2 2 Output 2 3 4 1 2 -----Note----- In the first test case of the example, we can reach the optimal answer for $s=6$. Then the first boat is used by participants $1$ and $5$ and the second boat is used by participants $2$ and $4$ (indices are the same as weights). In the second test case of the example, we can reach the optimal answer for $s=12$. Then first $6$ participants can form $3$ pairs. In the third test case of the example, we can reach the optimal answer for $s=3$. The answer is $4$ because we have $4$ participants with weight $1$ and $4$ participants with weight $2$. In the fourth test case of the example, we can reach the optimal answer for $s=4$ or $s=6$. In the fifth test case of the example, we can reach the optimal answer for $s=3$. Note that participant with weight $3$ can't use the boat because there is no suitable pair for him in the list. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Alice has a string $s$. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not. Alice can erase some characters from her string $s$. She would like to know what is the longest string remaining after erasing some characters (possibly zero) to get a good string. It is guaranteed that the string has at least one "a" in it, so the answer always exists. -----Input----- The first line contains a string $s$ ($1 \leq |s| \leq 50$) consisting of lowercase English letters. It is guaranteed that there is at least one "a" in $s$. -----Output----- Print a single integer, the length of the longest good string that Alice can get after erasing some characters from $s$. -----Examples----- Input xaxxxxa Output 3 Input aaabaa Output 6 -----Note----- In the first example, it's enough to erase any four of the "x"s. The answer is $3$ since that is the maximum number of characters that can remain. In the second example, we don't need to erase any characters. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 their story unravels, a timeless tale is told once again... Shirahime, a friend of Mocha's, is keen on playing the music game Arcaea and sharing Mocha interesting puzzles to solve. This day, Shirahime comes up with a new simple puzzle and wants Mocha to solve them. However, these puzzles are too easy for Mocha to solve, so she wants you to solve them and tell her the answers. The puzzles are described as follow. There are $n$ squares arranged in a row, and each of them can be painted either red or blue. Among these squares, some of them have been painted already, and the others are blank. You can decide which color to paint on each blank square. Some pairs of adjacent squares may have the same color, which is imperfect. We define the imperfectness as the number of pairs of adjacent squares that share the same color. For example, the imperfectness of "BRRRBBR" is $3$, with "BB" occurred once and "RR" occurred twice. Your goal is to minimize the imperfectness and print out the colors of the squares after painting. -----Input----- Each test contains multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains an integer $n$ ($1\leq n\leq 100$) — the length of the squares row. The second line of each test case contains a string $s$ with length $n$, containing characters 'B', 'R' and '?'. Here 'B' stands for a blue square, 'R' for a red square, and '?' for a blank square. -----Output----- For each test case, print a line with a string only containing 'B' and 'R', the colors of the squares after painting, which imperfectness is minimized. If there are multiple solutions, print any of them. -----Examples----- Input 5 7 ?R???BR 7 ???R??? 1 ? 1 B 10 ?R??RB??B? Output BRRBRBR BRBRBRB B B BRRBRBBRBR -----Note----- In the first test case, if the squares are painted "BRRBRBR", the imperfectness is $1$ (since squares $2$ and $3$ have the same color), which is the minimum possible imperfectness. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Prior to having fancy iPhones, teenagers would wear out their thumbs sending SMS messages on candybar-shaped feature phones with 3x4 numeric keypads. ------- ------- ------- | | | ABC | | DEF | | 1 | | 2 | | 3 | ------- ------- ------- ------- ------- ------- | GHI | | JKL | | MNO | | 4 | | 5 | | 6 | ------- ------- ------- ------- ------- ------- |PQRS | | TUV | | WXYZ| | 7 | | 8 | | 9 | ------- ------- ------- ------- ------- ------- | | |space| | | | * | | 0 | | # | ------- ------- ------- Prior to the development of T9 (predictive text entry) systems, the method to type words was called "multi-tap" and involved pressing a button repeatedly to cycle through the possible values. For example, to type a letter `"R"` you would press the `7` key three times (as the screen display for the current character cycles through `P->Q->R->S->7`). A character is "locked in" once the user presses a different key or pauses for a short period of time (thus, no extra button presses are required beyond what is needed for each letter individually). The zero key handles spaces, with one press of the key producing a space and two presses producing a zero. In order to send the message `"WHERE DO U WANT 2 MEET L8R"` a teen would have to actually do 47 button presses. No wonder they abbreviated. For this assignment, write a module that can calculate the amount of button presses required for any phrase. Punctuation can be ignored for this exercise. Likewise, you can assume the phone doesn't distinguish between upper/lowercase characters (but you should allow your module to accept input in either for convenience). Hint: While it wouldn't take too long to hard code the amount of keypresses for all 26 letters by hand, try to avoid doing so! (Imagine you work at a phone manufacturer who might be testing out different keyboard layouts, and you want to be able to test new ones rapidly.) Write your solution by modifying this code: ```python def presses(phrase): ``` Your solution should implemented in the function "presses". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You want to go on a trip with a friend. However, friends who have a habit of spending money cannot easily save travel expenses. I don't know when my friends will go on a trip if they continue their current lives. So, if you want to travel early, you decide to create a program to help your friends save in a planned manner. If you have a friend's pocket money of M yen and the money you spend in that month is N yen, you will save (M --N) yen in that month. Create a program that inputs the monthly income and expenditure information M and N and outputs the number of months it takes for the savings amount to reach the travel cost L. However, if your savings do not reach your travel expenses after 12 months, print NA. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: L M1 N1 M2 N2 :: M12 N12 The first line gives the travel cost L (1 ≤ L ≤ 1000000, integer). The next 12 lines are given the balance information for the i month, Mi, Ni (0 ≤ Mi, Ni ≤ 100000, Ni ≤ Mi, integer). The number of datasets does not exceed 1000. Output For each input dataset, print the number of months it takes for your savings to reach your travel costs on a single line. Example Input 10000 5000 3150 5000 5000 0 0 5000 1050 5000 3980 5000 210 5000 5000 5000 5000 0 0 5000 2100 5000 2100 5000 2100 29170 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 100000 70831 0 Output 6 NA Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently, Norge found a string $s = s_1 s_2 \ldots s_n$ consisting of $n$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $s$. Yes, all $\frac{n (n + 1)}{2}$ of them! A substring of $s$ is a non-empty string $x = s[a \ldots b] = s_{a} s_{a + 1} \ldots s_{b}$ ($1 \leq a \leq b \leq n$). For example, "auto" and "ton" are substrings of "automaton". Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $k$ Latin letters $c_1, c_2, \ldots, c_k$ out of $26$. After that, Norge became interested in how many substrings of the string $s$ he could still type using his broken keyboard. Help him to find this number. -----Input----- The first line contains two space-separated integers $n$ and $k$ ($1 \leq n \leq 2 \cdot 10^5$, $1 \leq k \leq 26$) — the length of the string $s$ and the number of Latin letters still available on the keyboard. The second line contains the string $s$ consisting of exactly $n$ lowercase Latin letters. The third line contains $k$ space-separated distinct lowercase Latin letters $c_1, c_2, \ldots, c_k$ — the letters still available on the keyboard. -----Output----- Print a single number — the number of substrings of $s$ that can be typed using only available letters $c_1, c_2, \ldots, c_k$. -----Examples----- Input 7 2 abacaba a b Output 12 Input 10 3 sadfaasdda f a d Output 21 Input 7 1 aaaaaaa b Output 0 -----Note----- In the first example Norge can print substrings $s[1\ldots2]$, $s[2\ldots3]$, $s[1\ldots3]$, $s[1\ldots1]$, $s[2\ldots2]$, $s[3\ldots3]$, $s[5\ldots6]$, $s[6\ldots7]$, $s[5\ldots7]$, $s[5\ldots5]$, $s[6\ldots6]$, $s[7\ldots7]$. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 and Grisha like studying sets of positive integers. One day Grisha has written a set A containing n different integers a_{i} on a blackboard. Now he asks Masha to create a set B containing n different integers b_{j} such that all n^2 integers that can be obtained by summing up a_{i} and b_{j} for all possible pairs of i and j are different. Both Masha and Grisha don't like big numbers, so all numbers in A are from 1 to 10^6, and all numbers in B must also be in the same range. Help Masha to create the set B that satisfies Grisha's requirement. -----Input----- Input data contains multiple test cases. The first line contains an integer t — the number of test cases (1 ≤ t ≤ 100). Each test case is described in the following way: the first line of the description contains one integer n — the number of elements in A (1 ≤ n ≤ 100). The second line contains n integers a_{i} — the elements of A (1 ≤ a_{i} ≤ 10^6). -----Output----- For each test first print the answer: NO, if Masha's task is impossible to solve, there is no way to create the required set B. YES, if there is the way to create the required set. In this case the second line must contain n different positive integers b_{j} — elements of B (1 ≤ b_{j} ≤ 10^6). If there are several possible sets, output any of them. -----Example----- Input 3 3 1 10 100 1 1 2 2 4 Output YES 1 2 3 YES 1 YES 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. Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret! A password is an array $a$ of $n$ positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index $i$ such that $1 \leq i < n$ and $a_{i} \neq a_{i+1}$, delete both $a_i$ and $a_{i+1}$ from the array and put $a_{i}+a_{i+1}$ in their place. For example, for array $[7, 4, 3, 7]$ you can choose $i = 2$ and the array will become $[7, 4+3, 7] = [7, 7, 7]$. Note that in this array you can't apply this operation anymore. Notice that one operation will decrease the size of the password by $1$. What is the shortest possible length of the password after some number (possibly $0$) of operations? -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows. The first line of each test case contains an integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the length of the password. The second line of each test case contains $n$ integers $a_{1},a_{2},\dots,a_{n}$ ($1 \leq a_{i} \leq 10^9$) — the initial contents of your password. The sum of $n$ over all test cases will not exceed $2 \cdot 10^5$. -----Output----- For each password, print one integer: the shortest possible length of the password after some number of operations. -----Example----- Input 2 4 2 1 3 1 2 420 420 Output 1 2 -----Note----- In the first test case, you can do the following to achieve a length of $1$: Pick $i=2$ to get $[2, 4, 1]$ Pick $i=1$ to get $[6, 1]$ Pick $i=1$ to get $[7]$ In the second test case, you can't perform any operations because there is no valid $i$ that satisfies the requirements mentioned above. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings! The sequence of round brackets is called valid if and only if: the total number of opening brackets is equal to the total number of closing brackets; for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets. Gabi bought a string s of length m (m ≤ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s. Now he wonders, how many pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 10^9 + 7. -----Input----- First line contains n and m (1 ≤ m ≤ n ≤ 100 000, n - m ≤ 2000) — the desired length of the string and the length of the string bought by Gabi, respectively. The second line contains string s of length m consisting of characters '(' and ')' only. -----Output----- Print the number of pairs of string p and q such that p + s + q is a valid sequence of round brackets modulo 10^9 + 7. -----Examples----- Input 4 1 ( Output 4 Input 4 4 (()) Output 1 Input 4 3 ((( Output 0 -----Note----- In the first sample there are four different valid pairs: p = "(", q = "))" p = "()", q = ")" p = "", q = "())" p = "", q = ")()" In the second sample the only way to obtain a desired string is choose empty p and q. In the third sample there is no way to get a valid sequence of brackets. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar. Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating). Input The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces. Output Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating). Examples Input 5 5 1 2 2 2 3 2 3 4 2 4 5 1 5 Output 0 Input 8 7 0 3 1 2 3 1 1 2 5 4 2 6 7 1 3 2 7 4 1 1 Output 2 Input 2 2 1 2 0 Output 1 Note In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4. In the third sample employee 2 must learn language 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. The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: Operation ++ increases the value of variable x by 1. Operation -- decreases the value of variable x by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains. A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains. You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed). -----Input----- The first line contains a single integer n (1 ≤ n ≤ 150) — the number of statements in the programme. Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order. -----Output----- Print a single integer — the final value of x. -----Examples----- Input 1 ++X Output 1 Input 2 X++ --X Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Problem F Pizza Delivery Alyssa is a college student, living in New Tsukuba City. All the streets in the city are one-way. A new social experiment starting tomorrow is on alternative traffic regulation reversing the one-way directions of street sections. Reversals will be on one single street section between two adjacent intersections for each day; the directions of all the other sections will not change, and the reversal will be canceled on the next day. Alyssa orders a piece of pizza everyday from the same pizzeria. The pizza is delivered along the shortest route from the intersection with the pizzeria to the intersection with Alyssa's house. Altering the traffic regulation may change the shortest route. Please tell Alyssa how the social experiment will affect the pizza delivery route. Input The input consists of a single test case in the following format. $n$ $m$ $a_1$ $b_1$ $c_1$ ... $a_m$ $b_m$ $c_m$ The first line contains two integers, $n$, the number of intersections, and $m$, the number of street sections in New Tsukuba City ($2 \leq n \leq 100 000, 1 \leq m \leq 100 000$). The intersections are numbered $1$ through $n$ and the street sections are numbered $1$ through $m$. The following $m$ lines contain the information about the street sections, each with three integers $a_i$, $b_i$, and $c_i$ ($1 \leq a_i n, 1 \leq b_i \leq n, a_i \ne b_i, 1 \leq c_i \leq 100 000$). They mean that the street section numbered $i$ connects two intersections with the one-way direction from $a_i$ to $b_i$, which will be reversed on the $i$-th day. The street section has the length of $c_i$. Note that there may be more than one street section connecting the same pair of intersections. The pizzeria is on the intersection 1 and Alyssa's house is on the intersection 2. It is guaranteed that at least one route exists from the pizzeria to Alyssa's before the social experiment starts. Output The output should contain $m$ lines. The $i$-th line should be * HAPPY if the shortest route on the $i$-th day will become shorter, * SOSO if the length of the shortest route on the $i$-th day will not change, and * SAD if the shortest route on the $i$-th day will be longer or if there will be no route from the pizzeria to Alyssa's house. Alyssa doesn't mind whether the delivery bike can go back to the pizzeria or not. Sample Input 1 4 5 1 3 5 3 4 6 4 2 7 2 1 18 2 3 12 Sample Output 1 SAD SAD SAD SOSO HAPPY Sample Input 2 7 5 1 3 2 1 6 3 4 2 4 6 2 5 7 5 6 Sample Output 2 SOSO SAD SOSO SAD SOSO Sample Input 3 10 14 1 7 9 1 8 3 2 8 4 2 6 11 3 7 8 3 4 4 3 2 1 3 2 7 4 8 4 5 6 11 5 8 12 6 10 6 7 10 8 8 3 6 Sample Output 3 SOSO SAD HAPPY SOSO SOSO SOSO SAD SOSO SOSO SOSO SOSO SOSO SOSO SAD Example Input 4 5 1 3 5 3 4 6 4 2 7 2 1 18 2 3 12 Output SAD SAD SAD SOSO HAPPY Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Billy investigates the question of applying greedy algorithm to different spheres of life. At the moment he is studying the application of greedy algorithm to the problem about change. There is an amount of n coins of different face values, and the coins of each value are not limited in number. The task is to collect the sum x with the minimum amount of coins. Greedy algorithm with each its step takes the coin of the highest face value, not exceeding x. Obviously, if among the coins' face values exists the face value 1, any sum x can be collected with the help of greedy algorithm. However, greedy algorithm does not always give the optimal representation of the sum, i.e. the representation with the minimum amount of coins. For example, if there are face values {1, 3, 4} and it is asked to collect the sum 6, greedy algorithm will represent the sum as 4 + 1 + 1, while the optimal representation is 3 + 3, containing one coin less. By the given set of face values find out if there exist such a sum x that greedy algorithm will collect in a non-optimal way. If such a sum exists, find out the smallest of these sums. Input The first line contains an integer n (1 ≤ n ≤ 400) — the amount of the coins' face values. The second line contains n integers ai (1 ≤ ai ≤ 109), describing the face values. It is guaranteed that a1 > a2 > ... > an and an = 1. Output If greedy algorithm collects any sum in an optimal way, output -1. Otherwise output the smallest sum that greedy algorithm collects in a non-optimal way. Examples Input 5 25 10 5 2 1 Output -1 Input 3 4 3 1 Output 6 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This problem is a simplified version of D2, but it has significant differences, so read the whole statement. Polycarp has an array of $n$ ($n$ is even) integers $a_1, a_2, \dots, a_n$. Polycarp conceived of a positive integer $k$. After that, Polycarp began performing the following operations on the array: take an index $i$ ($1 \le i \le n$) and reduce the number $a_i$ by $k$. After Polycarp performed some (possibly zero) number of such operations, it turned out that all numbers in the array became the same. Find the maximum $k$ at which such a situation is possible, or print $-1$ if such a number can be arbitrarily large. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10$) — the number of test cases. Then $t$ test cases follow. Each test case consists of two lines. The first line contains an even integer $n$ ($4 \le n \le 40$) ($n$ is even). The second line contains $n$ integers $a_1, a_2, \dots a_n$ ($-10^6 \le a_i \le 10^6$). It is guaranteed that the sum of all $n$ specified in the given test cases does not exceed $100$. -----Output----- For each test case output on a separate line an integer $k$ ($k \ge 1$) — the maximum possible number that Polycarp used in operations on the array, or $-1$, if such a number can be arbitrarily large. -----Examples----- Input 3 6 1 5 3 1 1 5 8 -1 0 1 -1 0 1 -1 0 4 100 -1000 -1000 -1000 Output 2 1 1100 -----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. Bob is playing a game of Spaceship Solitaire. The goal of this game is to build a spaceship. In order to do this, he first needs to accumulate enough resources for the construction. There are $n$ types of resources, numbered $1$ through $n$. Bob needs at least $a_i$ pieces of the $i$-th resource to build the spaceship. The number $a_i$ is called the goal for resource $i$. Each resource takes $1$ turn to produce and in each turn only one resource can be produced. However, there are certain milestones that speed up production. Every milestone is a triple $(s_j, t_j, u_j)$, meaning that as soon as Bob has $t_j$ units of the resource $s_j$, he receives one unit of the resource $u_j$ for free, without him needing to spend a turn. It is possible that getting this free resource allows Bob to claim reward for another milestone. This way, he can obtain a large number of resources in a single turn. The game is constructed in such a way that there are never two milestones that have the same $s_j$ and $t_j$, that is, the award for reaching $t_j$ units of resource $s_j$ is at most one additional resource. A bonus is never awarded for $0$ of any resource, neither for reaching the goal $a_i$ nor for going past the goal — formally, for every milestone $0 < t_j < a_{s_j}$. A bonus for reaching certain amount of a resource can be the resource itself, that is, $s_j = u_j$. Initially there are no milestones. You are to process $q$ updates, each of which adds, removes or modifies a milestone. After every update, output the minimum number of turns needed to finish the game, that is, to accumulate at least $a_i$ of $i$-th resource for each $i \in [1, n]$. -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the number of types of resources. The second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq 10^9$), the $i$-th of which is the goal for the $i$-th resource. The third line contains a single integer $q$ ($1 \leq q \leq 10^5$) — the number of updates to the game milestones. Then $q$ lines follow, the $j$-th of which contains three space separated integers $s_j$, $t_j$, $u_j$ ($1 \leq s_j \leq n$, $1 \leq t_j < a_{s_j}$, $0 \leq u_j \leq n$). For each triple, perform the following actions: First, if there is already a milestone for obtaining $t_j$ units of resource $s_j$, it is removed. If $u_j = 0$, no new milestone is added. If $u_j \neq 0$, add the following milestone: "For reaching $t_j$ units of resource $s_j$, gain one free piece of $u_j$." Output the minimum number of turns needed to win the game. -----Output----- Output $q$ lines, each consisting of a single integer, the $i$-th represents the answer after the $i$-th update. -----Example----- Input 2 2 3 5 2 1 1 2 2 1 1 1 1 2 1 2 2 2 0 Output 4 3 3 2 3 -----Note----- After the first update, the optimal strategy is as follows. First produce $2$ once, which gives a free resource $1$. Then, produce $2$ twice and $1$ once, for a total of four turns. After the second update, the optimal strategy is to produce $2$ three times — the first two times a single unit of resource $1$ is also granted. After the third update, the game is won as follows. First produce $2$ once. This gives a free unit of $1$. This gives additional bonus of resource $1$. After the first turn, the number of resources is thus $[2, 1]$. Next, produce resource $2$ again, which gives another unit of $1$. After this, produce one more unit of $2$. The final count of resources is $[3, 3]$, and three turns are needed to reach this situation. Notice that we have more of resource $1$ than its goal, which is of no use. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed. There are $n$ students, each of them has a unique id (from $1$ to $n$). Thomas's id is $1$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids. In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 1000$) — the number of students. Each of the next $n$ lines contains four integers $a_i$, $b_i$, $c_i$, and $d_i$ ($0\leq a_i, b_i, c_i, d_i\leq 100$) — the grades of the $i$-th student on English, German, Math, and History. The id of the $i$-th student is equal to $i$. -----Output----- Print the rank of Thomas Smith. Thomas's id is $1$. -----Examples----- Input 5 100 98 100 100 100 100 100 100 100 100 99 99 90 99 90 100 100 98 60 99 Output 2 Input 6 100 80 90 99 60 60 60 60 90 60 100 60 60 100 60 80 100 100 0 100 0 0 0 0 Output 1 -----Note----- In the first sample, the students got total scores: $398$, $400$, $398$, $379$, and $357$. Among the $5$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $2$. In the second sample, the students got total scores: $369$, $240$, $310$, $300$, $300$, and $0$. Among the $6$ students, Thomas got the highest score, so his rank is $1$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a matrix with $n$ rows (numbered from $1$ to $n$) and $m$ columns (numbered from $1$ to $m$). A number $a_{i, j}$ is written in the cell belonging to the $i$-th row and the $j$-th column, each number is either $0$ or $1$. A chip is initially in the cell $(1, 1)$, and it will be moved to the cell $(n, m)$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $(x, y)$, then after the move it can be either $(x + 1, y)$ or $(x, y + 1)$). The chip cannot leave the matrix. Consider each path of the chip from $(1, 1)$ to $(n, m)$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on. Your goal is to change the values in the minimum number of cells so that every path is palindromic. -----Input----- The first line contains one integer $t$ ($1 \le t \le 200$) — the number of test cases. The first line of each test case contains two integers $n$ and $m$ ($2 \le n, m \le 30$) — the dimensions of the matrix. Then $n$ lines follow, the $i$-th line contains $m$ integers $a_{i, 1}$, $a_{i, 2}$, ..., $a_{i, m}$ ($0 \le a_{i, j} \le 1$). -----Output----- For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. -----Example----- Input 4 2 2 1 1 0 1 2 3 1 1 0 1 0 0 3 7 1 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 0 1 3 5 1 0 1 0 0 1 1 1 1 0 0 0 1 0 0 Output 0 3 4 4 -----Note----- The resulting matrices in the first three test cases: $\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$ $\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$ $\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Here's a way to construct a list containing every positive rational number: Build a binary tree where each node is a rational and the root is `1/1`, with the following rules for creating the nodes below: * The value of the left-hand node below `a/b` is `a/a+b` * The value of the right-hand node below `a/b` is `a+b/b` So the tree will look like this: ``` 1/1 / \ 1/2 2/1 / \ / \ 1/3 3/2 2/3 3/1 / \ / \ / \ / \ 1/4 4/3 3/5 5/2 2/5 5/3 3/4 4/1 ... ``` Now traverse the tree, breadth first, to get a list of rationals. ``` [ 1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, .. ] ``` Every positive rational will occur, in its reduced form, exactly once in the list, at a finite index. ```if:haskell In the kata, we will use tuples of type `(Integer, Integer)` to represent rationals, where `(a, b)` represents `a / b` ``` ```if:javascript In the kata, we will use tuples of type `[ Number, Number ]` to represent rationals, where `[a,b]` represents `a / b` ``` Using this method you could create an infinite list of tuples: matching the list described above: However, constructing the actual list is too slow for our purposes. Instead, study the tree above, and write two functions: For example: Write your solution by modifying this code: ```python def rat_at(n): ``` Your solution should implemented in the function "rat_at". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Salem gave you $n$ sticks with integer positive lengths $a_1, a_2, \ldots, a_n$. For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from $a$ to $b$ is $|a - b|$, where $|x|$ means the absolute value of $x$. A stick length $a_i$ is called almost good for some integer $t$ if $|a_i - t| \le 1$. Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer $t$ and the total cost of changing is minimum possible. The value of $t$ is not fixed in advance and you can choose it as any positive integer. As an answer, print the value of $t$ and the minimum cost. If there are multiple optimal choices for $t$, print any of them. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 1000$) — the number of sticks. The second line contains $n$ integers $a_i$ ($1 \le a_i \le 100$) — the lengths of the sticks. -----Output----- Print the value of $t$ and the minimum possible cost. If there are multiple optimal choices for $t$, print any of them. -----Examples----- Input 3 10 1 4 Output 3 7 Input 5 1 1 2 2 3 Output 2 0 -----Note----- In the first example, we can change $1$ into $2$ and $10$ into $4$ with cost $|1 - 2| + |10 - 4| = 1 + 6 = 7$ and the resulting lengths $[2, 4, 4]$ are almost good for $t = 3$. In the second example, the sticks lengths are already almost good for $t = 2$, so we don't have to do anything. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history. Everybody knows that the World history encompasses exactly n events: the i-th event had continued from the year ai to the year bi inclusive (ai < bi). Polycarpus easily learned the dates when each of n events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event j includes an event i if aj < ai and bi < bj. Your task is simpler: find the number of events that are included in some other event. Input The first input line contains integer n (1 ≤ n ≤ 105) which represents the number of events. Next n lines contain descriptions of the historical events, one event per line. The i + 1 line contains two integers ai and bi (1 ≤ ai < bi ≤ 109) — the beginning and the end of the i-th event. No two events start or finish in the same year, that is, ai ≠ aj, ai ≠ bj, bi ≠ aj, bi ≠ bj for all i, j (where i ≠ j). Events are given in arbitrary order. Output Print the only integer — the answer to the problem. Examples Input 5 1 10 2 9 3 8 4 7 5 6 Output 4 Input 5 1 100 2 50 51 99 52 98 10 60 Output 4 Input 1 1 1000000000 Output 0 Note In the first example the fifth event is contained in the fourth. Similarly, the fourth event is contained in the third, the third — in the second and the second — in the first. In the second example all events except the first one are contained in the first. In the third example only one event, so 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. You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide. We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors <image> and <image> is acute (i.e. strictly less than <image>). Otherwise, the point is called good. The angle between vectors <image> and <image> in 5-dimensional space is defined as <image>, where <image> is the scalar product and <image> is length of <image>. Given the list of points, print the indices of the good points in ascending order. Input The first line of input contains a single integer n (1 ≤ n ≤ 103) — the number of points. The next n lines of input contain five integers ai, bi, ci, di, ei (|ai|, |bi|, |ci|, |di|, |ei| ≤ 103) — the coordinates of the i-th point. All points are distinct. Output First, print a single integer k — the number of good points. Then, print k integers, each on their own line — the indices of the good points in ascending order. Examples Input 6 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 Output 1 1 Input 3 0 0 1 2 0 0 0 9 2 0 0 0 5 9 0 Output 0 Note In the first sample, the first point forms exactly a <image> angle with all other pairs of points, so it is good. In the second sample, along the cd plane, we can see the points look as follows: <image> We can see that all angles here are acute, so no points are good. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Your task is to make function, which returns the sum of a sequence of integers. The sequence is defined by 3 non-negative values: **begin**, **end**, **step**. If **begin** value is greater than the **end**, function should returns **0** *Examples* ~~~if-not:nasm ~~~ This is the first kata in the series: 1) Sum of a sequence (this kata) 2) [Sum of a Sequence [Hard-Core Version]](https://www.codewars.com/kata/sum-of-a-sequence-hard-core-version/javascript) Write your solution by modifying this code: ```python def sequence_sum(begin_number, end_number, step): ``` Your solution should implemented in the function "sequence_sum". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A Pythagorean triple is a triple of integer numbers $(a, b, c)$ such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to $a$, $b$ and $c$, respectively. An example of the Pythagorean triple is $(3, 4, 5)$. Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: $c = a^2 - b$. Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple $(3, 4, 5)$: $5 = 3^2 - 4$, so, according to Vasya's formula, it is a Pythagorean triple. When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers $(a, b, c)$ with $1 \le a \le b \le c \le n$ such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Each test case consists of one line containing one integer $n$ ($1 \le n \le 10^9$). -----Output----- For each test case, print one integer — the number of triples of integers $(a, b, c)$ with $1 \le a \le b \le c \le n$ such that they are Pythagorean according both to the real definition and to the formula Vasya came up with. -----Examples----- Input 3 3 6 9 Output 0 1 1 -----Note----- The only Pythagorean triple satisfying $c = a^2 - b$ with $1 \le a \le b \le c \le 9$ is $(3, 4, 5)$; that's why the answer for $n = 3$ is $0$, and the answer for $n = 6$ (and for $n = 9$) 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. A thief sneaked into a museum with a lot of treasures with only one large furoshiki. There are many things I want to steal, but the weight that the furoshiki can withstand is limited, and if it exceeds this, the furoshiki will tear. Therefore, the thief must consider a combination of treasures that will not break the prepared furoshiki and will be the most valuable. The weight W that the bath room can withstand, and the value and weight of each treasure in the museum are read, and the total value of the treasure is the maximum when the total value does not exceed W. Create a program that outputs the total weight. However, if there are multiple combinations that maximize the sum of values, the one with the smallest sum of weights will be output. Input Given multiple datasets. Each dataset is given in the following format: W N v1, w1 v2, w2 :: vN, wN The first line gives the integer W (W ≤ 1,000), which represents the weight that the furoshiki can bear, and the second line gives the number of treasures N (1 ≤ N ≤ 1,000). The next N lines are given a set of the integer vi (0 ≤ vi ≤ 10,000) representing the value of the i-th treasure and the integer wi (0 ≤ wi ≤ W) representing its weight. When W is 0, it is the last input. The number of datasets does not exceed 50. Output Output as follows for each data set. Case dataset number: Sum of the value of the treasure in the furoshiki Sum of the weight of the treasure at that time Example Input 50 5 60,10 100,20 120,30 210,45 10,4 50 5 60,10 100,20 120,30 210,45 10,4 0 Output Case 1: 220 49 Case 2: 220 49 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ## Emotional Sort ( ︶︿︶) You'll have a function called "**sortEmotions**" that will return an array of **emotions** sorted. It has two parameters, the first parameter called "**arr**" will expect an array of **emotions** where an **emotion** will be one of the following: - **:D** -> Super Happy - **:)** -> Happy - **:|** -> Normal - **:(** -> Sad - **T\_T** -> Super Sad Example of the array:``[ 'T_T', ':D', ':|', ':)', ':(' ]`` And the second parameter is called "**order**", if this parameter is **true** then the order of the emotions will be descending (from **Super Happy** to **Super Sad**) if it's **false** then it will be ascending (from **Super Sad** to **Super Happy**) Example if **order** is true with the above array: ``[ ':D', ':)', ':|', ':(', 'T_T' ]`` - Super Happy -> Happy -> Normal -> Sad -> Super Sad If **order** is false: ``[ 'T_T', ':(', ':|', ':)', ':D' ]`` - Super Sad -> Sad -> Normal -> Happy -> Super Happy Example: ``` arr = [':D', ':|', ':)', ':(', ':D'] sortEmotions(arr, true) // [ ':D', ':D', ':)', ':|', ':(' ] sortEmotions(arr, false) // [ ':(', ':|', ':)', ':D', ':D' ] ``` **More in test cases!** Notes: - The array could be empty, in that case return the same empty array ¯\\\_( ツ )\_/¯ - All **emotions** will be valid ## Enjoy! (づ。◕‿‿◕。)づ Write your solution by modifying this code: ```python def sort_emotions(arr, order): ``` Your solution should implemented in the function "sort_emotions". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=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. Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. For example: ```python unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] unique_in_order([1,2,2,3,3]) == [1,2,3] ``` Write your solution by modifying this code: ```python def unique_in_order(iterable): ``` Your solution should implemented in the function "unique_in_order". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Example Input 8 -10 0 -10 5 -5 5 -5 0 10 0 10 -5 5 -5 5 0 Output 50 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Hi there! You have to implement the `String get_column_title(int num) // syntax depends on programming language` function that takes an integer number (index of the Excel column) and returns the string represents the title of this column. #Intro In the MS Excel lines are numbered by decimals, columns - by sets of letters. For example, the first column has the title "A", second column - "B", 26th - "Z", 27th - "AA". "BA"(53) comes after "AZ"(52), "AAA" comes after "ZZ". Excel? Columns? More details [here](https://en.wikipedia.org/wiki/Microsoft_Excel) #Input It takes only one argument - column decimal index number. Argument `num` is a natural number. #Output Output is the upper-case string represents the title of column. It contains the English letters: A..Z #Errors For cases `num < 1` your function should throw/raise `IndexError`. In case of non-integer argument you should throw/raise `TypeError`. In Java, you should throw `Exceptions`. Nothing should be returned in Haskell. #Examples Python, Ruby: ``` >>> get_column_title(52) "AZ" >>> get_column_title(1337) "AYK" >>> get_column_title(432778) "XPEH" >>> get_column_title() TypeError: >>> get_column_title("123") TypeError: >>> get_column_title(0) IndexError: ``` JS, Java: ``` >>> getColumnTitle(52) "AZ" >>> getColumnTitle(1337) "AYK" >>> getColumnTitle(432778) "XPEH" >>> getColumnTitle() TypeError: >>> getColumnTitle("123") TypeError: >>> getColumnTitle(0) IndexError: ``` #Hint The difference between the 26-digits notation and Excel columns numeration that in the first system, after "Z" there are "BA", "BB", ..., while in the Excel columns scale there is a range of 26 elements: AA, AB, ... , AZ between Z and BA. It is as if in the decimal notation was the following order: 0, 1, 2, .., 9, 00, 01, 02, .., 09, 10, 11, .., 19, 20..29..99, 000, 001 and so on. #Also The task is really sapid and hard. If you're stuck - write to the discussion board, there are many smart people willing to help. Write your solution by modifying this code: ```python def get_column_title(num): ``` Your solution should implemented in the function "get_column_title". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. $N$ sages are sitting around a round table with $N$ seats. Each sage holds chopsticks with his dominant hand to eat his dinner. The following happens in this situation. * If sage $i$ is right-handed and a left-handed sage sits on his right, a level of frustration $w_i$ occurs to him. A right-handed sage on his right does not cause such frustration at all. * If sage $i$ is left-handed and a right-handed sage sits on his left, a level of frustration $w_i$ occurs to him. A left-handed sage on his left does not cause such frustration at all. You wish you could minimize the total amount of frustration by clever sitting order arrangement. Given the number of sages with his dominant hand information, make a program to evaluate the minimum frustration achievable. Input The input is given in the following format. $N$ $a_1$ $a_2$ $...$ $a_N$ $w_1$ $w_2$ $...$ $w_N$ The first line provides the number of sages $N$ ($3 \leq N \leq 10$). The second line provides an array of integers $a_i$ (0 or 1) which indicate if the $i$-th sage is right-handed (0) or left-handed (1). The third line provides an array of integers $w_i$ ($1 \leq w_i \leq 1000$) which indicate the level of frustration the $i$-th sage bears. Output Output the minimum total frustration the sages bear. Examples Input 5 1 0 0 1 0 2 3 5 1 2 Output 3 Input 3 0 0 0 1 2 3 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sereja has got an array, consisting of n integers, a_1, a_2, ..., a_{n}. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make v_{i}-th array element equal to x_{i}. In other words, perform the assignment a_{v}_{i} = x_{i}. Increase each array element by y_{i}. In other words, perform n assignments a_{i} = a_{i} + y_{i} (1 ≤ i ≤ n). Take a piece of paper and write out the q_{i}-th array element. That is, the element a_{q}_{i}. Help Sereja, complete all his operations. -----Input----- The first line contains integers n, m (1 ≤ n, m ≤ 10^5). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer t_{i} (1 ≤ t_{i} ≤ 3) that represents the operation type. If t_{i} = 1, then it is followed by two integers v_{i} and x_{i}, (1 ≤ v_{i} ≤ n, 1 ≤ x_{i} ≤ 10^9). If t_{i} = 2, then it is followed by integer y_{i} (1 ≤ y_{i} ≤ 10^4). And if t_{i} = 3, then it is followed by integer q_{i} (1 ≤ q_{i} ≤ n). -----Output----- For each third type operation print value a_{q}_{i}. Print the values in the order, in which the corresponding queries follow in the input. -----Examples----- Input 10 11 1 2 3 4 5 6 7 8 9 10 3 2 3 9 2 10 3 1 3 10 1 1 10 2 10 2 10 3 1 3 10 3 9 Output 2 9 11 20 30 40 39 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 strings arranged in a row. It is known that, for any two adjacent strings, the string to the left is lexicographically smaller than the string to the right. That is, S_1<S_2<...<S_N holds lexicographically, where S_i is the i-th string from the left. At least how many different characters are contained in S_1,S_2,...,S_N, if the length of S_i is known to be A_i? Constraints * 1 \leq N \leq 2\times 10^5 * 1 \leq A_i \leq 10^9 * A_i is an integer. Input Input is given from Standard Input in the following format: N A_1 A_2 ... A_N Output Print the minimum possible number of different characters contained in the strings. Examples Input 3 3 2 1 Output 2 Input 5 2 3 2 1 2 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. An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code $091$), a colon (ASCII code $058$), some (possibly zero) vertical line characters (ASCII code $124$), another colon, and a closing bracket (ASCII code $093$). The length of the accordion is the number of characters in it. For example, [::], [:||:] and [:|||:] are accordions having length $4$, $6$ and $7$. (:|:), {:||:}, [:], ]:||:[ are not accordions. You are given a string $s$. You want to transform it into an accordion by removing some (possibly zero) characters from it. Note that you may not insert new characters or reorder existing ones. Is it possible to obtain an accordion by removing characters from $s$, and if so, what is the maximum possible length of the result? -----Input----- The only line contains one string $s$ ($1 \le |s| \le 500000$). It consists of lowercase Latin letters and characters [, ], : and |. -----Output----- If it is not possible to obtain an accordion by removing some characters from $s$, print $-1$. Otherwise print maximum possible length of the resulting accordion. -----Examples----- Input |[a:b:|] Output 4 Input |]:[|:] 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. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 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. The only difference between easy and hard versions is the maximum value of $n$. You are given a positive integer number $n$. You really love good numbers so you want to find the smallest good number greater than or equal to $n$. The positive integer is called good if it can be represented as a sum of distinct powers of $3$ (i.e. no duplicates of powers of $3$ are allowed). For example: $30$ is a good number: $30 = 3^3 + 3^1$, $1$ is a good number: $1 = 3^0$, $12$ is a good number: $12 = 3^2 + 3^1$, but $2$ is not a good number: you can't represent it as a sum of distinct powers of $3$ ($2 = 3^0 + 3^0$), $19$ is not a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representations $19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$ are invalid), $20$ is also not a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representation $20 = 3^2 + 3^2 + 3^0 + 3^0$ is invalid). Note, that there exist other representations of $19$ and $20$ as sums of powers of $3$ but none of them consists of distinct powers of $3$. For the given positive integer $n$ find such smallest $m$ ($n \le m$) that $m$ is a good number. You have to answer $q$ independent queries. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 500$) — the number of queries. Then $q$ queries follow. The only line of the query contains one integer $n$ ($1 \le n \le 10^4$). -----Output----- For each query, print such smallest integer $m$ (where $n \le m$) that $m$ is a good number. -----Example----- Input 7 1 2 6 13 14 3620 10000 Output 1 3 9 13 27 6561 19683 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Covfefe Your are given a string. You must replace the word(s) `coverage` by `covfefe`, however, if you don't find the word `coverage` in the string, you must add `covfefe` at the end of the string with a leading space. For the languages where the string is not immutable (such as ruby), don't modify the given string, otherwise this will break the test cases. Write your solution by modifying this code: ```python def covfefe(s): ``` Your solution should implemented in the function "covfefe". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!). The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one — to the 1-st and the 3-rd ones, the 3-rd one — only to the 2-nd one. The transitions are possible only between the adjacent sections. The spacecraft team consists of n aliens. Each of them is given a rank — an integer from 1 to n. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section a to section b only if it is senior in rank to all aliens who are in the segments a and b (besides, the segments a and b are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship. Alien A is senior in rank to alien B, if the number indicating rank A, is more than the corresponding number for B. At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task. Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo m. Input The first line contains two space-separated integers: n and m (1 ≤ n, m ≤ 109) — the number of aliens on the saucer and the number, modulo which you should print the answer, correspondingly. Output Print a single number — the answer to the problem modulo m. Examples Input 1 10 Output 2 Input 3 8 Output 2 Note In the first sample the only crew member moves from segment 3 to segment 2, and then from segment 2 to segment 1 without any problems. Thus, the whole moving will take two minutes. To briefly describe the movements in the second sample we will use value <image>, which would correspond to an alien with rank i moving from the segment in which it is at the moment, to the segment number j. Using these values, we will describe the movements between the segments in the second sample: <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>; In total: the aliens need 26 moves. The remainder after dividing 26 by 8 equals 2, so the answer to this test is 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string $s$ of length $n$, consisting of digits. In one operation you can delete any character from string $s$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string $s$ becomes a telephone number. -----Input----- The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. The first line of each test case contains one integer $n$ ($1 \le n \le 100$) — the length of string $s$. The second line of each test case contains the string $s$ ($|s| = n$) consisting of digits. -----Output----- For each test print one line. If there is a sequence of operations, after which $s$ becomes a telephone number, print YES. Otherwise, print NO. -----Example----- Input 2 13 7818005553535 11 31415926535 Output YES NO -----Note----- In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote. However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes. $n$ reviewers enter the site one by one. Each reviewer is one of the following types: type $1$: a reviewer has watched the movie, and they like it — they press the upvote button; type $2$: a reviewer has watched the movie, and they dislike it — they press the downvote button; type $3$: a reviewer hasn't watched the movie — they look at the current number of upvotes and downvotes of the movie on the server they are in and decide what button to press. If there are more downvotes than upvotes, then a reviewer downvotes the movie. Otherwise, they upvote the movie. Each reviewer votes on the movie exactly once. Since you have two servers, you can actually manipulate the votes so that your movie gets as many upvotes as possible. When a reviewer enters a site, you know their type, and you can send them either to the first server or to the second one. What is the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to? -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases. Then the descriptions of $t$ testcases follow. The first line of each testcase contains a single integer $n$ ($1 \le n \le 50$) — the number of reviewers. The second line of each testcase contains $n$ integers $r_1, r_2, \dots, r_n$ ($1 \le r_i \le 3$) — the types of the reviewers in the same order they enter the site. -----Output----- For each testcase print a single integer — the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to. -----Examples----- Input 4 1 2 3 1 2 3 5 1 1 1 1 1 3 3 3 2 Output 0 2 5 2 -----Note----- In the first testcase of the example you can send the only reviewer to either of the servers — they'll downvote anyway. The movie won't receive any upvotes. In the second testcase of the example you can send all reviewers to the first server: the first reviewer upvotes; the second reviewer downvotes; the last reviewer sees that the number of downvotes is not greater than the number of upvotes — upvote themselves. There are two upvotes in total. Alternatevely, you can send the first and the second reviewers to the first server and the last reviewer — to the second server: the first reviewer upvotes on the first server; the second reviewer downvotes on the first server; the last reviewer sees no upvotes or downvotes on the second server — upvote themselves. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game! n racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to n-th (no two racers share the same place) and first m places are awarded. Racer gains bi points for i-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer i is ai points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order. Unfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship. Input The first line contains number n (1 ≤ n ≤ 105) — number of racers. Each of the next n lines contains si and ai — nick of the racer (nonempty string, which consist of no more than 20 lowercase Latin letters) and the racer's points (0 ≤ ai ≤ 106). Racers are given in the arbitrary order. The next line contains the number m (0 ≤ m ≤ n). Then m nonnegative integer numbers bi follow. i-th number is equal to amount of points for the i-th awarded place (0 ≤ bi ≤ 106). The last line contains Vasya's racer nick. Output Output two numbers — the highest and the lowest place Vasya can take up as a result of the championship. Examples Input 3 teama 10 teamb 20 teamc 40 2 10 20 teama Output 2 3 Input 2 teama 10 teamb 10 2 10 10 teamb Output 2 2 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 positive integer is called a 2-3-integer, if it is equal to 2^{x}·3^{y} for some non-negative integers x and y. In other words, these integers are such integers that only have 2 and 3 among their prime divisors. For example, integers 1, 6, 9, 16 and 108 — are 2-3 integers, while 5, 10, 21 and 120 are not. Print the number of 2-3-integers on the given segment [l, r], i. e. the number of sich 2-3-integers t that l ≤ t ≤ r. -----Input----- The only line contains two integers l and r (1 ≤ l ≤ r ≤ 2·10^9). -----Output----- Print a single integer the number of 2-3-integers on the segment [l, r]. -----Examples----- Input 1 10 Output 7 Input 100 200 Output 5 Input 1 2000000000 Output 326 -----Note----- In the first example the 2-3-integers are 1, 2, 3, 4, 6, 8 and 9. In the second example the 2-3-integers are 108, 128, 144, 162 and 192. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.