question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before. As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a node $v$ is the last different from $v$ vertex on the path from the root to the vertex $v$. Children of vertex $v$ are all nodes for which $v$ is the parent. A vertex is a leaf if it has no children. The rooted tree Serval owns has $n$ nodes, node $1$ is the root. Serval will write some numbers into all nodes of the tree. However, there are some restrictions. Each of the nodes except leaves has an operation $\max$ or $\min$ written in it, indicating that the number in this node should be equal to the maximum or minimum of all the numbers in its sons, respectively. Assume that there are $k$ leaves in the tree. Serval wants to put integers $1, 2, \ldots, k$ to the $k$ leaves (each number should be used exactly once). He loves large numbers, so he wants to maximize the number in the root. As his best friend, can you help him? -----Input----- The first line contains an integer $n$ ($2 \leq n \leq 3\cdot 10^5$), the size of the tree. The second line contains $n$ integers, the $i$-th of them represents the operation in the node $i$. $0$ represents $\min$ and $1$ represents $\max$. If the node is a leaf, there is still a number of $0$ or $1$, but you can ignore it. The third line contains $n-1$ integers $f_2, f_3, \ldots, f_n$ ($1 \leq f_i \leq i-1$), where $f_i$ represents the parent of the node $i$. -----Output----- Output one integer — the maximum possible number in the root of the tree. -----Examples----- Input 6 1 0 1 1 0 1 1 2 2 2 2 Output 1 Input 5 1 0 1 0 1 1 1 1 1 Output 4 Input 8 1 0 0 1 0 1 1 0 1 1 2 2 3 3 3 Output 4 Input 9 1 1 0 0 1 0 1 0 1 1 1 2 2 3 3 4 4 Output 5 -----Note----- Pictures below explain the examples. The numbers written in the middle of the nodes are their indices, and the numbers written on the top are the numbers written in the nodes. In the first example, no matter how you arrange the numbers, the answer is $1$. [Image] In the second example, no matter how you arrange the numbers, the answer is $4$. [Image] In the third example, one of the best solution to achieve $4$ is to arrange $4$ and $5$ to nodes $4$ and $5$. [Image] In the fourth example, the best solution is to arrange $5$ to node $5$. [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Takahashi is about to assemble a character figure, consisting of N parts called Part 1, Part 2, ..., Part N and N-1 connecting components. Parts are distinguishable, but connecting components are not. Part i has d_i holes, called Hole 1, Hole 2, ..., Hole d_i, into which a connecting component can be inserted. These holes in the parts are distinguishable. Each connecting component will be inserted into two holes in different parts, connecting these two parts. It is impossible to insert multiple connecting components into a hole. The character figure is said to be complete when it has the following properties: - All of the N-1 components are used to connect parts. - Consider a graph with N vertices corresponding to the parts and N-1 undirected edges corresponding to the pairs of vertices connected by a connecting component. Then, this graph is connected. Two ways A and B to make the figure complete are considered the same when the following is satisfied: for every pair of holes, A uses a connecting component to connect these holes if and only if B uses one to connect them. Find the number of ways to make the figure complete. Since the answer can be enormous, find the count modulo 998244353. -----Constraints----- - All values in input are integers. - 2 \leq N \leq 2 \times 10^5 - 1 \leq d_i < 998244353 -----Input----- Input is given from Standard Input in the following format: N d_1 d_2 \cdots d_N -----Output----- Print the answer. -----Sample Input----- 3 1 1 3 -----Sample Output----- 6 One way to make the figure complete is to connect Hole 1 in Part 1 and Hole 3 in Part 3 and then connect Hole 1 in Part 2 and Hole 1 in Part 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. Find \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}. Here \gcd(a,b,c) denotes the greatest common divisor of a, b, and c. -----Constraints----- - 1 \leq K \leq 200 - K is an integer. -----Input----- Input is given from Standard Input in the following format: K -----Output----- Print the value of \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}. -----Sample Input----- 2 -----Sample Output----- 9 \gcd(1,1,1)+\gcd(1,1,2)+\gcd(1,2,1)+\gcd(1,2,2)+\gcd(2,1,1)+\gcd(2,1,2)+\gcd(2,2,1)+\gcd(2,2,2)=1+1+1+1+1+1+1+2=9 Thus, the answer is 9. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In a small restaurant there are a tables for one person and b tables for two persons. It it known that n groups of people come today, each consisting of one or two people. If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person. If there are still none of them, the restaurant denies service to this group. If a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group. You are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to. -----Input----- The first line contains three integers n, a and b (1 ≤ n ≤ 2·10^5, 1 ≤ a, b ≤ 2·10^5) — the number of groups coming to the restaurant, the number of one-seater and the number of two-seater tables. The second line contains a sequence of integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 2) — the description of clients in chronological order. If t_{i} is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people. -----Output----- Print the total number of people the restaurant denies service to. -----Examples----- Input 4 1 2 1 2 1 1 Output 0 Input 4 1 1 1 1 2 1 Output 2 -----Note----- In the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. The third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, all clients are served. In the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, it occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. The fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given an array (or list) of scores, return the array of _ranks_ for each value in the array. The largest value has rank 1, the second largest value has rank 2, and so on. Ties should be handled by assigning the same rank to all tied values. For example: ranks([9,3,6,10]) = [2,4,3,1] and ranks([3,3,3,3,3,5,1]) = [2,2,2,2,2,1,7] because there is one 1st place value, a five-way tie for 2nd place, and one in 7th place. Write your solution by modifying this code: ```python def ranks(a): ``` Your solution should implemented in the function "ranks". 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. Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring s1, the second enters an infinite loop if the input data contains the substring s2, and the third requires too much memory if the input data contains the substring s3. Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions? Input There are exactly 3 lines in the input data. The i-th line contains string si. All the strings are non-empty, consists of lowercase Latin letters, the length of each string doesn't exceed 105. Output Output one number — what is minimal length of the string, containing s1, s2 and s3 as substrings. Examples Input ab bc cd Output 4 Input abacaba abaaba x Output 11 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Nauuo is a girl who loves playing cards. One day she was playing cards but found that the cards were mixed with some empty ones. There are $n$ cards numbered from $1$ to $n$, and they were mixed with another $n$ empty cards. She piled up the $2n$ cards and drew $n$ of them. The $n$ cards in Nauuo's hands are given. The remaining $n$ cards in the pile are also given in the order from top to bottom. In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile. Nauuo wants to make the $n$ numbered cards piled up in increasing order (the $i$-th card in the pile from top to bottom is the card $i$) as quickly as possible. Can you tell her the minimum number of operations? -----Input----- The first line contains a single integer $n$ ($1\le n\le 2\cdot 10^5$) — the number of numbered cards. The second line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($0\le a_i\le n$) — the initial cards in Nauuo's hands. $0$ represents an empty card. The third line contains $n$ integers $b_1,b_2,\ldots,b_n$ ($0\le b_i\le n$) — the initial cards in the pile, given in order from top to bottom. $0$ represents an empty card. It is guaranteed that each number from $1$ to $n$ appears exactly once, either in $a_{1..n}$ or $b_{1..n}$. -----Output----- The output contains a single integer — the minimum number of operations to make the $n$ numbered cards piled up in increasing order. -----Examples----- Input 3 0 2 0 3 0 1 Output 2 Input 3 0 2 0 1 0 3 Output 4 Input 11 0 0 0 5 0 0 0 4 0 0 11 9 2 6 0 8 1 7 0 3 0 10 Output 18 -----Note----- Example 1 We can play the card $2$ and draw the card $3$ in the first operation. After that, we have $[0,3,0]$ in hands and the cards in the pile are $[0,1,2]$ from top to bottom. Then, we play the card $3$ in the second operation. The cards in the pile are $[1,2,3]$, in which the cards are piled up in increasing order. Example 2 Play an empty card and draw the card $1$, then play $1$, $2$, $3$ in order. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function that accepts two arguments: an array/list of integers and another integer (`n`). Determine the number of times where two integers in the array have a difference of `n`. For example: ``` [1, 1, 5, 6, 9, 16, 27], n=4 --> 3 # (1,5), (1,5), (5,9) [1, 1, 3, 3], n=2 --> 4 # (1,3), (1,3), (1,3), (1,3) ``` Write your solution by modifying this code: ```python def int_diff(arr, n): ``` Your solution should implemented in the function "int_diff". 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. At the start of each season, every player in a football team is assigned their own unique squad number. Due to superstition or their history certain numbers are more desirable than others. Write a function generateNumber() that takes two arguments, an array of the current squad numbers (squad) and the new player's desired number (n). If the new player's desired number is not already taken, return n, else if the desired number can be formed by adding two digits between 1 and 9, return the number formed by joining these two digits together. E.g. If 2 is taken, return 11 because 1 + 1 = 2. Otherwise return null. Note: Often there will be several different ways to form a replacement number. In these cases the number with lowest first digit should be given priority. E.g. If n = 15, but squad already contains 15, return 69, not 78. Write your solution by modifying this code: ```python def generate_number(squad, n): ``` Your solution should implemented in the function "generate_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. Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression. An Ahmes arithmetic expression can be defined as: "d" is an Ahmes arithmetic expression, where d is a one-digit positive integer; "(E_1 op E_2)" is an Ahmes arithmetic expression, where E_1 and E_2 are valid Ahmes arithmetic expressions (without spaces) and op is either plus ( + ) or minus ( - ). For example 5, (1-1) and ((1+(2-3))-5) are valid Ahmes arithmetic expressions. On his trip to Egypt, Fafa found a piece of papyrus paper having one of these Ahmes arithmetic expressions written on it. Being very ancient, the papyrus piece was very worn out. As a result, all the operators were erased, keeping only the numbers and the brackets. Since Fafa loves mathematics, he decided to challenge himself with the following task: Given the number of plus and minus operators in the original expression, find out the maximum possible value for the expression on the papyrus paper after putting the plus and minus operators in the place of the original erased operators. -----Input----- The first line contains a string E (1 ≤ |E| ≤ 10^4) — a valid Ahmes arithmetic expression. All operators are erased and replaced with '?'. The second line contains two space-separated integers P and M (0 ≤ min(P, M) ≤ 100) — the number of plus and minus operators, respectively. It is guaranteed that P + M = the number of erased operators. -----Output----- Print one line containing the answer to the problem. -----Examples----- Input (1?1) 1 0 Output 2 Input (2?(1?2)) 1 1 Output 1 Input ((1?(5?7))?((6?2)?7)) 3 2 Output 18 Input ((1?(5?7))?((6?2)?7)) 2 3 Output 16 -----Note----- The first sample will be (1 + 1) = 2. The second sample will be (2 + (1 - 2)) = 1. The third sample will be ((1 - (5 - 7)) + ((6 + 2) + 7)) = 18. The fourth sample will be ((1 + (5 + 7)) - ((6 - 2) - 7)) = 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. Ito joined the Kyudo club after entering high school. At first, I had a hard time because the arrow didn't reach the target, but in the fall of my first year of high school, I managed to improve to the point where the arrow reached the target. One day, my senior Kato suggested, "Why don't you participate in a recent Kyudo competition?" Ito is ready to take on the challenge of the first tournament. In the near-field competition, four lines are shot (shooting arrows) at a time, and the number of hits (the number of hits) is recorded. Repeat this multiple times to compete for the total number of hits. For Ito-kun, who is practicing hard for the tournament, Kato-kun decided to create a program that can calculate the total middle number assuming the actual performance. This program reads the total number of shots n and the number of hits each time, and outputs the total number of hits. For example, if the total number of shots is 20, then 4 lines are shot 5 times at a time, so enter the number of hits 5 times. Input Multiple datasets are given as input. The first line of each dataset is given n (an integer that is a multiple of 4). Then n / 4 integers are given on each line to indicate the number of hits each time. When n is 0, it indicates the end of input. Do not output to this input. Output For each dataset, print the total middle number on one line. Example Input 20 4 3 2 1 3 8 2 0 0 Output 13 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given n × m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that: All cells in a set have the same color. Every two cells in a set share row or column. -----Input----- The first line of input contains integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns correspondingly. The next n lines of input contain descriptions of rows. There are m integers, separated by spaces, in each line. The number equals 0 if the corresponding cell is colored white and equals 1 if the corresponding cell is colored black. -----Output----- Output single integer  — the number of non-empty sets from the problem description. -----Examples----- Input 1 1 0 Output 1 Input 2 3 1 0 1 0 1 0 Output 8 -----Note----- In the second example, there are six one-element sets. Additionally, there are two two-element sets, the first one consists of the first and the third cells of the first row, the second one consists of the first and the third cells of the second row. To sum up, there are 8 sets. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. One day in the IT lesson Anna and Maria learned about the lexicographic order. String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi, and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languages​​. The teacher gave Anna and Maria homework. She gave them a string of length n. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string "aab": "a", "a", "aa", "ab", "aab", "b"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the k-th string from the list. Help Anna and Maria do the homework. Input The first line contains a non-empty string that only consists of small Latin letters ("a"-"z"), whose length does not exceed 105. The second line contains the only integer k (1 ≤ k ≤ 105). Output Print the string Anna and Maria need — the k-th (in the lexicographical order) substring of the given string. If the total number of substrings is less than k, print a string saying "No such line." (without the quotes). Examples Input aa 2 Output a Input abc 5 Output bc Input abab 7 Output b Note In the second sample before string "bc" follow strings "a", "ab", "abc", "b". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The only difference between easy and hard versions is the length of the string. You are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $s$ without changing order of remaining characters (in other words, it is guaranteed that $t$ is a subsequence of $s$). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from $s$ of maximum possible length such that after removing this substring $t$ will remain a subsequence of $s$. If you want to remove the substring $s[l;r]$ then the string $s$ will be transformed to $s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$ (where $|s|$ is the length of $s$). Your task is to find the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$. -----Input----- The first line of the input contains one string $s$ consisting of at least $1$ and at most $200$ lowercase Latin letters. The second line of the input contains one string $t$ consisting of at least $1$ and at most $200$ lowercase Latin letters. It is guaranteed that $t$ is a subsequence of $s$. -----Output----- Print one integer — the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$. -----Examples----- Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Nathan O. Davis is challenging a kind of shooter game. In this game, enemies emit laser beams from outside of the screen. A laser beam is a straight line with a certain thickness. Nathan moves a circular-shaped machine within the screen, in such a way it does not overlap a laser beam. As in many shooters, the machine is destroyed when the overlap happens. Nathan is facing an uphill stage. Many enemies attack simultaneously in this stage, so eventually laser beams fill out almost all of the screen. Surprisingly, it is even possible he has no "safe area" on the screen. In other words, the machine cannot survive wherever it is located in some cases. The world is as kind as it is cruel! There is a special item that helps the machine to survive any dangerous situation, even if it is exposed in a shower of laser beams, for some seconds. In addition, another straight line (called "a warning line") is drawn on the screen for a few seconds before a laser beam is emit along that line. The only problem is that Nathan has a little slow reflexes. He often messes up the timing to use the special item. But he knows a good person who can write a program to make up his slow reflexes - it's you! So he asked you for help. Your task is to write a program to make judgement whether he should use the item or not, for given warning lines and the radius of the machine. Input The input is a sequence of datasets. Each dataset corresponds to one situation with warning lines in the following format: W H N R x1,1 y1,1 x1,2 y1,2 t1 x2,1 y2,1 x2,2 y2,2 t2 ... xN,1 yN,1 xN,2 yN,2 tN The first line of a dataset contains four integers W, H, N and R (2 < W ≤ 640, 2 < H ≤ 480, 0 ≤ N ≤ 100 and 0 < R < min{W, H}/2). The first two integers W and H indicate the width and height of the screen, respectively. The next integer N represents the number of laser beams. The last integer R indicates the radius of the machine. It is guaranteed that the output would remain unchanged if the radius of the machine would become larger by 10-5 than R. The following N lines describe the N warning lines. The (i+1)-th line of the dataset corresponds to the i-th warning line, which is represented as a straight line which passes through two given different coordinates (xi,1, yi,1 ) and (xi,2 , yi,2 ). The last integer ti indicates the thickness of the laser beam corresponding to the i-th warning line. All given coordinates (x, y) on the screen are a pair of integers (0 ≤ x ≤ W, 0 ≤ y ≤ H). Note that, however, the machine is allowed to be located at non-integer coordinates during the play. The input is terminated by a line with four zeros. This line should not be processed. Output For each case, print "Yes" in a line if there is a safe area, or print "No" otherwise. Example Input 100 100 1 1 50 0 50 100 50 640 480 1 1 0 0 640 480 100 0 0 0 0 Output No Yes Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. problem Prepare the Othello board. The upper left is $ (1,1) $ and the lower right is $ (8,8) $. The board to be prepared here is $ (5,4) as follows. ) There is no $ black stone. ........ ........ ........ ... ox ... .... o ... ........ ........ ........ Kuroishi: x Shiraishi: o 8x8 board From this state, Black starts Othello first. AOR Ika-chan plays $ q $ times according to the following rules. A rectangular area is given, with the upper left as the cell in the $ a $ and $ b $ columns, and the lower right as the cell in the $ c $ and $ d $ columns. AOR Ika-chan puts black stones and white stones alternately according to the rules of Othello (reference: Wikipedia Othello) so as to maximize the number of stones contained in this rectangular area. When no more stones can be placed (when both Shiraishi and Kuroishi have to pass or when all the boards are filled), the game ends. In each game, output the number of stones when the number of stones contained in the area is maximized. Since the number of inputs and outputs may increase, it is recommended to use high-speed functions for input and output. output In each game, output the number of stones in the area when the number of stones is maximized. Also, output a line break at the end. Example Input 3 1 1 8 8 2 4 3 8 8 8 8 8 Output 48 7 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. Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm: Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). Digits are written one by one in order corresponding to number and separated by single '0' character. Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number. -----Input----- The first line contains one integer number n (1 ≤ n ≤ 89) — length of the string s. The second line contains string s — sequence of '0' and '1' characters, number in its encoded format. It is guaranteed that the number corresponding to the string is positive and doesn't exceed 10^9. The string always starts with '1'. -----Output----- Print the decoded number. -----Examples----- Input 3 111 Output 3 Input 9 110011101 Output 2031 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 stones arranged on an axis. Initially the i-th stone is located at the coordinate s_i. There may be more than one stone in a single place. You can perform zero or more operations of the following type: * take two stones with indices i and j so that s_i ≤ s_j, choose an integer d (0 ≤ 2 ⋅ d ≤ s_j - s_i), and replace the coordinate s_i with (s_i + d) and replace coordinate s_j with (s_j - d). In other words, draw stones closer to each other. You want to move the stones so that they are located at positions t_1, t_2, …, t_n. The order of the stones is not important — you just want for the multiset of the stones resulting positions to be the same as the multiset of t_1, t_2, …, t_n. Detect whether it is possible to move the stones this way, and if yes, construct a way to do so. You don't need to minimize the number of moves. Input The first line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) – the number of stones. The second line contains integers s_1, s_2, …, s_n (1 ≤ s_i ≤ 10^9) — the initial positions of the stones. The second line contains integers t_1, t_2, …, t_n (1 ≤ t_i ≤ 10^9) — the target positions of the stones. Output If it is impossible to move the stones this way, print "NO". Otherwise, on the first line print "YES", on the second line print the number of operations m (0 ≤ m ≤ 5 ⋅ n) required. You don't have to minimize the number of operations. Then print m lines, each containing integers i, j, d (1 ≤ i, j ≤ n, s_i ≤ s_j, 0 ≤ 2 ⋅ d ≤ s_j - s_i), defining the operations. One can show that if an answer exists, there is an answer requiring no more than 5 ⋅ n operations. Examples Input 5 2 2 7 4 9 5 4 5 5 5 Output YES 4 4 3 1 2 3 1 2 5 2 1 5 2 Input 3 1 5 10 3 5 7 Output NO Note Consider the first example. * After the first move the locations of stones is [2, 2, 6, 5, 9]. * After the second move the locations of stones is [2, 3, 5, 5, 9]. * After the third move the locations of stones is [2, 5, 5, 5, 7]. * After the last move the locations of stones is [4, 5, 5, 5, 5]. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You and your best friend Stripes have just landed your first high school jobs! You'll be delivering newspapers to your neighbourhood on weekends. For your services you'll be charging a set price depending on the quantity of the newspaper bundles. The cost of deliveries is: - $3.85 for 40 newspapers - $1.93 for 20 - $0.97 for 10 - $0.49 for 5 - $0.10 for 1 Stripes is taking care of the footwork doing door-to-door drops and your job is to take care of the finances. What you'll be doing is providing the cheapest possible quotes for your services. Write a function that's passed an integer representing the amount of newspapers and returns the cheapest price. The returned number must be rounded to two decimal places. ![Paperboy](http://mametesters.org/file_download.php?file_id=1016&type=bug) Write your solution by modifying this code: ```python def cheapest_quote(n): ``` Your solution should implemented in the function "cheapest_quote". 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. Let's call the set of positive integers $S$ correct if the following two conditions are met: $S \subseteq \{1, 2, \dots, n\}$; if $a \in S$ and $b \in S$, then $|a-b| \neq x$ and $|a-b| \neq y$. For the given values $n$, $x$, and $y$, you have to find the maximum size of the correct set. -----Input----- A single line contains three integers $n$, $x$ and $y$ ($1 \le n \le 10^9$; $1 \le x, y \le 22$). -----Output----- Print one integer — the maximum size of the correct set. -----Examples----- Input 10 2 5 Output 5 Input 21 4 6 Output 9 Input 1337 7 7 Output 672 Input 455678451 22 17 Output 221997195 -----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. Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical. The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification. Help Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order. Input Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters. Output If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots. If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages. Examples Input NOD BAA YARD AIRWAY NEWTON BURN Output BAA... U.I... R.R... NEWTON ..A..O ..YARD Input AAA AAA AAAAA AAA AAA AAAAA Output AAA.. A.A.. AAAAA ..A.A ..AAA Input PTC JYNYFDSGI ZGPPC IXEJNDOP JJFS SSXXQOFGJUZ Output JJFS.... Y..S.... N..X.... Y..X.... F..Q.... D..O.... S..F.... G..G.... IXEJNDOP ...U...T ...ZGPPC Read the inputs from stdin solve the problem and write the answer to stdout (do 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 unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission. Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k_1 knights with lightsabers of the first color, k_2 knights with lightsabers of the second color, ..., k_{m} knights with lightsabers of the m-th color. Help her find out if this is possible. -----Input----- The first line of the input contains n (1 ≤ n ≤ 100) and m (1 ≤ m ≤ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains m integers k_1, k_2, ..., k_{m} (with $1 \leq \sum_{i = 1}^{m} k_{i} \leq n$) – the desired counts of lightsabers of each color from 1 to m. -----Output----- Output YES if an interval with prescribed color counts exists, or output NO if there is none. -----Example----- Input 5 2 1 1 2 2 1 1 2 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. There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of n walruses in the queue his displeasure. Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Examples Input 6 10 8 5 3 50 45 Output 2 1 0 -1 0 -1 Input 7 10 4 6 3 2 8 15 Output 4 2 1 0 -1 -1 -1 Input 5 10 3 1 10 11 Output 1 0 -1 -1 -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to perform a very large number of calculations to improve the calculation power and raise awareness. Exponentiation is an operation that easily produces large numbers. There are N non-negative integers A1, A2, ..., AN. We would like to find the sorts B1, B2, ..., BN that maximize B1B2 ... BN -1BN. Of course, it is common sense for rabbits, but this calculation is performed in order from the upper right. We also promise that 00 = 1. There may be multiple types of B1, B2, ..., and BN that satisfy the maximum conditions. In such a case, let's choose the smallest column in the dictionary order. Input N A1 ... AN Satisfy 1 ≤ N ≤ 100, 0 ≤ Ai ≤ 1,000,000,000. Output The output consists of N lines. Output Bi on line i. Examples Input 4 7 5 10 6 Output 5 6 7 10 Input 3 0 0 1000000000 Output 1000000000 0 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. Two tortoises named ***A*** and ***B*** must run a race. ***A*** starts with an average speed of ```720 feet per hour```. Young ***B*** knows she runs faster than ***A***, and furthermore has not finished her cabbage. When she starts, at last, she can see that ***A*** has a `70 feet lead` but ***B***'s speed is `850 feet per hour`. How long will it take ***B*** to catch ***A***? More generally: given two speeds `v1` (***A***'s speed, integer > 0) and `v2` (***B***'s speed, integer > 0) and a lead `g` (integer > 0) how long will it take ***B*** to catch ***A***? The result will be an array ```[hour, min, sec]``` which is the time needed in hours, minutes and seconds (round down to the nearest second) or a string in some languages. If `v1 >= v2` then return `nil`, `nothing`, `null`, `None` or `{-1, -1, -1}` for C++, C, Go, Nim, `[]` for Kotlin or "-1 -1 -1". ## Examples: (form of the result depends on the language) ``` race(720, 850, 70) => [0, 32, 18] or "0 32 18" race(80, 91, 37) => [3, 21, 49] or "3 21 49" ``` ** Note: - See other examples in "Your test cases". - In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings. ** Hints for people who don't know how to convert to hours, minutes, seconds: - Tortoises don't care about fractions of seconds - Think of calculation by hand using only integers (in your code use or simulate integer division) - or Google: "convert decimal time to hours minutes seconds" Write your solution by modifying this code: ```python def race(v1, v2, g): ``` Your solution should implemented in the function "race". 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 a non-negative integer N, define S(N) as the sum of the odd digits of N plus twice the sum of the even digits of N. For example, S(5)=5, S(456)=2*4+5+2*6=25, and S(314159)=3+1+2*4+1+5+9=27. Define D(N) as the last digit of S(N). So D(5)=5, D(456)=5, and D(314159)=7. Given 2 non-negative integers A and B, compute the sum of D(N) over all N between A and B, inclusive. ------ Input ------ Input will begin with an integer T, the number of test cases. T lines follow, each containing 2 integers A and B. ------ Output ------ For each test case, output a single integer indicating the corresponding sum. ------ Constraints ------ $T ≤ 1000$ $0 ≤ A ≤ B ≤ 400,000,000$ ----- Sample Input 1 ------ 3 1 8 28 138 314159 314159 ----- Sample Output 1 ------ 36 495 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. It is a holiday season, and Koala is decorating his house with cool lights! He owns $n$ lights, all of which flash periodically. After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters $a_i$ and $b_i$. Light with parameters $a_i$ and $b_i$ will toggle (on to off, or off to on) every $a_i$ seconds starting from the $b_i$-th second. In other words, it will toggle at the moments $b_i$, $b_i + a_i$, $b_i + 2 \cdot a_i$ and so on. You know for each light whether it's initially on or off and its corresponding parameters $a_i$ and $b_i$. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out. [Image] Here is a graphic for the first example. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 100$), the number of lights. The next line contains a string $s$ of $n$ characters. The $i$-th character is "1", if the $i$-th lamp is initially on. Otherwise, $i$-th character is "0". The $i$-th of the following $n$ lines contains two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le 5$)  — the parameters of the $i$-th light. -----Output----- Print a single integer — the maximum number of lights that will ever be on at the same time. -----Examples----- Input 3 101 3 3 3 2 3 1 Output 2 Input 4 1111 3 4 5 2 3 1 3 2 Output 4 Input 6 011100 5 3 5 5 2 4 3 5 4 2 1 5 Output 6 -----Note----- For first example, the lamps' states are shown in the picture above. The largest number of simultaneously on lamps is $2$ (e.g. at the moment $2$). In the second example, all lights are initially on. So the answer is $4$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Takahashi has many red balls and blue balls. Now, he will place them in a row. Initially, there is no ball placed. Takahashi, who is very patient, will do the following operation 10^{100} times: - Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row. How many blue balls will be there among the first N balls in the row of balls made this way? -----Constraints----- - 1 \leq N \leq 10^{18} - A, B \geq 0 - 0 < A + B \leq 10^{18} - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N A B -----Output----- Print the number of blue balls that will be there among the first N balls in the row of balls. -----Sample Input----- 8 3 4 -----Sample Output----- 4 Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains n ski junctions, numbered from 1 to n. Initially the junctions aren't connected in any way. In the constructing process m bidirectional ski roads will be built. The roads are built one after another: first the road number 1 will be built, then the road number 2, and so on. The i-th road connects the junctions with numbers ai and bi. Track is the route with the following properties: * The route is closed, that is, it begins and ends in one and the same junction. * The route contains at least one road. * The route doesn't go on one road more than once, however it can visit any junction any number of times. Let's consider the ski base as a non-empty set of roads that can be divided into one or more tracks so that exactly one track went along each road of the chosen set. Besides, each track can consist only of roads from the chosen set. Ski base doesn't have to be connected. Two ski bases are considered different if they consist of different road sets. After building each new road the Walrusland government wants to know the number of variants of choosing a ski base based on some subset of the already built roads. The government asks you to help them solve the given problem. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). They represent the number of junctions and the number of roads correspondingly. Then on m lines follows the description of the roads in the order in which they were built. Each road is described by a pair of integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of the connected junctions. There could be more than one road between a pair of junctions. Output Print m lines: the i-th line should represent the number of ways to build a ski base after the end of construction of the road number i. The numbers should be printed modulo 1000000009 (109 + 9). Examples Input 3 4 1 3 2 3 1 2 1 2 Output 0 0 1 3 Note Let us have 3 junctions and 4 roads between the junctions have already been built (as after building all the roads in the sample): 1 and 3, 2 and 3, 2 roads between junctions 1 and 2. The land lot for the construction will look like this: <image> The land lot for the construction will look in the following way: <image> We can choose a subset of roads in three ways: <image> In the first and the second ways you can choose one path, for example, 1 - 2 - 3 - 1. In the first case you can choose one path 1 - 2 - 1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. For a pole vaulter, it is very important to begin the approach run at the best possible starting mark. This is affected by numerous factors and requires fine-tuning in practice. But there is a guideline that will help a beginning vaulter start at approximately the right location for the so-called "three-step approach," based on the vaulter's body height. This guideline was taught to me in feet and inches, but due to the international nature of Codewars, I am creating this kata to use metric units instead. You are given the following two guidelines to begin with: (1) A vaulter with a height of 1.52 meters should start at 9.45 meters on the runway. (2) A vaulter with a height of 1.83 meters should start at 10.67 meters on the runway. You will receive a vaulter's height in meters (which will always lie in a range between a minimum of 1.22 meters and a maximum of 2.13 meters). Your job is to return the best starting mark in meters, rounded to two decimal places. Hint: Based on the two guidelines given above, you will want to account for the change in starting mark per change in body height. This involves a linear relationship. But there is also a constant offset involved. If you can determine the rate of change described above, you should be able to determine that constant offset. Write your solution by modifying this code: ```python def starting_mark(height): ``` Your solution should implemented in the function "starting_mark". 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. Write a program which reverses a given string str. Input str (the size of str ≤ 20) is given in a line. Output Print the reversed str in a line. Example Input w32nimda Output admin23w Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path. Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each floor is surrounded by a concrete wall on the left and on the right. Now Joe is on the n-th floor and in the first cell, counting from left to right. At each moment of time, Joe has the direction of his gaze, to the right or to the left (always one direction of the two). Initially, Joe looks to the right. Joe moves by a particular algorithm. Every second he makes one of the following actions: If the cell directly under Joe is empty, then Joe falls down. That is, he moves to this cell, the gaze direction is preserved. Otherwise consider the next cell in the current direction of the gaze. If the cell is empty, then Joe moves into it, the gaze direction is preserved. If this cell has bricks, then Joe breaks them with his forehead (the cell becomes empty), and changes the direction of his gaze to the opposite. If this cell has a concrete wall, then Joe just changes the direction of his gaze to the opposite (concrete can withstand any number of forehead hits). Joe calms down as soon as he reaches any cell of the first floor. The figure below shows an example Joe's movements around the house. [Image] Determine how many seconds Joe will need to calm down. -----Input----- The first line contains two integers n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 10^4). Next n lines contain the description of Joe's house. The i-th of these lines contains the description of the (n - i + 1)-th floor of the house — a line that consists of m characters: "." means an empty cell, "+" means bricks and "#" means a concrete wall. It is guaranteed that the first cell of the n-th floor is empty. -----Output----- Print a single number — the number of seconds Joe needs to reach the first floor; or else, print word "Never" (without the quotes), if it can never happen. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 3 5 ..+.# #+..+ +.#+. Output 14 Input 4 10 ...+.##+.+ +#++..+++# ++.#++++.. .+##.++#.+ Output 42 Input 2 2 .. ++ Output Never Read the inputs from stdin solve the problem and write the answer to stdout (do 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 It's been more than 20 minutes since the negligent waiter has taken your order for the house special prime tofu steak with a side of chili fries. Out of boredom, you start fiddling around with the condiments tray. To be efficient, you want to be familiar with the choice of sauces and spices before your order is finally served. You also examine the toothpick holder and try to analyze its inner workings when - yikes - the holder's lid falls off and all 23 picks lay scattered on the table. Being a good and hygiene oriented citizen, you decide not to just put them back in the holder. Instead of letting all the good wood go to waste, you start playing around with the picks. In the first "round", you lay down one toothpick vertically. You've used a total of one toothpick. In the second "round", at each end of the first toothpick, you add a perpendicular toothpick at its center point. You added two additional toothpicks for a total of three toothpicks. In the next rounds, you continue to add perpendicular toothpicks to each free end of toothpicks already on the table. With your 23 toothpicks, you can complete a total of six rounds: You wonder if you'd be able to implement this sequence in your favorite programming language. Because your food still hasn't arrived, you decide to take out your laptop and start implementing... Challenge Implement a script that returns the amount of toothpicks needed to complete n amount of rounds of the toothpick sequence. ``` 0 <= n <= 5000 ``` Hint You can attempt this brute force or get some inspiration from the math department. Write your solution by modifying this code: ```python def toothpick(n): ``` Your solution should implemented in the function "toothpick". 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. At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect. The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that. Input The first line contains integer n (1 ≤ n ≤ 5000) — amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1 ≤ li < ri ≤ 106) — starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1). Output Output integer k — amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers — indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order. Examples Input 3 3 10 20 30 1 3 Output 3 1 2 3 Input 4 3 10 20 30 1 3 1 39 Output 1 4 Input 3 1 5 2 6 3 7 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. Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift. Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad. Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7). Input The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b). Output Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7). Examples Input 5 2 4 1 Output 2 Input 5 2 4 2 Output 2 Input 5 3 4 1 Output 0 Note Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj. Notes to the samples: 1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|. 2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip. 3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s. Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order. A merge z is produced from a sequence a by the following rules: * if a_i=0, then remove a letter from the beginning of x and append it to the end of z; * if a_i=1, then remove a letter from the beginning of y and append it to the end of z. Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i. Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i. Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive. Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered. Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353. Input The first line contains a string x (1 ≤ |x| ≤ 1000). The second line contains a string y (1 ≤ |y| ≤ 1000). Both strings consist only of lowercase Latin letters. Output Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353. Examples Input aaa bb Output 24 Input code forces Output 1574 Input aaaaa aaa Output 0 Input justamassivetesttocheck howwellyouhandlemodulooperations Output 667387032 Note In the first example there are: * 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10"; * 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101"; * 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010"; * 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010"; * 2 pairs of substrings "aaa" and "b", each with no valid merging sequences; * 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010"; Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 educational program (AHK Education) of the Aiz Broadcasting Association broadcasts a handicraft program for children, "Play with Tsukuro". This time I will make a box with sticks, but I would like to see if I can make a rectangular parallelepiped using the 12 sticks I prepared. However, the stick must not be cut or broken. Given the lengths of the twelve bars, write a program to determine if you can create a rectangular parallelepiped with all of them as sides. Input The input is given in the following format. e1 e2 ... e12 The input consists of one line and is given the integer ei (1 ≤ ei ≤ 100) representing the length of each bar. Output If a rectangular parallelepiped can be created, "yes" is output, and if it cannot be created, "no" is output. However, since a cube is a kind of rectangular parallelepiped, "yes" is output even if it is a cube. Examples Input 1 1 3 4 8 9 7 3 4 5 5 5 Output no Input 1 1 2 2 3 1 2 3 3 3 1 2 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. # Definition A number is a **_Special Number_** *if it’s digits only consist 0, 1, 2, 3, 4 or 5* **_Given_** a number *determine if it special number or not* . # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ___ # Notes * **_The number_** passed will be **_positive_** (N > 0) . * All **single-digit numbers** with in the interval **_[0:5]_** are considered as **_special number_**. ___ # Input >> Output Examples ``` specialNumber(2) ==> return "Special!!" ``` ## Explanation: It's **_a single-digit number_** within the interval **_[0:5]_** . ``` specialNumber(9) ==> return "NOT!!" ``` ## Explanation: Although, it's a single-digit number but **_Outside the interval [0:5]_** . ``` specialNumber(23) ==> return "Special!!" ``` ## Explanation: All **_the number's digits_** formed from the interval **_[0:5]_** digits . ``` specialNumber(39) ==> return "NOT!!" ``` ## Explanation: Although, *there is a digit (3) Within the interval* **_But_** **_the second digit is not (Must be ALL The Number's Digits )_** . ``` specialNumber(59) ==> return "NOT!!" ``` ## Explanation: Although, *there is a digit (5) Within the interval* **_But_** **_the second digit is not (Must be ALL The Number's Digits )_** . ``` specialNumber(513) ==> return "Special!!" ``` ___ ``` specialNumber(709) ==> return "NOT!!" ``` ___ # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ### ALL translation are welcomed ## Enjoy Learning !! # Zizou Write your solution by modifying this code: ```python def special_number(number): ``` Your solution should implemented in the function "special_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. A queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop. There are m queens on a square n × n chessboard. You know each queen's positions, the i-th queen is positioned in the square (ri, ci), where ri is the board row number (numbered from the top to the bottom from 1 to n), and ci is the board's column number (numbered from the left to the right from 1 to n). No two queens share the same position. For each queen one can count w — the number of other queens that the given queen threatens (attacks). For a fixed attack direction only the first queen in this direction is under attack if there are many queens are on the ray of the attack. Obviously, for any queen w is between 0 and 8, inclusive. Print the sequence t0, t1, ..., t8, where ti is the number of queens that threaten exactly i other queens, i.e. the number of queens that their w equals i. Input The first line of the input contains a pair of integers n, m (1 ≤ n, m ≤ 105), where n is the size of the board and m is the number of queens on the board. Then m following lines contain positions of the queens, one per line. Each line contains a pair of integers ri, ci (1 ≤ ri, ci ≤ n) — the queen's position. No two queens stand on the same square. Output Print the required sequence t0, t1, ..., t8, separating the numbers with spaces. Examples Input 8 4 4 3 4 8 6 5 1 6 Output 0 3 0 1 0 0 0 0 0 Input 10 3 1 1 1 2 1 3 Output 0 2 1 0 0 0 0 0 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. When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add and subtract? — That's right, using counting sticks! An here's our new task: An expression of counting sticks is an expression of type:[ A sticks][sign +][B sticks][sign =][C sticks] (1 ≤ A, B, C). Sign + consists of two crossed sticks: one vertical and one horizontal. Sign = consists of two horizontal sticks. The expression is arithmetically correct if A + B = C. We've got an expression that looks like A + B = C given by counting sticks. Our task is to shift at most one stick (or we can shift nothing) so that the expression became arithmetically correct. Note that we cannot remove the sticks from the expression, also we cannot shift the sticks from the signs + and =. We really aren't fabulous at arithmetics. Can you help us? -----Input----- The single line contains the initial expression. It is guaranteed that the expression looks like A + B = C, where 1 ≤ A, B, C ≤ 100. -----Output----- If there isn't a way to shift the stick so the expression becomes correct, print on a single line "Impossible" (without the quotes). If there is a way, print the resulting expression. Follow the format of the output from the test samples. Don't print extra space characters. If there are multiple correct answers, print any of them. For clarifications, you are recommended to see the test samples. -----Examples----- Input ||+|=||||| Output |||+|=|||| Input |||||+||=|| Output Impossible Input |+|=|||||| Output Impossible Input ||||+||=|||||| Output ||||+||=|||||| -----Note----- In the first sample we can shift stick from the third group of sticks to the first one. In the second sample we cannot shift vertical stick from + sign to the second group of sticks. So we cannot make a - sign. There is no answer in the third sample because we cannot remove sticks from the expression. In the forth sample the initial expression is already arithmetically correct and that is why we don't have to shift sticks. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Print all the integers that satisfies the following in ascending order: - Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers. -----Constraints----- - 1 \leq A \leq B \leq 10^9 - 1 \leq K \leq 100 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: A B K -----Output----- Print all the integers that satisfies the condition above in ascending order. -----Sample Input----- 3 8 2 -----Sample Output----- 3 4 7 8 - 3 is the first smallest integer among the integers between 3 and 8. - 4 is the second smallest integer among the integers between 3 and 8. - 7 is the second largest integer among the integers between 3 and 8. - 8 is the first largest integer among the integers between 3 and 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. In an embassy of a well-known kingdom an electronic queue is organised. Every person who comes to the embassy, needs to make the following three actions: show the ID, pay money to the cashier and be fingerprinted. Besides, the actions should be performed in the given order. For each action several separate windows are singled out: k1 separate windows for the first action (the first type windows), k2 windows for the second one (the second type windows), and k3 for the third one (the third type windows). The service time for one person in any of the first type window equals to t1. Similarly, it takes t2 time to serve a person in any of the second type windows. And it takes t3 to serve one person in any of the third type windows. Thus, the service time depends only on the window type and is independent from the person who is applying for visa. At some moment n people come to the embassy, the i-th person comes at the moment of time ci. The person is registered under some number. After that he sits in the hall and waits for his number to be shown on a special board. Besides the person's number the board shows the number of the window where one should go and the person goes there immediately. Let's consider that the time needed to approach the window is negligible. The table can show information for no more than one person at a time. The electronic queue works so as to immediately start working with the person who has approached the window, as there are no other people in front of the window. The Client Service Quality inspectors noticed that several people spend too much time in the embassy (this is particularly tiresome as the embassy has no mobile phone reception and 3G). It was decided to organise the system so that the largest time a person spends in the embassy were minimum. Help the inspectors organise the queue. Consider that all actions except for being served in at the window, happen instantly. Input The first line contains three space-separated integers k1, k2, k3 (1 ≤ ki ≤ 109), they are the number of windows of the first, second and third type correspondingly. The second line contains three space-separated integers t1, t2, t3 (1 ≤ ti ≤ 105), they are the periods of time needed to serve one person in the window of the first, second and third type correspondingly. The third line contains an integer n (1 ≤ n ≤ 105), it is the number of people. The fourth line contains n space-separated integers ci (1 ≤ ci ≤ 109) in the non-decreasing order; ci is the time when the person number i comes to the embassy. Output Print the single number, the maximum time a person will spend in the embassy if the queue is organized optimally. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams (also you may use the %I64d specificator). Examples Input 1 1 1 1 1 1 5 1 1 1 1 1 Output 7 Input 2 1 1 5 1 1 5 1 2 3 3 5 Output 13 Note In the first test 5 people come simultaneously at the moment of time equal to 1. There is one window of every type, it takes 1 unit of time to be served at each window. That's why the maximal time a person spends in the embassy is the time needed to be served at the windows (3 units of time) plus the time the last person who comes to the first window waits (4 units of time). Windows in the second test work like this: The first window of the first type: [1, 6) — the first person, [6, 11) — third person, [11, 16) — fifth person The second window of the first type: [2, 7) — the second person, [7, 12) — the fourth person The only second type window: [6, 7) — first, [7, 8) — second, [11, 12) — third, [12, 13) — fourth, [16, 17) — fifth The only third type window: [7, 8) — first, [8, 9) — second, [12, 13) — third, [13, 14) — fourth, [17, 18) — fifth We can see that it takes most time to serve the fifth person. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $p$ of length $n$, and Skynyrd bought an array $a$ of length $m$, consisting of integers from $1$ to $n$. Lynyrd and Skynyrd became bored, so they asked you $q$ queries, each of which has the following form: "does the subsegment of $a$ from the $l$-th to the $r$-th positions, inclusive, have a subsequence that is a cyclic shift of $p$?" Please answer the queries. A permutation of length $n$ is a sequence of $n$ integers such that each integer from $1$ to $n$ appears exactly once in it. A cyclic shift of a permutation $(p_1, p_2, \ldots, p_n)$ is a permutation $(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$ for some $i$ from $1$ to $n$. For example, a permutation $(2, 1, 3)$ has three distinct cyclic shifts: $(2, 1, 3)$, $(1, 3, 2)$, $(3, 2, 1)$. A subsequence of a subsegment of array $a$ from the $l$-th to the $r$-th positions, inclusive, is a sequence $a_{i_1}, a_{i_2}, \ldots, a_{i_k}$ for some $i_1, i_2, \ldots, i_k$ such that $l \leq i_1 < i_2 < \ldots < i_k \leq r$. -----Input----- The first line contains three integers $n$, $m$, $q$ ($1 \le n, m, q \le 2 \cdot 10^5$) — the length of the permutation $p$, the length of the array $a$ and the number of queries. The next line contains $n$ integers from $1$ to $n$, where the $i$-th of them is the $i$-th element of the permutation. Each integer from $1$ to $n$ appears exactly once. The next line contains $m$ integers from $1$ to $n$, the $i$-th of them is the $i$-th element of the array $a$. The next $q$ lines describe queries. The $i$-th of these lines contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le m$), meaning that the $i$-th query is about the subsegment of the array from the $l_i$-th to the $r_i$-th positions, inclusive. -----Output----- Print a single string of length $q$, consisting of $0$ and $1$, the digit on the $i$-th positions should be $1$, if the subsegment of array $a$ from the $l_i$-th to the $r_i$-th positions, inclusive, contains a subsequence that is a cyclic shift of $p$, and $0$ otherwise. -----Examples----- Input 3 6 3 2 1 3 1 2 3 1 2 3 1 5 2 6 3 5 Output 110 Input 2 4 3 2 1 1 1 2 2 1 2 2 3 3 4 Output 010 -----Note----- In the first example the segment from the $1$-st to the $5$-th positions is $1, 2, 3, 1, 2$. There is a subsequence $1, 3, 2$ that is a cyclic shift of the permutation. The subsegment from the $2$-nd to the $6$-th positions also contains a subsequence $2, 1, 3$ that is equal to the permutation. The subsegment from the $3$-rd to the $5$-th positions is $3, 1, 2$, there is only one subsequence of length $3$ ($3, 1, 2$), but it is not a cyclic shift of the permutation. In the second example the possible cyclic shifts are $1, 2$ and $2, 1$. The subsegment from the $1$-st to the $2$-nd positions is $1, 1$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $2$-nd to the $3$-rd positions is $1, 2$, it coincides with the permutation. The subsegment from the $3$ to the $4$ positions is $2, 2$, its subsequences are not cyclic shifts of the permutation. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Falling Block Puzzle Block drop You are playing a falling block puzzle. As shown in the figure below, the field of this puzzle has a shape in which cubic cells are arranged in 2 squares x 2 squares in each row, and the rows are infinitely arranged on the top. <image> Each cell either has one block that fits snugly in the cell, or nothing. This puzzle proceeds as follows. 1. Some blocks are installed in the initial state. 2. Drop a block that fits in 2 squares x 2 squares x 2 squares from above. However, before dropping, the block can be translated horizontally so that the block does not stick out of the field. 3. When the bottom surface of one of the dropped blocks reaches the bottom of the block or field that has already been placed, all the blocks will stop falling and stop. 4. For each stage, if all 4 squares are filled, the blocks in that stage will disappear, and the blocks above it will fall one by one. Even if there are no blocks in the cell below each block after the fall, it will not fall any further. 5. Return to 2. Since the blocks placed in the initial state and some lumps to be dropped are given, create a program to find out how many steps can be erased by dropping all the lumps in the order given. Input The input consists of 100 or less datasets. Each dataset has the following form. > (Initial block height H) (Number of lumps to drop N) > (1st stage in the initial state) > ... > (H stage in the initial state) > (1st drop) > ... > (Nth drop) The first line of each dataset specifies the initial block height H (1 ≤ H ≤ 10) and the number of lumps to drop N (1 ≤ N ≤ 3). Then, the information of each stage in the initial state is given in the following format. > c11 c12 > c21 c22 cij represents the information of each cell,'#' indicates that a block exists, and'.' Indicates that there is no block. It can be assumed that there are no blocks in all cells or no blocks in all cells for each of the first to H rows. Then, the information of each drop mass is given in the following format. > b111 b112 > b121 b122 > b211 b212 > b221 b222 As in the initial state format,'#' indicates that a block exists, and'.' Indicates that there is no block. Each block contains at least one block. The blocks contained in the block may be touched only by the corners and sides, and are not necessarily connected by the surface. Refer to the figure below for the correspondence of the input subscripts of the initial state and block block. <image> The end of the input is indicated by a single line of two zeros. The figure below shows the first data set in the Sample Input shown later. In this dataset, one step can be erased by translating a block of blocks diagonally and then dropping them. <image> Output For each dataset, output on one line how many columns can be erased at the maximum. Sample Input 1 1 .. .. .. .. .. 1 1 . # .. .. .. .. . # twenty two .. .. .. . # .. .. .. .. .. 13 .. .. 10 3 .. .. . # . # .. .. . # . # . # .. . # .. .. . # .. . # .. .. .. .. .. .. .. .. 10 3 . # .. .. . # .. . # . # . # .. . # .. . # .. .. . # .. .. .. .. .. .. .. .. . # 0 0 Output for Sample Input 1 0 3 6 6 0 Example Input 1 1 ## #. .. .. #. .. 1 1 .# #. #. .. .. .# 2 2 ## #. ## #. .. .# ## #. #. .. #. .. 1 3 #. .. ## ## ## ## ## ## ## ## ## ## ## ## 10 3 ## #. ## #. ## .# ## .# #. ## #. ## .# ## .# ## .# #. .# #. #. .# #. .# #. .. #. .. #. .. #. .. 10 3 ## .# ## .. ## #. .# .. ## .# .# ## .# ## #. ## ## .# .. .# #. #. .# #. #. #. #. .. .. .. .. .# 0 0 Output 1 0 3 6 6 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 kata is part of the collection [Mary's Puzzle Books](https://www.codewars.com/collections/marys-puzzle-books). Mary brought home a "spot the differences" book. The book is full of a bunch of problems, and each problem consists of two strings that are similar. However, in each string there are a few characters that are different. An example puzzle from her book is: ``` String 1: "abcdefg" String 2: "abcqetg" ``` Notice how the "d" from String 1 has become a "q" in String 2, and "f" from String 1 has become a "t" in String 2. It's your job to help Mary solve the puzzles. Write a program `spot_diff`/`Spot` that will compare the two strings and return a list with the positions where the two strings differ. In the example above, your program should return `[3, 5]` because String 1 is different from String 2 at positions 3 and 5. NOTES: ```if-not:csharp • If both strings are the same, return `[]` ``` ```if:csharp • If both strings are the same, return `new List()` ``` • Both strings will always be the same length • Capitalization and punctuation matter Write your solution by modifying this code: ```python def spot_diff(s1, s2): ``` Your solution should implemented in the function "spot_diff". 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. Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he understood, and he's ready to face the evils of the Empire! The rebels have $s$ spaceships, each with a certain attacking power $a$. They want to send their spaceships to destroy the empire bases and steal enough gold and supplies in order to keep the rebellion alive. The empire has $b$ bases, each with a certain defensive power $d$, and a certain amount of gold $g$. A spaceship can attack all the bases which have a defensive power less than or equal to its attacking power. If a spaceship attacks a base, it steals all the gold in that base. The rebels are still undecided which spaceship to send out first, so they asked for the Doctor's help. They would like to know, for each spaceship, the maximum amount of gold it can steal. -----Input----- The first line contains integers $s$ and $b$ ($1 \leq s, b \leq 10^5$), the number of spaceships and the number of bases, respectively. The second line contains $s$ integers $a$ ($0 \leq a \leq 10^9$), the attacking power of each spaceship. The next $b$ lines contain integers $d, g$ ($0 \leq d \leq 10^9$, $0 \leq g \leq 10^4$), the defensive power and the gold of each base, respectively. -----Output----- Print $s$ integers, the maximum amount of gold each spaceship can steal, in the same order as the spaceships are given in the input. -----Example----- Input 5 4 1 3 5 2 4 0 1 4 2 2 8 9 4 Output 1 9 11 9 11 -----Note----- The first spaceship can only attack the first base. The second spaceship can attack the first and third bases. The third spaceship can attack the first, second and third bases. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Summation Of Primes The sum of the primes below or equal to 10 is **2 + 3 + 5 + 7 = 17**. Find the sum of all the primes **_below or equal to the number passed in_**. From Project Euler's [Problem #10](https://projecteuler.net/problem=10 "Project Euler - Problem 10"). Write your solution by modifying this code: ```python def summationOfPrimes(primes): ``` Your solution should implemented in the function "summationOfPrimes". 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. Write a program which judges wheather given length of three side form a right triangle. Print "YES" if the given sides (integers) form a right triangle, "NO" if not so. Constraints * 1 ≤ length of the side ≤ 1,000 * N ≤ 1,000 Input Input consists of several data sets. In the first line, the number of data set, N is given. Then, N lines follow, each line corresponds to a data set. A data set consists of three integers separated by a single space. Output For each data set, print "YES" or "NO". Example Input 3 4 3 5 4 3 6 8 8 8 Output YES NO NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task Mr.Nam has `n` candies, he wants to put one candy in each cell of a table-box. The table-box has `r` rows and `c` columns. Each candy was labeled by its cell number. The cell numbers are in range from 1 to N and the direction begins from right to left and from bottom to top. Nam wants to know the position of a specific `candy` and which box is holding it. The result should be an array and contain exactly 3 elements. The first element is the `label` of the table; The second element is the `row` of the candy; The third element is the `column` of the candy. If there is no candy with the given number, return `[-1, -1, -1]`. Note: When the current box is filled up, Nam buys another one. The boxes are labeled from `1`. Rows and columns are `0`-based numbered from left to right and from top to bottom. # Example For `n=6,r=2,c=2,candy=3`, the result should be `[1,0,1]` the candies will be allocated like this: ``` Box 1 +-----+-----+ | 4 | (3) | --> box 1,row 0, col 1 +-----+-----+ | 2 | 1 | +-----+-----+ Box 2 +-----+-----+ | x | x | +-----+-----+ | 6 | (5) | --> box 2,row 1, col 1 +-----+-----+``` For `candy = 5(n,r,c same as above)`, the output should be `[2,1,1]`. For `candy = 7(n,r,c same as above)`, the output should be `[-1,-1,-1]`. For `n=8,r=4,c=2,candy=3`, the result should be `[1,2,1]` ``` Box 1 +-----+-----+ | 8 | 7 | +-----+-----+ | 6 | 5 | +-----+-----+ | 4 | (3) |--> box 1,row 2, col 1 +-----+-----+ | 2 | 1 | +-----+-----+ ``` # Input/Output - `[input]` integer `n` The number of candies. `0 < n <= 100` - `[input]` integer `r` The number of rows. `0 < r <= 100` - `[input]` integer `c` The number of columns. `0 < c <= 100` - `[input]` integer `candy` The label of the candy Nam wants to get position of. `0 < c <= 120` - `[output]` an integer array Array of 3 elements: a label, a row and a column. Write your solution by modifying this code: ```python def get_candy_position(n, r, c, candy): ``` Your solution should implemented in the function "get_candy_position". 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. Let's call a positive integer extremely round if it has only one non-zero digit. For example, $5000$, $4$, $1$, $10$, $200$ are extremely round integers; $42$, $13$, $666$, $77$, $101$ are not. You are given an integer $n$. You have to calculate the number of extremely round integers $x$ such that $1 \le x \le n$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then, $t$ lines follow. The $i$-th of them contains one integer $n$ ($1 \le n \le 999999$) — the description of the $i$-th test case. -----Output----- For each test case, print one integer — the number of extremely round integers $x$ such that $1 \le x \le n$. -----Examples----- Input 5 9 42 13 100 111 Output 9 13 10 19 19 -----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. Seen from above, there is a grid-like square shaped like Figure 1. The presence or absence of "walls" on each side of this grid is represented by a sequence of 0s and 1s. Create a program that stands at point A, puts your right hand on the wall, keeps walking in the direction of the arrow, and outputs the route to return to point A again. <image> --- Figure 1 --- Input The input consists of 9 lines and is given in the following format, with 1 being the presence of a wall and 0 being the absence of a wall, as shown in Figure 2 below. The first line is a character string that indicates the presence or absence of the top horizontal line wall as 0 and 1 from the left. The second line is a character string that indicates the presence or absence of the vertical line wall below it with 0 and 1 from the left. The third line is a character string that indicates the presence or absence of the wall of the second horizontal line from the top by 0 and 1 from the left. ... The 9th line is a character string representing the presence or absence of the bottom horizontal line wall with 0 and 1 from the left. <image> --- Figure 2 (Thick line shows where the wall is) (corresponding numbers) However, as shown by the thick line in Fig. 1, it is assumed that there is always a wall for one section to the right of point A. That is, the first character on the first line is always 1. Output "Advance one section to the left of the figure" is "L", "Advance one section to the right of the figure" is "R", "Advance one section to the top of the figure" is "U", "Figure" "Advance one block downward" is represented by "D", and "L", "R", "U", and "D" are output in the order of advance. Example Input 1111 00001 0110 01011 0010 01111 0010 01001 0111 Output RRRRDDDDLLLUUURRDDLURULLDDDRRRUUUULLLL Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are $n$ crossroads in the line in the town, and there is either the bus or the tram station at each crossroad. The crossroads are represented as a string $s$ of length $n$, where $s_i = \texttt{A}$, if there is a bus station at $i$-th crossroad, and $s_i = \texttt{B}$, if there is a tram station at $i$-th crossroad. Currently Petya is at the first crossroad (which corresponds to $s_1$) and his goal is to get to the last crossroad (which corresponds to $s_n$). If for two crossroads $i$ and $j$ for all crossroads $i, i+1, \ldots, j-1$ there is a bus station, one can pay $a$ roubles for the bus ticket, and go from $i$-th crossroad to the $j$-th crossroad by the bus (it is not necessary to have a bus station at the $j$-th crossroad). Formally, paying $a$ roubles Petya can go from $i$ to $j$ if $s_t = \texttt{A}$ for all $i \le t < j$. If for two crossroads $i$ and $j$ for all crossroads $i, i+1, \ldots, j-1$ there is a tram station, one can pay $b$ roubles for the tram ticket, and go from $i$-th crossroad to the $j$-th crossroad by the tram (it is not necessary to have a tram station at the $j$-th crossroad). Formally, paying $b$ roubles Petya can go from $i$ to $j$ if $s_t = \texttt{B}$ for all $i \le t < j$. For example, if $s$="AABBBAB", $a=4$ and $b=3$ then Petya needs:[Image] buy one bus ticket to get from $1$ to $3$, buy one tram ticket to get from $3$ to $6$, buy one bus ticket to get from $6$ to $7$. Thus, in total he needs to spend $4+3+4=11$ roubles. Please note that the type of the stop at the last crossroad (i.e. the character $s_n$) does not affect the final expense. Now Petya is at the first crossroad, and he wants to get to the $n$-th crossroad. After the party he has left with $p$ roubles. He's decided to go to some station on foot, and then go to home using only public transport. Help him to choose the closest crossroad $i$ to go on foot the first, so he has enough money to get from the $i$-th crossroad to the $n$-th, using only tram and bus tickets. -----Input----- Each test contains one or more test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The first line of each test case consists of three integers $a, b, p$ ($1 \le a, b, p \le 10^5$) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has. The second line of each test case consists of one string $s$, where $s_i = \texttt{A}$, if there is a bus station at $i$-th crossroad, and $s_i = \texttt{B}$, if there is a tram station at $i$-th crossroad ($2 \le |s| \le 10^5$). It is guaranteed, that the sum of the length of strings $s$ by all test cases in one test doesn't exceed $10^5$. -----Output----- For each test case print one number — the minimal index $i$ of a crossroad Petya should go on foot. The rest of the path (i.e. from $i$ to $n$ he should use public transport). -----Example----- Input 5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB Output 2 1 3 1 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. Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $n$ sub-tracks. You are given an array $a$ where $a_i$ represents the number of traffic cars in the $i$-th sub-track. You define the inconvenience of the track as $\sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert$, where $|x|$ is the absolute value of $x$. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track. Find the minimum inconvenience you can achieve. -----Input----- The first line of input contains a single integer $t$ ($1\leq t\leq 10000$) — the number of test cases. The first line of each test case contains a single integer $n$ ($1\leq n\leq 2\cdot 10^5$). The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0\leq a_i\leq 10^9$). It is guaranteed that the sum of $n$ over all test cases does not exceed $2\cdot 10^5$. -----Output----- For each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times. -----Examples----- Input 3 3 1 2 3 4 0 1 1 0 10 8 3 6 11 5 2 1 7 10 4 Output 0 4 21 -----Note----- For the first test case, you can move a car from the $3$-rd sub-track to the $1$-st sub-track to obtain $0$ inconvenience. For the second test case, moving any car won't decrease the inconvenience of the track. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types: * replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4); * swap any pair of digits in string a. Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task. Input The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105. Output Print on the single line the single number — the minimum number of operations needed to convert string a into string b. Examples Input 47 74 Output 1 Input 774 744 Output 1 Input 777 444 Output 3 Note In the first sample it is enough simply to swap the first and the second digit. In the second sample we should replace the second digit with its opposite. In the third number we should replace all three digits with their opposites. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Little Elephant loves numbers. He has a positive integer x. The Little Elephant wants to find the number of positive integers d, such that d is the divisor of x, and x and d have at least one common (the same) digit in their decimal representations. Help the Little Elephant to find the described number. Input A single line contains a single integer x (1 ≤ x ≤ 109). Output In a single line print an integer — the answer to the problem. Examples Input 1 Output 1 Input 10 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. Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $s = s_1 s_2 \dots s_{n}$ of length $n$ where each letter is either R, S or P. While initializing, the bot is choosing a starting index $pos$ ($1 \le pos \le n$), and then it can play any number of rounds. In the first round, he chooses "Rock", "Scissors" or "Paper" based on the value of $s_{pos}$: if $s_{pos}$ is equal to R the bot chooses "Rock"; if $s_{pos}$ is equal to S the bot chooses "Scissors"; if $s_{pos}$ is equal to P the bot chooses "Paper"; In the second round, the bot's choice is based on the value of $s_{pos + 1}$. In the third round — on $s_{pos + 2}$ and so on. After $s_n$ the bot returns to $s_1$ and continues his game. You plan to play $n$ rounds and you've already figured out the string $s$ but still don't know what is the starting index $pos$. But since the bot's tactic is so boring, you've decided to find $n$ choices to each round to maximize the average number of wins. In other words, let's suggest your choices are $c_1 c_2 \dots c_n$ and if the bot starts from index $pos$ then you'll win in $win(pos)$ rounds. Find $c_1 c_2 \dots c_n$ such that $\frac{win(1) + win(2) + \dots + win(n)}{n}$ is maximum possible. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. Next $t$ lines contain test cases — one per line. The first and only line of each test case contains string $s = s_1 s_2 \dots s_{n}$ ($1 \le n \le 2 \cdot 10^5$; $s_i \in \{\text{R}, \text{S}, \text{P}\}$) — the string of the bot. It's guaranteed that the total length of all strings in one test doesn't exceed $2 \cdot 10^5$. -----Output----- For each test case, print $n$ choices $c_1 c_2 \dots c_n$ to maximize the average number of wins. Print them in the same manner as the string $s$. If there are multiple optimal answers, print any of them. -----Example----- Input 3 RRRR RSP S Output PPPP RSP R -----Note----- In the first test case, the bot (wherever it starts) will always choose "Rock", so we can always choose "Paper". So, in any case, we will win all $n = 4$ rounds, so the average is also equal to $4$. In the second test case: if bot will start from $pos = 1$, then $(s_1, c_1)$ is draw, $(s_2, c_2)$ is draw and $(s_3, c_3)$ is draw, so $win(1) = 0$; if bot will start from $pos = 2$, then $(s_2, c_1)$ is win, $(s_3, c_2)$ is win and $(s_1, c_3)$ is win, so $win(2) = 3$; if bot will start from $pos = 3$, then $(s_3, c_1)$ is lose, $(s_1, c_2)$ is lose and $(s_2, c_3)$ is lose, so $win(3) = 0$; The average is equal to $\frac{0 + 3 + 0}{3} = 1$ and it can be proven that it's the maximum possible average. A picture from Wikipedia explaining "Rock paper scissors" game: $\beta$ Read the inputs from stdin solve the problem and write the answer to stdout (do 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 in Divanovo, a huge river locks system was built. There are now $n$ locks, the $i$-th of them has the volume of $v_i$ liters, so that it can contain any amount of water between $0$ and $v_i$ liters. Each lock has a pipe attached to it. When the pipe is open, $1$ liter of water enters the lock every second. The locks system is built in a way to immediately transfer all water exceeding the volume of the lock $i$ to the lock $i + 1$. If the lock $i + 1$ is also full, water will be transferred further. Water exceeding the volume of the last lock pours out to the river. The picture illustrates $5$ locks with two open pipes at locks $1$ and $3$. Because locks $1$, $3$, and $4$ are already filled, effectively the water goes to locks $2$ and $5$. Note that the volume of the $i$-th lock may be greater than the volume of the $i + 1$-th lock. To make all locks work, you need to completely fill each one of them. The mayor of Divanovo is interested in $q$ independent queries. For each query, suppose that initially all locks are empty and all pipes are closed. Then, some pipes are opened simultaneously. For the $j$-th query the mayor asks you to calculate the minimum number of pipes to open so that all locks are filled no later than after $t_j$ seconds. Please help the mayor to solve this tricky problem and answer his queries. -----Input----- The first lines contains one integer $n$ ($1 \le n \le 200000$) — the number of locks. The second lines contains $n$ integers $v_1, v_2, \dots, v_n$ ($1 \le v_i \le 10^9$)) — volumes of the locks. The third line contains one integer $q$ ($1 \le q \le 200000$) — the number of queries. Each of the next $q$ lines contains one integer $t_j$ ($1 \le t_j \le 10^9$) — the number of seconds you have to fill all the locks in the query $j$. -----Output----- Print $q$ integers. The $j$-th of them should be equal to the minimum number of pipes to turn on so that after $t_j$ seconds all of the locks are filled. If it is impossible to fill all of the locks in given time, print $-1$. -----Examples----- Input 5 4 1 5 4 1 6 1 6 2 3 4 5 Output -1 3 -1 -1 4 3 Input 5 4 4 4 4 4 6 1 3 6 5 2 4 Output -1 -1 4 4 -1 5 -----Note----- There are $6$ queries in the first example test. In the queries $1, 3, 4$ the answer is $-1$. We need to wait $4$ seconds to fill the first lock even if we open all the pipes. In the sixth query we can open pipes in locks $1$, $3$, and $4$. After $4$ seconds the locks $1$ and $4$ are full. In the following $1$ second $1$ liter of water is transferred to the locks $2$ and $5$. The lock $3$ is filled by its own pipe. Similarly, in the second query one can open pipes in locks $1$, $3$, and $4$. In the fifth query one can open pipes $1, 2, 3, 4$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given N items. The value of the i-th item (1 \leq i \leq N) is v_i. Your have to select at least A and at most B of these items. Under this condition, find the maximum possible arithmetic mean of the values of selected items. Additionally, find the number of ways to select items so that the mean of the values of selected items is maximized. -----Constraints----- - 1 \leq N \leq 50 - 1 \leq A,B \leq N - 1 \leq v_i \leq 10^{15} - Each v_i is an integer. -----Input----- The input is given from Standard Input in the following format: N A B v_1 v_2 ... v_N -----Output----- Print two lines. The first line should contain the maximum possible arithmetic mean of the values of selected items. The output should be considered correct if the absolute or relative error is at most 10^{-6}. The second line should contain the number of ways to select items so that the mean of the values of selected items is maximized. -----Sample Input----- 5 2 2 1 2 3 4 5 -----Sample Output----- 4.500000 1 The mean of the values of selected items will be maximized when selecting the fourth and fifth items. Hence, the first line of the output should contain 4.5. There is no other way to select items so that the mean of the values will be 4.5, and thus the second line of the output should contain 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. Pak Chanek plans to build a garage. He wants the garage to consist of a square and a right triangle that are arranged like the following illustration. Define $a$ and $b$ as the lengths of two of the sides in the right triangle as shown in the illustration. An integer $x$ is suitable if and only if we can construct a garage with assigning positive integer values for the lengths $a$ and $b$ ($a<b$) so that the area of the square at the bottom is exactly $x$. As a good friend of Pak Chanek, you are asked to help him find the $N$-th smallest suitable number. -----Input----- The only line contains a single integer $N$ ($1 \leq N \leq 10^9$). -----Output----- An integer that represents the $N$-th smallest suitable number. -----Examples----- Input 3 Output 7 -----Note----- The $3$-rd smallest suitable number is $7$. A square area of $7$ can be obtained by assigning $a=3$ and $b=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. The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits. Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number ri — the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to ri, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points (x1, y1) and (x2, y2) is <image> Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place. The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change. Input The first input line contains coordinates of two opposite table corners xa, ya, xb, yb (xa ≠ xb, ya ≠ yb). The second line contains integer n — the number of radiators (1 ≤ n ≤ 103). Then n lines contain the heaters' coordinates as "xi yi ri", the numbers are separated by spaces. All input data numbers are integers. The absolute value of all coordinates does not exceed 1000, 1 ≤ ri ≤ 1000. Several radiators can be located at the same point. Output Print the only number — the number of blankets you should bring. Examples Input 2 5 4 2 3 3 1 2 5 3 1 1 3 2 Output 4 Input 5 2 6 3 2 6 2 2 6 5 3 Output 0 Note In the first sample the generals are sitting at points: (2, 2), (2, 3), (2, 4), (2, 5), (3, 2), (3, 5), (4, 2), (4, 3), (4, 4), (4, 5). Among them, 4 generals are located outside the heating range. They are the generals at points: (2, 5), (3, 5), (4, 4), (4, 5). In the second sample the generals are sitting at points: (5, 2), (5, 3), (6, 2), (6, 3). All of them are located inside the heating range. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. People in the Tomskaya region like magic formulas very much. You can see some of them below. Imagine you are given a sequence of positive integer numbers p_1, p_2, ..., p_{n}. Lets write down some magic formulas:$q_{i} = p_{i} \oplus(i \operatorname{mod} 1) \oplus(i \operatorname{mod} 2) \oplus \cdots \oplus(i \operatorname{mod} n)$$Q = q_{1} \oplus q_{2} \oplus \ldots \oplus q_{n}$ Here, "mod" means the operation of taking the residue after dividing. The expression $x \oplus y$ means applying the bitwise xor (excluding "OR") operation to integers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal — by "xor". People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence p, calculate the value of Q. -----Input----- The first line of the input contains the only integer n (1 ≤ n ≤ 10^6). The next line contains n integers: p_1, p_2, ..., p_{n} (0 ≤ p_{i} ≤ 2·10^9). -----Output----- The only line of output should contain a single integer — the value of Q. -----Examples----- Input 3 1 2 3 Output 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right. Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other. -----Input----- The first line of the input contains n (1 ≤ n ≤ 200 000) — the number of bishops. Each of next n lines contains two space separated integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ 1000) — the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position. -----Output----- Output one integer — the number of pairs of bishops which attack each other. -----Examples----- Input 5 1 1 1 5 3 3 5 1 5 5 Output 6 Input 3 1 1 2 3 3 5 Output 0 -----Note----- In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you. Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to: 1. dr(n) = S(n), if S(n) < 10; 2. dr(n) = dr( S(n) ), if S(n) ≥ 10. For example, dr(4098) = dr(21) = 3. Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n) = S( S( S( S(n) ) ) ) (n ≤ 101000). Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist. Input The first line contains two integers k and d (1 ≤ k ≤ 1000; 0 ≤ d ≤ 9). Output In a single line print either any number that meets the requirements (without the leading zeroes) or "No solution" (without the quotes), if the corresponding number does not exist. The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes. Examples Input 4 4 Output 5881 Input 5 1 Output 36172 Input 1 0 Output 0 Note For the first test sample dr(5881) = dr(22) = 4. For the second test sample dr(36172) = dr(19) = dr(10) = 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 an array $a$ of $n$ integers. You are asked to find out if the inequality $$\max(a_i, a_{i + 1}, \ldots, a_{j - 1}, a_{j}) \geq a_i + a_{i + 1} + \dots + a_{j - 1} + a_{j}$$ holds for all pairs of indices $(i, j)$, where $1 \leq i \leq j \leq n$. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^5$). Description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the size of the array. The next line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($-10^9 \le a_i \le 10^9$). It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case, on a new line output "YES" if the condition is satisfied for the given array, and "NO" otherwise. You can print each letter in any case (upper or lower). -----Examples----- Input 3 4 -1 1 -1 2 5 -1 2 -3 2 -1 3 2 3 -1 Output YES YES NO -----Note----- In test cases $1$ and $2$, the given condition is satisfied for all $(i, j)$ pairs. In test case $3$, the condition isn't satisfied for the pair $(1, 2)$ as $\max(2, 3) < 2 + 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. Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem. A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit. More formally, if a game designer selected cells having coordinates (x_1, y_1) and (x_2, y_2), where x_1 ≤ x_2 and y_1 ≤ y_2, then all cells having center coordinates (x, y) such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2 will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to OX axis, all hexagon centers have integer coordinates and for each integer x there are cells having center with such x coordinate and for each integer y there are cells having center with such y coordinate. It is guaranteed that difference x_2 - x_1 is divisible by 2. Working on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map. Help him implement counting of these units before painting. [Image] -----Input----- The only line of input contains four integers x_1, y_1, x_2, y_2 ( - 10^9 ≤ x_1 ≤ x_2 ≤ 10^9, - 10^9 ≤ y_1 ≤ y_2 ≤ 10^9) — the coordinates of the centers of two cells. -----Output----- Output one integer — the number of cells to be filled. -----Examples----- Input 1 1 5 5 Output 13 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese, Russian and Vietnamese as well. The Head Chef is receiving a lot of orders for cooking the best of the problems lately. For this, he organized an hiring event to hire some talented Chefs. He gave the following problem to test the skills of the participating Chefs. Can you solve this problem and be eligible for getting hired by Head Chef. A non-negative number n is said to be magical if it satisfies the following property. Let S denote the multi-set of numbers corresponding to the non-empty subsequences of the digits of the number n in decimal representation. Please note that the numbers in the set S can have leading zeros. Let us take an element s of the multi-set S, prod(s) denotes the product of all the digits of number s in decimal representation. The number n will be called magical if sum of prod(s) for all elements s in S, is even. For example, consider a number 246, its all possible non-empty subsequence will be S = {2, 4, 6, 24, 46, 26, 246}. Products of digits of these subsequences will be {prod(2) = 2, prod(4) = 4, prod(6) = 6, prod(24) = 8, prod(46) = 24, prod(26) = 12, prod(246) = 48, i.e. {2, 4, 6, 8, 24, 12, 48}. Sum of all of these is 104, which is even. Hence 246 is a magical number. Please note that multi-set S can contain repeated elements, e.g. if number is 55, then S = {5, 5, 55}. Products of digits of these subsequences will be {prod(5) = 5, prod(5) = 5, prod(55) = 25}, i.e. {5, 5, 25}. Sum of all of these is 35 which is odd. Hence 55 is not a magical number. Consider a number 204, then S = {2, 0, 4, 20, 04, 24, 204}. Products of digits of these subsequences will be {2, 0, 4, 0, 0, 8, 0}. Sum of all these elements will be 14 which is even. So 204 is a magical number. The task was to simply find the K^{th} magical number. ------ Input ------ First line of the input contains an integer T denoting the number of test cases. Each of the next T lines contains a single integer K. ------ Output ------ For each test case, print a single integer corresponding to the K^{th} magical number. ------ Constraints ------ 1 ≤ T ≤ 10^{5} 1 ≤ K ≤ 10^{12}. ------ Subtasks ------ Subtask #1 : (20 points) 1 ≤ T ≤ 100 1 ≤ K ≤ 10^{4}. Subtask 2 : (80 points) Original Constraints ----- Sample Input 1 ------ 2 2 5 ----- Sample Output 1 ------ 2 8 ----- explanation 1 ------ Example case 1. 2 is the 2nd magical number, since it satisfies the property of the magical number. The first magical number will be of course 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. Complete the code which should return `true` if the given object is a single ASCII letter (lower or upper case), `false` otherwise. Write your solution by modifying this code: ```python def is_letter(s): ``` Your solution should implemented in the function "is_letter". 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. It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters. Write your solution by modifying this code: ```python def remove_char(s): ``` Your solution should implemented in the function "remove_char". 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. IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible by any number from 2 to 10 every developer of this game gets a small bonus. A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that n people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it. -----Input----- The only line of the input contains one integer n (1 ≤ n ≤ 10^18) — the prediction on the number of people who will buy the game. -----Output----- Output one integer showing how many numbers from 1 to n are not divisible by any number from 2 to 10. -----Examples----- Input 12 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. The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the king, whose name was Victorious Vasily Pupkin, was always called by the berlanders VVP. In Berland over its long history many dynasties of kings replaced each other, but they were all united by common traditions. Thus, according to one Berland traditions, to maintain stability in the country, the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor). Berlanders appreciate stability, so this tradition has never been broken. Also Berlanders like perfection, so another tradition requires that the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king). This tradition, of course, has also been always observed. The name of a dynasty is formed by very simple rules: we take all the short names of the kings in the order in which they ruled, and write them in one line. Thus, a dynasty of kings "ab" and "ba" is called "abba", and the dynasty, which had only the king "abca", is called "abca". Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland. Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B. Input The first line contains integer n (1 ≤ n ≤ 5·105) — the number of names in Vasya's list. Next n lines contain n abbreviated names, one per line. An abbreviated name is a non-empty sequence of lowercase Latin letters. Its length does not exceed 10 characters. Output Print a single number — length of the sought dynasty's name in letters. If Vasya's list is wrong and no dynasty can be found there, print a single number 0. Examples Input 3 abc ca cba Output 6 Input 4 vvp vvp dam vvp Output 0 Input 3 ab c def Output 1 Note In the first sample two dynasties can exist: the one called "abcca" (with the first and second kings) and the one called "abccba" (with the first and third kings). In the second sample there aren't acceptable dynasties. The only dynasty in the third sample consists of one king, his name is "c". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasiliy has an exam period which will continue for n days. He has to pass exams on m subjects. Subjects are numbered from 1 to m. About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day. On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest. About each subject Vasiliy know a number a_{i} — the number of days he should prepare to pass the exam number i. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during a_{i} days for the exam number i. He can mix the order of preparation for exams in any way. Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time. -----Input----- The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of days in the exam period and the number of subjects. The second line contains n integers d_1, d_2, ..., d_{n} (0 ≤ d_{i} ≤ m), where d_{i} is the number of subject, the exam of which can be passed on the day number i. If d_{i} equals 0, it is not allowed to pass any exams on the day number i. The third line contains m positive integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^5), where a_{i} is the number of days that are needed to prepare before passing the exam on the subject i. -----Output----- Print one integer — the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1. -----Examples----- Input 7 2 0 1 0 2 1 0 2 2 1 Output 5 Input 10 3 0 0 1 2 3 0 2 0 1 2 1 1 4 Output 9 Input 5 1 1 1 1 1 1 5 Output -1 -----Note----- In the first example Vasiliy can behave as follows. On the first and the second day he can prepare for the exam number 1 and pass it on the fifth day, prepare for the exam number 2 on the third day and pass it on the fourth day. In the second example Vasiliy should prepare for the exam number 3 during the first four days and pass it on the fifth day. Then on the sixth day he should prepare for the exam number 2 and then pass it on the seventh day. After that he needs to prepare for the exam number 1 on the eighth day and pass it on the ninth day. In the third example Vasiliy can't pass the only exam because he hasn't anough time to prepare for it. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated? There are $n$ students living in a building, and for each of them the favorite drink $a_i$ is known. So you know $n$ integers $a_1, a_2, \dots, a_n$, where $a_i$ ($1 \le a_i \le k$) is the type of the favorite drink of the $i$-th student. The drink types are numbered from $1$ to $k$. There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $k$ types of drink sets, the $j$-th type contains two portions of the drink $j$. The available number of sets of each of the $k$ types is infinite. You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $\lceil \frac{n}{2} \rceil$, where $\lceil x \rceil$ is $x$ rounded up. After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $n$ is odd then one portion will remain unused and the students' teacher will drink it. What is the maximum number of students that can get their favorite drink if $\lceil \frac{n}{2} \rceil$ sets will be chosen optimally and students will distribute portions between themselves optimally? -----Input----- The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 1\,000$) — the number of students in the building and the number of different drinks. The next $n$ lines contain student's favorite drinks. The $i$-th line contains a single integer from $1$ to $k$ — the type of the favorite drink of the $i$-th student. -----Output----- Print exactly one integer — the maximum number of students that can get a favorite drink. -----Examples----- Input 5 3 1 3 1 1 2 Output 4 Input 10 3 2 1 3 2 3 3 1 3 1 2 Output 9 -----Note----- In the first example, students could choose three sets with drinks $1$, $1$ and $2$ (so they will have two sets with two drinks of the type $1$ each and one set with two drinks of the type $2$, so portions will be $1, 1, 1, 1, 2, 2$). This way all students except the second one will get their favorite drinks. Another possible answer is sets with drinks $1$, $2$ and $3$. In this case the portions will be $1, 1, 2, 2, 3, 3$. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with $a_i = 1$ (i.e. the first, the third or the fourth). Read the inputs from stdin solve the problem and write the answer to stdout (do 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, a junior high school student, is working on his homework. Today's homework is to read Chinese classic texts. As you know, Japanese language shares the (mostly) same Chinese characters but the order of words is a bit different. Therefore the notation called "returning marks" was invented in order to read Chinese classic texts in the order similar to Japanese language. There are two major types of returning marks: 'Re' mark and jump marks. Also there are a couple of jump marks such as one-two-three marks, top-middle-bottom marks. The marks are attached to letters to describe the reading order of each letter in the Chinese classic text. Figure 1 is an example of a Chinese classic text annotated with returning marks, which are the small letters at the bottom-left of the big Chinese letters. <image> Figure 1: a Chinese classic text Taro generalized the concept of jump marks, and summarized the rules to read Chinese classic texts with returning marks as below. Your task is to help Taro by writing a program that interprets Chinese classic texts with returning marks following his rules, and outputs the order of reading of each letter. When two (or more) rules are applicable in each step, the latter in the list below is applied first, then the former. 1. Basically letters are read downwards from top to bottom, i.e. the first letter should be read (or skipped) first, and after the i-th letter is read or skipped, (i + 1)-th letter is read next. 2. Each jump mark has a type (represented with a string consisting of lower-case letters) and a number (represented with a positive integer). A letter with a jump mark whose number is 2 or larger must be skipped. 3. When the i-th letter with a jump mark of type t, number n is read, and when there exists an unread letter L at position less than i that has a jump mark of type t, number n + 1, then L must be read next. If there is no such letter L, the (k + 1)-th letter is read, where k is the index of the most recently read letter with a jump mark of type t, number 1. 4. A letter with a 'Re' mark must be skipped. 5. When the i-th letter is read and (i - 1)-th letter has a 'Re' mark, then (i - 1)-th letter must be read next. 6. No letter may be read twice or more. Once a letter is read, the letter must be skipped in the subsequent steps. 7. If no letter can be read next, finish reading. Let's see the first case of the sample input. We begin reading with the first letter because of the rule 1. However, since the first letter has a jump mark 'onetwo2', we must follow the rule 2 and skip the letter. Therefore the second letter, which has no returning mark, will be read first. Then the third letter will be read. The third letter has a jump mark 'onetwo1', so we must follow rule 3 and read a letter with a jump mark `onetwo2' next, if exists. The first letter has the exact jump mark, so it will be read third. Similarly, the fifth letter is read fourth, and then the sixth letter is read. Although we have two letters which have the same jump mark 'onetwo2', we must not take into account the first letter, which has already been read, and must read the fourth letter. Now we have read all six letters and no letter can be read next, so we finish reading. We have read the second, third, first, fifth, sixth, and fourth letter in this order, so the output is 2 3 1 5 6 4. Input The input contains multiple datasets. Each dataset is given in the following format: N mark1 ... markN N, a positive integer (1 ≤ N ≤ 10,000), means the number of letters in a Chinese classic text. marki denotes returning marks attached to the i-th letter. A 'Re' mark is represented by a single letter, namely, 'v' (quotes for clarity). The description of a jump mark is the simple concatenation of its type, specified by one or more lowercase letter, and a positive integer. Note that each letter has at most one jump mark and at most one 'Re' mark. When the same letter has both types of returning marks, the description of the jump mark comes first, followed by 'v' for the 'Re' mark. You can assume this happens only on the jump marks with the number 1. If the i-th letter has no returning mark, marki is '-' (quotes for clarity). The length of marki never exceeds 20. You may assume that input is well-formed, that is, there is exactly one reading order that follows the rules above. And in the ordering, every letter is read exactly once. You may also assume that the N-th letter does not have 'Re' mark. The input ends when N = 0. Your program must not output anything for this case. Output For each dataset, you should output N lines. The first line should contain the index of the letter which is to be read first, the second line for the letter which is to be read second, and so on. All the indices are 1-based. Example Input 6 onetwo2 - onetwo1 onetwo2 - onetwo1 7 v topbottom2 onetwo2 - onetwo1 topbottom1 - 6 baz2 foo2 baz1v bar2 foo1 bar1 0 Output 2 3 1 5 6 4 4 5 3 6 2 1 7 5 2 6 4 3 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. There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step. He can climb up one or two steps at a time. However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps. How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps? Find the count modulo 1\ 000\ 000\ 007. -----Constraints----- - 1 \leq N \leq 10^5 - 0 \leq M \leq N-1 - 1 \leq a_1 < a_2 < ... < a_M \leq N-1 -----Input----- Input is given from Standard Input in the following format: N M a_1 a_2 . . . a_M -----Output----- Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007. -----Sample Input----- 6 1 3 -----Sample Output----- 4 There are four ways to climb up the stairs, as follows: - 0 \to 1 \to 2 \to 4 \to 5 \to 6 - 0 \to 1 \to 2 \to 4 \to 6 - 0 \to 2 \to 4 \to 5 \to 6 - 0 \to 2 \to 4 \to 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 is a harder version of the problem. In this version, $n \le 50\,000$. There are $n$ distinct points in three-dimensional space numbered from $1$ to $n$. The $i$-th point has coordinates $(x_i, y_i, z_i)$. The number of points $n$ is even. You'd like to remove all $n$ points using a sequence of $\frac{n}{2}$ snaps. In one snap, you can remove any two points $a$ and $b$ that have not been removed yet and form a perfectly balanced pair. A pair of points $a$ and $b$ is perfectly balanced if no other point $c$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $a$ and $b$. Formally, point $c$ lies within the axis-aligned minimum bounding box of points $a$ and $b$ if and only if $\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$, $\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$, and $\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$. Note that the bounding box might be degenerate. Find a way to remove all points in $\frac{n}{2}$ snaps. -----Input----- The first line contains a single integer $n$ ($2 \le n \le 50\,000$; $n$ is even), denoting the number of points. Each of the next $n$ lines contains three integers $x_i$, $y_i$, $z_i$ ($-10^8 \le x_i, y_i, z_i \le 10^8$), denoting the coordinates of the $i$-th point. No two points coincide. -----Output----- Output $\frac{n}{2}$ pairs of integers $a_i, b_i$ ($1 \le a_i, b_i \le n$), denoting the indices of points removed on snap $i$. Every integer between $1$ and $n$, inclusive, must appear in your output exactly once. We can show that it is always possible to remove all points. If there are many solutions, output any of them. -----Examples----- Input 6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0 Output 3 6 5 1 2 4 Input 8 0 1 1 1 0 1 1 1 0 1 1 1 2 2 2 3 2 2 2 3 2 2 2 3 Output 4 5 1 6 2 7 3 8 -----Note----- In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on $z = 0$ plane). Note that order of removing matters: for example, points $5$ and $1$ don't form a perfectly balanced pair initially, but they do after point $3$ is removed. [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not." And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times k, so they got k+1 pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled. In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using 3 cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts. More formally, Sasha wants for the given palindrome s find such minimum k, that you can cut this string into k + 1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. It there is no answer, then print "Impossible" (without quotes). Input The first line contains one string s (1 ≤ |s| ≤ 5 000) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that s is a palindrome. Output Print one integer k — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes). Examples Input nolon Output 2 Input otto Output 1 Input qqqq Output Impossible Input kinnikkinnik Output 1 Note In the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut. In the second example, you can cut the string right in the middle, and swap peaces, so you get toot. In the third example, you can't make a string, that won't be equal to the initial one. In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 not good at hide-and-seek. As soon as you hide, you will find it, and it will be difficult to find the hidden child. My father, who couldn't see it, made an ultra-high performance location search system. You can use it to know exactly where your friends are, including your own. Once you become a demon, you can easily find the hidden child. Taro came up with the idea of ​​further evolving this system and adding a function to judge whether or not he can be seen by the demon. If you can do this, even if you are told "Is it okay", if you are in a visible position, it is "OK", and if you are in an invisible position, it is "Okay". The park I play all the time has cylindrical walls of various sizes. This wall cannot be seen from the outside, nor can it be seen from the inside. If you go inside with a demon, you can see it without another wall. <image> Taro has a good idea, but he is not good at making software. So, your best friend, you, decided to make the software of "Invisible to the Demon Confirmation System" on behalf of Mr. Taro. The walls of the park are fixed, but you need to determine if you can see them for various locations of Taro and the demon. Information on the walls in the park (center coordinates (wx, wy) and radius r) and position information of Taro and the demon (coordinates of Taro's position (tx, ty) and coordinates of the position of the demon (sx, sy)) ) Is input, and create a program that determines whether or not you can see Taro from the demon at that position. If you can see Taro from the demon, output Danger, and if you cannot see it, output Safe. If there is a wall on the line segment connecting the positions of the demon and Taro, it shall not be visible, and neither the demon nor Taro shall be on the wall. Input Given multiple datasets. Each dataset is given in the following format: n wx1 wy1 r1 wx2 wy2 r2 :: wxn wyn rn m tx1 ty1 sx1 sy1 tx2 ty2 sx2 sy2 :: txm tym sxm sym The first line is the number of cylindrical walls n (0 ≤ n ≤ 100), the next n lines are the integers wxi, wyi (0 ≤ wxi, wyi ≤ 255) representing the coordinates of the center of the wall i and the integer ri representing the radius. (1 ≤ ri ≤ 255) is given. The number of position information of Taro-kun and the demon in the following line m (m ≤ 100), and the integers txi, tyi (0 ≤ txi, tyi ≤ 255) and the demon that represent the coordinates of the position of Taro-kun in the position information i in the following line. Given the integers sxi, syi (0 ≤ sxi, syi ≤ 255) that represent the coordinates of the position of. Also, not all of the cylindrical walls are in the park, they are all cylindrical and enter the park. When n is 0, it indicates the end of input. The number of datasets does not exceed 20. Output For each data set, output the judgment result Danger or Safe of the location information i on the i-line. Example Input 3 6 6 3 19 7 4 21 8 1 6 5 4 2 11 12 4 2 11 11 9 2 11 14 3 20 5 17 9 20 5 20 10 20 5 0 Output Safe Safe Danger Safe Danger Safe Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits. Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them. -----Input----- The first line contains the positive integer x (1 ≤ x ≤ 10^18) — the integer which Anton has. -----Output----- Print the positive integer which doesn't exceed x and has the maximum sum of digits. If there are several such integers, print the biggest of them. Printed integer must not contain leading zeros. -----Examples----- Input 100 Output 99 Input 48 Output 48 Input 521 Output 499 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes. Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy. Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more. Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing. -----Input----- The first line contains a sequence of letters without spaces s_1s_2... s_{n} (1 ≤ n ≤ 10^6), consisting of capital English letters M and F. If letter s_{i} equals M, that means that initially, the line had a boy on the i-th position. If letter s_{i} equals F, then initially the line had a girl on the i-th position. -----Output----- Print a single integer — the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0. -----Examples----- Input MFM Output 1 Input MMFF Output 3 Input FFMMM Output 0 -----Note----- In the first test case the sequence of changes looks as follows: MFM → FMM. The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF → MFMF → FMFM → FFMM. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A sequence $(b_1, b_2, \ldots, b_k)$ is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair $(i, j)$ with $1 \le i<j \le k$, we have $|a_i-a_j|\geq MAX$, where $MAX$ is the largest element of the sequence. In particular, any sequence of length at most $1$ is strange. For example, the sequences $(-2021, -1, -1, -1)$ and $(-1, 0, 1)$ are strange, but $(3, 0, 1)$ is not, because $|0 - 1| < 3$. Sifid has an array $a$ of $n$ integers. Sifid likes everything big, so among all the strange subsequences of $a$, he wants to find the length of the longest one. Can you help him? A sequence $c$ is a subsequence of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements. -----Input----- The first line contains an integer $t$ $(1\le t\le 10^4)$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $n$ $(1\le n\le 10^5)$ — the length of the array $a$. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ $(-10^9\le a_i \le 10^9)$ — the elements of the array $a$. It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$. -----Output----- For each test case output a single integer — the length of the longest strange subsequence of $a$. -----Examples----- Input 6 4 -1 -2 0 0 7 -3 4 -2 0 -4 6 1 5 0 5 -3 2 -5 3 2 3 1 4 -3 0 2 0 6 -3 -2 -1 1 1 1 Output 4 5 4 1 3 4 -----Note----- In the first test case, one of the longest strange subsequences is $(a_1, a_2, a_3, a_4)$ In the second test case, one of the longest strange subsequences is $(a_1, a_3, a_4, a_5, a_7)$. In the third test case, one of the longest strange subsequences is $(a_1, a_3, a_4, a_5)$. In the fourth test case, one of the longest strange subsequences is $(a_2)$. In the fifth test case, one of the longest strange subsequences is $(a_1, a_2, a_4)$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given three integers A, B and C. Determine if there exists an equilateral triangle whose sides have lengths A, B and C. Constraints * All values in input are integers. * 1 \leq A,B,C \leq 100 Input Input is given from Standard Input in the following format: A B C Output If there exists an equilateral triangle whose sides have lengths A, B and C, print `Yes`; otherwise, print `No`. Examples Input 2 2 2 Output Yes Input 3 4 5 Output No Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9. Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9. For instance, Inna can alter number 14545181 like this: 14545181 → 1945181 → 194519 → 19919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine. Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task. -----Input----- The first line of the input contains integer a (1 ≤ a ≤ 10^100000). Number a doesn't have any zeroes. -----Output----- In a single line print a single integer — the answer to the problem. It is guaranteed that the answer to the problem doesn't exceed 2^63 - 1. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 369727 Output 2 Input 123456789987654321 Output 1 Input 1 Output 1 -----Note----- Notes to the samples In the first sample Inna can get the following numbers: 369727 → 99727 → 9997, 369727 → 99727 → 9979. In the second sample, Inna can act like this: 123456789987654321 → 12396789987654321 → 1239678998769321. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. I bought food at the store to make a lunch box to eat at lunch. At the store, I only got an elongated bag to put food in, so I had to stack all the food vertically and put it in the bag. I want to pack the bag with the heavy ones down so that it won't fall over, but some foods are soft and will collapse if I put a heavy one on top. Therefore, create a program that inputs food information and outputs the stacking method so that all foods are not crushed and the overall center of gravity is the lowest. For each food, a name f, a weight w, and a weight s that can be placed on top are specified. "All foods are not crushed" means that (f1, f2, ..., fn) and n foods are loaded in order from the bottom, for all fs. sfi ≥ wfi + 1 + wfi + 2 + ... + wfn Means that Also, the overall center of gravity G is G = (1 x wf1 + 2 x wf2 + ... + n x wfn) / (wf1 + wf2 + ... + wfn) will do. However, assume that there is exactly one solution. 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: n f1 w1 s1 f2 w2 s2 :: fn wn sn The number of foods on the first line n (1 ≤ n ≤ 10), the name of the i-th food on the following n lines fi (half-width English character string of up to 20 characters), weight wi (1 ≤ wi ≤ 1000), endurance The weight to be si (1 ≤ si ≤ 1000) is given, separated by spaces. The number of datasets does not exceed 20. Output For each dataset, the food names are output in the following format in the order in which they are stacked from the bottom. 1st line: Name of the food at the bottom (half-width English character string) Line 2: The name of the second food from the bottom : Line n: The name of the top food Example Input 4 sandwich 80 120 apple 50 200 cheese 20 40 cake 100 100 9 onigiri 80 300 onigiri 80 300 anpan 70 280 mikan 50 80 kanzume 100 500 chocolate 50 350 cookie 30 80 purin 40 400 cracker 40 160 0 Output apple cake sandwich cheese kanzume purin chocolate onigiri onigiri anpan mikan cracker cookie Read the inputs from stdin solve the problem and write the answer to stdout (do 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 For the integer n (1 ≤ n), let Pn be a string of n + 1 I's and n O's starting with I and alternating, where I and O are the uppercase Ai and O, respectively. is there. P1 | IOI --- | --- P2 | IOIOI P3 | IOIOIOI |. | |. | |. | Pn | IOIOIO ... OI (n O) Figure 1-1 Character string considered in this question Pn Given the integer n and the string s consisting only of I and O, write a program that outputs how many Pn's are contained in s. input The input consists of multiple datasets. Each dataset is given in the following format. The integer n (1 ≤ n ≤ 1000000) is written on the first line. The second line contains the integer m (1 ≤ m ≤ 1000000). M represents the number of characters in s. The string s is written on the third line. S consists of only I and O. For all scoring data, 2n + 1 ≤ m. Of the scoring data, 50% of the scoring data satisfies n ≤ 100 and m ≤ 10000. When n is 0, it indicates the end of input. The number of datasets does not exceed 10. output For each dataset, print one integer on one line that indicates how many strings Pn are contained in the string s. If s does not contain Pn, print 0 as an integer. Examples Input 1 13 OOIOIOIOIIOII 2 13 OOIOIOIOIIOII 0 Output 4 2 Input None Output 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. Gottfried learned about binary number representation. He then came up with this task and presented it to you. You are given a collection of $n$ non-negative integers $a_1, \ldots, a_n$. You are allowed to perform the following operation: choose two distinct indices $1 \leq i, j \leq n$. If before the operation $a_i = x$, $a_j = y$, then after the operation $a_i = x~\mathsf{AND}~y$, $a_j = x~\mathsf{OR}~y$, where $\mathsf{AND}$ and $\mathsf{OR}$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero). After all operations are done, compute $\sum_{i=1}^n a_i^2$ — the sum of squares of all $a_i$. What is the largest sum of squares you can achieve? -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 2 \cdot 10^5$). The second line contains $n$ integers $a_1, \ldots, a_n$ ($0 \leq a_i < 2^{20}$). -----Output----- Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations. -----Examples----- Input 1 123 Output 15129 Input 3 1 3 5 Output 51 Input 2 349525 699050 Output 1099509530625 -----Note----- In the first sample no operation can be made, thus the answer is $123^2$. In the second sample we can obtain the collection $1, 1, 7$, and $1^2 + 1^2 + 7^2 = 51$. If $x$ and $y$ are represented in binary with equal number of bits (possibly with leading zeros), then each bit of $x~\mathsf{AND}~y$ is set to $1$ if and only if both corresponding bits of $x$ and $y$ are set to $1$. Similarly, each bit of $x~\mathsf{OR}~y$ is set to $1$ if and only if at least one of the corresponding bits of $x$ and $y$ are set to $1$. For example, $x = 3$ and $y = 5$ are represented as $011_2$ and $101_2$ (highest bit first). Then, $x~\mathsf{AND}~y = 001_2 = 1$, and $x~\mathsf{OR}~y = 111_2 = 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 goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given $n$ matrices $M_1, M_2, M_3,...,M_n$. Write a program which reads dimensions of $M_i$, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication $M_1M_2...M_n$. Constraints * $1 \leq n \leq 100$ * $1 \leq r, c \leq 100$ Input In the first line, an integer $n$ is given. In the following $n$ lines, the dimension of matrix $M_i$ ($i = 1...n$) is given by two integers $r$ and $c$ which respectively represents the number of rows and columns of $M_i$. Output Print the minimum number of scalar multiplication in a line. Example Input 6 30 35 35 15 15 5 5 10 10 20 20 25 Output 15125 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Print all subsets of a set $S$, which contains $0, 1, ... n-1$ as elements. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a subset is calculated by bitwise OR of existing elements. Constraints * $1 \leq n \leq 18$ Input The input is given in the following format. $n$ Output Print subsets ordered by their decimal integers. Print a subset in a line in the following format. $d$: $e_0$ $e_1$ ... Print ':' after the integer value $d$, then print elements $e_i$ in the subset in ascending order. Seprate two adjacency elements by a space character. Example Input 4 Output 0: 1: 0 2: 1 3: 0 1 4: 2 5: 0 2 6: 1 2 7: 0 1 2 8: 3 9: 0 3 10: 1 3 11: 0 1 3 12: 2 3 13: 0 2 3 14: 1 2 3 15: 0 1 2 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. # A History Lesson The Pony Express was a mail service operating in the US in 1859-60. It reduced the time for messages to travel between the Atlantic and Pacific coasts to about 10 days, before it was made obsolete by the transcontinental telegraph. # How it worked There were a number of *stations*, where: * The rider switched to a fresh horse and carried on, or * The mail bag was handed over to the next rider # Kata Task `stations` is a list/array of distances (miles) from one station to the next along the Pony Express route. Implement the `riders` method/function, to return how many riders are necessary to get the mail from one end to the other. ## Missing rider In this version of the Kata a rider may go missing. In practice, this could be for a number of reasons - a lame horse, an accidental fall, foul play... After some time, the rider's absence would be noticed at the **next** station, so the next designated rider from there would have to back-track the mail route to look for his missing colleague. The missing rider is then safely escorted back to the station he last came from, and the mail bags are handed to his rescuer (or another substitute rider if necessary). `stationX` is the number (2..N) of the station where the rider's absence was noticed. # Notes * Each rider travels as far as he can, but never more than 100 miles. # Example GIven * `stations = [43, 23, 40, 13]` * `stationX = 4` So `S1` ... ... 43 ... ... `S2` ... ... 23 ... ... `S3` ... ... 40 ... ... `S4` ... ... 13 ... ... `S5` * Rider 1 gets as far as Station S3 * Rider 2 (at station S3) takes mail bags from Rider 1 * Rider 2 never arrives at station S4 * Rider 3 goes back to find what happened to Rider 2 * Rider 2 and Rider 3 return together back to Station S3 * Rider 3 takes mail bags from Rider 2 * Rider 3 completes the journey to Station S5 **Answer:** 3 riders *Good Luck. DM.* --- See also * The Pony Express * The Pony Express (missing rider) Write your solution by modifying this code: ```python def riders(stations, station_x): ``` Your solution should implemented in the function "riders". 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. Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite. -----Input----- Input will consist of a single integer N (1 ≤ N ≤ 10^6), the number of city blocks that must be enclosed by the route. -----Output----- Print the minimum perimeter that can be achieved. -----Examples----- Input 4 Output 8 Input 11 Output 14 Input 22 Output 20 -----Note----- Here are some possible shapes for the examples: [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa. Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him оf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else. At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya. Input The first line contains four integers k, x, n, m (3 ≤ k ≤ 50; 0 ≤ x ≤ 109; 1 ≤ n, m ≤ 100). Output In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them. If the required pair of strings doesn't exist, print "Happy new year!" without the quotes. Examples Input 3 2 2 2 Output AC AC Input 3 3 2 2 Output Happy new year! Input 3 0 2 2 Output AA AA Input 4 3 2 1 Output Happy new year! Input 4 2 2 1 Output Happy new year! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal ($\forall$) and existential ($\exists$). You can read more about them here. The universal quantifier is used to make a claim that a statement holds for all real numbers. For example: $\forall x,x<100$ is read as: for all real numbers $x$, $x$ is less than $100$. This statement is false. $\forall x,x>x-1$ is read as: for all real numbers $x$, $x$ is greater than $x-1$. This statement is true. The existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example: $\exists x,x<100$ is read as: there exists a real number $x$ such that $x$ is less than $100$. This statement is true. $\exists x,x>x-1$ is read as: there exists a real number $x$ such that $x$ is greater than $x-1$. This statement is true. Moreover, these quantifiers can be nested. For example: $\forall x,\exists y,x<y$ is read as: for all real numbers $x$, there exists a real number $y$ such that $x$ is less than $y$. This statement is true since for every $x$, there exists $y=x+1$. $\exists y,\forall x,x<y$ is read as: there exists a real number $y$ such that for all real numbers $x$, $x$ is less than $y$. This statement is false because it claims that there is a maximum real number: a number $y$ larger than every $x$. Note that the order of variables and quantifiers is important for the meaning and veracity of a statement. There are $n$ variables $x_1,x_2,\ldots,x_n$, and you are given some formula of the form $$ f(x_1,\dots,x_n):=(x_{j_1}<x_{k_1})\land (x_{j_2}<x_{k_2})\land \cdots\land (x_{j_m}<x_{k_m}), $$ where $\land$ denotes logical AND. That is, $f(x_1,\ldots, x_n)$ is true if every inequality $x_{j_i}<x_{k_i}$ holds. Otherwise, if at least one inequality does not hold, then $f(x_1,\ldots,x_n)$ is false. Your task is to assign quantifiers $Q_1,\ldots,Q_n$ to either universal ($\forall$) or existential ($\exists$) so that the statement $$ Q_1 x_1, Q_2 x_2, \ldots, Q_n x_n, f(x_1,\ldots, x_n) $$ is true, and the number of universal quantifiers is maximized, or determine that the statement is false for every possible assignment of quantifiers. Note that the order the variables appear in the statement is fixed. For example, if $f(x_1,x_2):=(x_1<x_2)$ then you are not allowed to make $x_2$ appear first and use the statement $\forall x_2,\exists x_1, x_1<x_2$. If you assign $Q_1=\exists$ and $Q_2=\forall$, it will only be interpreted as $\exists x_1,\forall x_2,x_1<x_2$. -----Input----- The first line contains two integers $n$ and $m$ ($2\le n\le 2\cdot 10^5$; $1\le m\le 2\cdot 10^5$) — the number of variables and the number of inequalities in the formula, respectively. The next $m$ lines describe the formula. The $i$-th of these lines contains two integers $j_i$,$k_i$ ($1\le j_i,k_i\le n$, $j_i\ne k_i$). -----Output----- If there is no assignment of quantifiers for which the statement is true, output a single integer $-1$. Otherwise, on the first line output an integer, the maximum possible number of universal quantifiers. On the next line, output a string of length $n$, where the $i$-th character is "A" if $Q_i$ should be a universal quantifier ($\forall$), or "E" if $Q_i$ should be an existential quantifier ($\exists$). All letters should be upper-case. If there are multiple solutions where the number of universal quantifiers is maximum, print any. -----Examples----- Input 2 1 1 2 Output 1 AE Input 4 3 1 2 2 3 3 1 Output -1 Input 3 2 1 3 2 3 Output 2 AAE -----Note----- For the first test, the statement $\forall x_1, \exists x_2, x_1<x_2$ is true. Answers of "EA" and "AA" give false statements. The answer "EE" gives a true statement, but the number of universal quantifiers in this string is less than in our answer. For the second test, we can show that no assignment of quantifiers, for which the statement is true exists. For the third test, the statement $\forall x_1, \forall x_2, \exists x_3, (x_1<x_3)\land (x_2<x_3)$ is true: We can set $x_3=\max\{x_1,x_2\}+1$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Kawashiro Nitori is a girl who loves competitive programming. One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem. Given a string $s$ and a parameter $k$, you need to check if there exist $k+1$ non-empty strings $a_1,a_2...,a_{k+1}$, such that $$s=a_1+a_2+\ldots +a_k+a_{k+1}+R(a_k)+R(a_{k-1})+\ldots+R(a_{1}).$$ Here $+$ represents concatenation. We define $R(x)$ as a reversed string $x$. For example $R(abcd) = dcba$. Note that in the formula above the part $R(a_{k+1})$ is intentionally skipped. -----Input----- The input consists of multiple test cases. The first line contains a single integer $t$ ($1\le t\le 100$) — the number of test cases. The description of the test cases follows. The first line of each test case description contains two integers $n$, $k$ ($1\le n\le 100$, $0\le k\le \lfloor \frac{n}{2} \rfloor$) — the length of the string $s$ and the parameter $k$. The second line of each test case description contains a single string $s$ of length $n$, consisting of lowercase English letters. -----Output----- For each test case, print "YES" (without quotes), if it is possible to find $a_1,a_2,\ldots,a_{k+1}$, and "NO" (without quotes) otherwise. You can print letters in any case (upper or lower). -----Examples----- Input 7 5 1 qwqwq 2 1 ab 3 1 ioi 4 2 icpc 22 0 dokidokiliteratureclub 19 8 imteamshanghaialice 6 3 aaaaaa Output YES NO YES NO YES NO NO -----Note----- In the first test case, one possible solution is $a_1=qw$ and $a_2=q$. In the third test case, one possible solution is $a_1=i$ and $a_2=o$. In the fifth test case, one possible solution is $a_1=dokidokiliteratureclub$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. n of the students use pieces made of two blocks and m of the students use pieces made of three blocks. The students don’t want to use too many blocks, but they also want to be unique, so no two students’ towers may contain the same number of blocks. Find the minimum height necessary for the tallest of the students' towers. -----Input----- The first line of the input contains two space-separated integers n and m (0 ≤ n, m ≤ 1 000 000, n + m > 0) — the number of students using two-block pieces and the number of students using three-block pieces, respectively. -----Output----- Print a single integer, denoting the minimum possible height of the tallest tower. -----Examples----- Input 1 3 Output 9 Input 3 2 Output 8 Input 5 0 Output 10 -----Note----- In the first case, the student using two-block pieces can make a tower of height 4, and the students using three-block pieces can make towers of height 3, 6, and 9 blocks. The tallest tower has a height of 9 blocks. In the second case, the students can make towers of heights 2, 4, and 8 with two-block pieces and towers of heights 3 and 6 with three-block pieces, for a maximum height of 8 blocks. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 contest, AtCoder Beginner Contest, is abbreviated as ABC. When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC. What is the abbreviation for the N-th round of ABC? Write a program to output the answer. -----Constraints----- - 100 ≤ N ≤ 999 -----Input----- Input is given from Standard Input in the following format: N -----Output----- Print the abbreviation for the N-th round of ABC. -----Sample Input----- 100 -----Sample Output----- ABC100 The 100th round of ABC is ABC100. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function. The array values passed in will only be strings or numbers. The only valid return values are `true` and `false`. Examples: ``` solution(1, 2, 3) --> false solution(1, 2, 3, 2) --> true solution('1', '2', '3', '2') --> true ``` Write your solution by modifying this code: ```python def solution(*args): ``` Your solution should implemented in the function "solution". 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. ## Description Given an array X of positive integers, its elements are to be transformed by running the following operation on them as many times as required: ```if X[i] > X[j] then X[i] = X[i] - X[j]``` When no more transformations are possible, return its sum ("smallest possible sum"). For instance, the successive transformation of the elements of input X = [6, 9, 21] is detailed below: ``` X_1 = [6, 9, 12] # -> X_1[2] = X[2] - X[1] = 21 - 9 X_2 = [6, 9, 6] # -> X_2[2] = X_1[2] - X_1[0] = 12 - 6 X_3 = [6, 3, 6] # -> X_3[1] = X_2[1] - X_2[0] = 9 - 6 X_4 = [6, 3, 3] # -> X_4[2] = X_3[2] - X_3[1] = 6 - 3 X_5 = [3, 3, 3] # -> X_5[1] = X_4[0] - X_4[1] = 6 - 3 ``` The returning output is the sum of the final transformation (here 9). ## Example ## Solution steps: ## Additional notes: There are performance tests consisted of very big numbers and arrays of size at least 30000. Please write an efficient algorithm to prevent timeout. Write your solution by modifying this code: ```python def solution(a): ``` Your solution should implemented in the function "solution". 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. Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible. In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line? Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on. Input The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones. The second line contains n space-separated integers, the i-th of which is ci (1 ≤ ci ≤ n) — the color of the i-th gemstone in a line. Output Print a single integer — the minimum number of seconds needed to destroy the entire line. Examples Input 3 1 2 1 Output 1 Input 3 1 2 3 Output 3 Input 7 1 4 4 2 3 2 1 Output 2 Note In the first sample, Genos can destroy the entire line in one second. In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds. In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are n columns of toy cubes in the box arranged in a line. The i-th column contains a_{i} cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange. [Image] Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the n columns after the gravity switch! -----Input----- The first line of input contains an integer n (1 ≤ n ≤ 100), the number of the columns in the box. The next line contains n space-separated integer numbers. The i-th number a_{i} (1 ≤ a_{i} ≤ 100) denotes the number of cubes in the i-th column. -----Output----- Output n integer numbers separated by spaces, where the i-th number is the amount of cubes in the i-th column after the gravity switch. -----Examples----- Input 4 3 2 1 2 Output 1 2 2 3 Input 3 2 3 8 Output 2 3 8 -----Note----- The first example case is shown on the figure. The top cube of the first column falls to the top of the last column; the top cube of the second column falls to the top of the third column; the middle cube of the first column falls to the top of the second column. In the second example case the gravity switch does not change the heights of the columns. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters). So given a string "super", we should return a list of [2, 4]. Some examples: Mmmm => [] Super => [2,4] Apple => [1,5] YoMama -> [1,2,4,6] **NOTES:** * Vowels in this context refers to: a e i o u y (including upper case) * This is indexed from `[1..n]` (not zero indexed!) Write your solution by modifying this code: ```python def vowel_indices(word): ``` Your solution should implemented in the function "vowel_indices". 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. Koa the Koala and her best friend want to play a game. The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts. Let's describe a move in the game: * During his move, a player chooses any element of the array and removes it from this array, xor-ing it with the current score of the player. More formally: if the current score of the player is x and the chosen element is y, his new score will be x ⊕ y. Here ⊕ denotes [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Note that after a move element y is removed from a. * The game ends when the array is empty. At the end of the game the winner is the player with the maximum score. If both players have the same score then it's a draw. If both players play optimally find out whether Koa will win, lose or draw the game. Input Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows. The first line of each test case contains the integer n (1 ≤ n ≤ 10^5) — the length of a. The second line of each test case contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — elements of a. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print: * WIN if Koa will win the game. * LOSE if Koa will lose the game. * DRAW if the game ends in a draw. Examples Input 3 3 1 2 2 3 2 2 3 5 0 0 0 2 2 Output WIN LOSE DRAW Input 4 5 4 1 5 1 3 4 1 0 1 6 1 0 2 5 4 Output WIN WIN DRAW WIN Note In testcase 1 of the first sample we have: a = [1, 2, 2]. Here Koa chooses 1, other player has to choose 2, Koa chooses another 2. Score for Koa is 1 ⊕ 2 = 3 and score for other player is 2 so Koa wins. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.