question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a. Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen with the same probability), after which the winner is the player, whose number was closer to c. The boys agreed that if m and a are located on the same distance from c, Misha wins. Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number n. You need to determine which value of a Andrew must choose, so that the probability of his victory is the highest possible. More formally, you need to find such integer a (1 ≤ a ≤ n), that the probability that $|c - a|<|c - m|$ is maximal, where c is the equiprobably chosen integer from 1 to n (inclusive). -----Input----- The first line contains two integers n and m (1 ≤ m ≤ n ≤ 10^9) — the range of numbers in the game, and the number selected by Misha respectively. -----Output----- Print a single number — such value a, that probability that Andrew wins is the highest. If there are multiple such values, print the minimum of them. -----Examples----- Input 3 1 Output 2 Input 4 3 Output 2 -----Note----- In the first sample test: Andrew wins if c is equal to 2 or 3. The probability that Andrew wins is 2 / 3. If Andrew chooses a = 3, the probability of winning will be 1 / 3. If a = 1, the probability of winning is 0. In the second sample test: Andrew wins if c is equal to 1 and 2. The probability that Andrew wins is 1 / 2. For other choices of a the probability of winning is less. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Define a method that accepts 2 strings as parameters. The method returns the first string sorted by the second. ```python sort_string("foos", "of") == "oofs" sort_string("string", "gnirts") == "gnirts" sort_string("banana", "abn") == "aaabnn" ``` To elaborate, the second string defines the ordering. It is possible that in the second string characters repeat, so you should remove repeating characters, leaving only the first occurrence. Any character in the first string that does not appear in the second string should be sorted to the end of the result in original 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. Nathan O. Davis is trying to capture a game and struggling to get a very rare item. This rare item can be obtained by arranging special patterns in a row on a casino slot machine. The slot machine has N reels, and pressing the button once stops the currently rotating leftmost reel. Therefore, you need to press the button N times to get this rare item. Also, in order to stop with a special pattern, it is necessary to press the button at a certain timing. However, the timing of pressing this button was very severe, so I was in trouble because it didn't go well. Therefore, Nathan decided to analyze the game while checking the memory value during the game using the memory viewer. As a result of Nathan's analysis, in order to stop the reel with that special pattern, the "random number" written at address 007E0D1F in the memory must have a specific value when the button is pressed. I found out. It was also found that the value of the random number changes every frame by the linear congruential method, and whether or not the button is pressed is judged once every frame. Here, the linear congruential method is one of the methods for generating pseudo-random numbers, and the value is determined by the following formula. x'= (A x x + B) mod C Here, x is the value of the current random number, x'is the value of the next random number, and A, B, and C are some constants. Also, y mod z represents the remainder when y is divided by z. For example, suppose a slot machine with two reels has A = 5, B = 7, C = 11 and the first "random number" value is 10. And, the condition for stopping the reel with a special pattern is that the reel on the left side is 2 and the reel on the right side is 4. At this time, the value of the random number in the first frame is (5 × 10 + 7) mod 11 = 2, so if you press the button in the first frame, the reel on the left side will stop with a special pattern. Since the value of the random number in the second frame that follows is (5 x 2 + 7) mod 11 = 6, the reel on the right side does not stop with a special pattern even if the button is pressed in the second frame. In the following 3rd frame, the random number value becomes (5 x 6 + 7) mod 11 = 4, so if you press the button in the 3rd frame, the reel on the right side will stop with a special pattern. Therefore, all reels can be stopped with a special pattern in a minimum of 3 frames, and rare items can be obtained. Your job is to help Nathan get a rare item by writing a program that asks how many frames in the shortest frame all reels can be stopped with a special pattern. .. Input The input consists of multiple datasets. Each dataset is given in the following format. > N A B C X > Y1 Y2 ... YN The first row contains five integers N (1 ≤ N ≤ 100), A, B (0 ≤ A, B ≤ 10,000), C (1 ≤ C ≤ 10,000), and X (0 ≤ X <C), respectively. It is given separated by two whitespace characters. Here, X represents the value of the first random number. On the following line, N integers Y1, Y2, ..., YN (0 ≤ Yi ≤ 10,000) are given, separated by a single space character. These represent the conditions for stopping the reel with a specific pattern, and the i-th number Yi is the random number value Yi to stop the i-th reel from the left with a special pattern. It means that there must be. The end of the input is indicated by a single line containing five zeros separated by blanks. Output For each dataset, output the shortest number of frames required to stop at a special pattern on one line. If it cannot be stopped within 10,000 frames, output -1 instead of the number of frames. The output must not contain extra blanks or line breaks. Sample Input 1 5 7 11 10 Ten 2 5 7 11 10 twenty four 2 1 1 256 0 128 255 2 0 0 1 0 1 2 3 4 5 6 7 8 2 1 1 100 0 99 98 2 1 1 100 0 99 99 2 1 1 10000 0 Ten 2 1 1 10000 0 twenty one 0 0 0 0 0 Output for the Sample Input 0 3 255 -1 198 199 10000 -1 Example Input 1 5 7 11 10 10 2 5 7 11 10 2 4 2 1 1 256 0 128 255 2 0 0 1 0 1234 5678 2 1 1 100 0 99 98 2 1 1 100 0 99 99 2 1 1 10000 0 1 0 2 1 1 10000 0 2 1 0 0 0 0 0 Output 0 3 255 -1 198 199 10000 -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given the list of numbers, you are to sort them in non decreasing order. -----Input----- t – the number of numbers in list, then t lines follow [t <= 10^6]. Each line contains one integer: N [0 <= N <= 10^6] -----Output----- Output given numbers in non decreasing order. -----Example----- Input: 5 5 3 6 7 1 Output: 1 3 5 6 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. To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation: - 1 yen (the currency of Japan) - 6 yen, 6^2(=36) yen, 6^3(=216) yen, ... - 9 yen, 9^2(=81) yen, 9^3(=729) yen, ... At least how many operations are required to withdraw exactly N yen in total? It is not allowed to re-deposit the money you withdrew. -----Constraints----- - 1 \leq N \leq 100000 - N is an integer. -----Input----- Input is given from Standard Input in the following format: N -----Output----- If at least x operations are required to withdraw exactly N yen in total, print x. -----Sample Input----- 127 -----Sample Output----- 4 By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively. In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge. Output Print the diameter of the tree in a line. Examples Input 4 0 1 2 1 2 1 1 3 3 Output 5 Input 4 0 1 1 1 2 2 2 3 4 Output 7 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier. He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though. Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious. Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it. Write a program that outputs delicious if he found it delicious, safe if he did not found it delicious but did not get a stomachache either, and dangerous if he got a stomachache. -----Constraints----- - 1 ≤ X,A,B ≤ 10^9 -----Input----- Input is given from Standard Input in the following format: X A B -----Output----- Print delicious if Takahashi found the food delicious; print safe if he neither found it delicious nor got a stomachache; print dangerous if he got a stomachache. -----Sample Input----- 4 3 6 -----Sample Output----- safe He ate the food three days after the "best-by" date. It was not delicious or harmful for him. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 dynamic array $A = \\{a_0, a_1, ...\\}$ of integers, perform a sequence of the following operations: * pushBack($x$): add element $x$ at the end of $A$ * randomAccess($p$):print element $a_p$ * popBack(): delete the last element of $A$ $A$ is a 0-origin array and it is empty in the initial state. Constraints * $1 \leq q \leq 200,000$ * $0 \leq p < $ the size of $A$ * $-1,000,000,000 \leq x \leq 1,000,000,000$ Input The input is given in the following format. $q$ $query_1$ $query_2$ : $query_q$ Each query $query_i$ is given by 0 $x$ or 1 $p$ or 2 where the first digits 0, 1 and 2 represent pushBack, randomAccess and popBack operations respectively. randomAccess and popBack operations will not be given for an empty array. Output For each randomAccess, print $a_p$ in a line. Example Input 8 0 1 0 2 0 3 2 0 4 1 0 1 1 1 2 Output 1 2 4 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. Roman has no idea, why this problem is called Stone. He also has no idea on how to solve the followong problem: given array of N integers A and a number K. During a turn the maximal value over all A_{i} is chosen, let's call it MAX. Then A_{i} = MAX - A_{i} is done for every 1 ≤ i ≤ N. Help Roman to find out how will the array look like after K turns. ------ Input ------ The numbers N and K are given in the first line of an input. Then N integers are given in the second line which denote the array A. ------ Output ------ Output N numbers on a single line. It should be the array A after K turns. ------ Constraints ------ $1 ≤ N ≤ 10^{5}$ $0 ≤ K ≤ 10^{9}$ $A_{i} does not exceed 2 * 10^{9} by it's absolute value.$ ----- Sample Input 1 ------ 4 1 5 -1 7 0 ----- Sample Output 1 ------ 2 8 0 7 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ekiden competitions are held every year in Aizukuni. The country of Aiz is dotted with N towns, each numbered from 1 to N. Several towns are connected by roads that allow them to come and go directly to each other. You can also follow several roads between any town. The course of the tournament is decided as follows. * Find the shortest path distance for all combinations of the two towns. * Of these, the two towns that maximize the distance of the shortest route are the start town and the goal town. If there are multiple town combinations, choose one of them. * The shortest route between the chosen starting town and the goal town will be the course of the tournament. If there are multiple shortest paths, choose one of them. Tokuitsu, a monk from Yamato, wants to open a new temple in the quietest possible town in Aiz. Therefore, I want to know a town that is unlikely to be used for the course of the relay race. When given information on the roads connecting the towns of Aiz, create a program to find towns that are unlikely to be used for the relay race course. Input The input is given in the following format. N R s1 t1 d1 s2 t2 d2 :: sR tR dR The first line gives the number of towns N (2 ≤ N ≤ 1500) and the number of roads directly connecting the towns R (1 ≤ R ≤ 3000). The following R line is given a way to connect the two towns directly in both directions. si and ti (1 ≤ si <ti ≤ N) represent the numbers of the two towns connected by the i-th road, and di (1 ≤ di ≤ 1000) represents the length of the road. However, in any of the two towns, there should be at most one road connecting them directly. Output For the given road information, output all the towns that will not be the course of the relay race. The first line outputs the number M of towns that will not be the course of the relay race. Print such town numbers in ascending order on the following M line. Examples Input 4 5 1 2 2 1 3 2 2 3 1 2 4 2 3 4 1 Output 1 2 Input 7 11 1 2 2 1 3 1 2 4 2 2 5 2 2 6 1 3 4 1 3 5 1 3 6 1 4 7 2 5 7 2 6 7 1 Output 3 2 4 5 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a program that prints a chessboard with N rows and M columns with the following rules: The top left cell must be an asterisk (*) Any cell touching (left, right, up or down) a cell with an asterisk must be a dot (.) Any cell touching (left, right, up or down) a cell with a dot must be an asterisk. A chessboard of 8 rows and 8 columns printed using these rules would be: ``` *.*.*.*. .*.*.*.* *.*.*.*. .*.*.*.* *.*.*.*. .*.*.*.* *.*.*.*. .*.*.*.* ``` Input A single line with two integers N and M separated by space. The number N will represent the number of rows and M the number of columns. Output Return N lines each containing M characters with the chessboard pattern. Empty string if N, M or both are 0. From: 2016 AIPO National Finals http://aipo.computing.dcu.ie/2016-aipo-national-finals-problems Read the inputs from stdin solve the problem and write the answer to stdout (do 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 got a magic matrix a of size n × m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column. Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element. After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it. Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to √{(i_1-i_2)^2 + (j_1-j_2)^2}. Calculate the expected value of the Vasya's final score. It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q not≡ 0~(mod ~ 998244353). Print the value P ⋅ Q^{-1} modulo 998244353. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 1 000) — the number of rows and the number of columns in the matrix a. The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 ≤ a_{ij} ≤ 10^9). The following line contains two integers r and c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — the index of row and the index of column where the chip is now. Output Print the expected value of Vasya's final score in the format described in the problem statement. Examples Input 1 4 1 1 2 1 1 3 Output 2 Input 2 3 1 5 7 2 3 1 1 2 Output 665496238 Note In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i. Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square). He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits. Find the maximum possible sum of the values of items he picks up. -----Constraints----- - 1 \leq R, C \leq 3000 - 1 \leq K \leq \min(2 \times 10^5, R \times C) - 1 \leq r_i \leq R - 1 \leq c_i \leq C - (r_i, c_i) \neq (r_j, c_j) (i \neq j) - 1 \leq v_i \leq 10^9 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: R C K r_1 c_1 v_1 r_2 c_2 v_2 : r_K c_K v_K -----Output----- Print the maximum possible sum of the values of items Takahashi picks up. -----Sample Input----- 2 2 3 1 1 3 2 1 4 1 2 5 -----Sample Output----- 8 He has two ways to get to the goal: - Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8. - Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7. Thus, the maximum possible sum of the values of items he picks up is 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. You are given a grid with 2 rows and 3 columns of squares. The color of the square at the i-th row and j-th column is represented by the character C_{ij}. Write a program that prints YES if this grid remains the same when rotated 180 degrees, and prints NO otherwise. -----Constraints----- - C_{i,j}(1 \leq i \leq 2, 1 \leq j \leq 3) is a lowercase English letter. -----Input----- Input is given from Standard Input in the following format: C_{11}C_{12}C_{13} C_{21}C_{22}C_{23} -----Output----- Print YES if this grid remains the same when rotated 180 degrees; print NO otherwise. -----Sample Input----- pot top -----Sample Output----- YES This grid remains the same when rotated 180 degrees. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. To satisfy his love of matching socks, Phoenix has brought his $n$ socks ($n$ is even) to the sock store. Each of his socks has a color $c_i$ and is either a left sock or right sock. Phoenix can pay one dollar to the sock store to either: recolor a sock to any color $c'$ $(1 \le c' \le n)$ turn a left sock into a right sock turn a right sock into a left sock The sock store may perform each of these changes any number of times. Note that the color of a left sock doesn't change when it turns into a right sock, and vice versa. A matching pair of socks is a left and right sock with the same color. What is the minimum cost for Phoenix to make $n/2$ matching pairs? Each sock must be included in exactly one matching pair. -----Input----- The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases. The first line of each test case contains three integers $n$, $l$, and $r$ ($2 \le n \le 2 \cdot 10^5$; $n$ is even; $0 \le l, r \le n$; $l+r=n$) — the total number of socks, and the number of left and right socks, respectively. The next line contains $n$ integers $c_i$ ($1 \le c_i \le n$) — the colors of the socks. The first $l$ socks are left socks, while the next $r$ socks are right socks. It is guaranteed that the sum of $n$ across all the test cases will not exceed $2 \cdot 10^5$. -----Output----- For each test case, print one integer — the minimum cost for Phoenix to make $n/2$ matching pairs. Each sock must be included in exactly one matching pair. -----Examples----- Input 4 6 3 3 1 2 3 2 2 2 6 2 4 1 1 2 2 2 2 6 5 1 6 5 4 3 2 1 4 0 4 4 4 4 3 Output 2 3 5 3 -----Note----- In the first test case, Phoenix can pay $2$ dollars to: recolor sock $1$ to color $2$ recolor sock $3$ to color $2$ There are now $3$ matching pairs. For example, pairs $(1, 4)$, $(2, 5)$, and $(3, 6)$ are matching. In the second test case, Phoenix can pay $3$ dollars to: turn sock $6$ from a right sock to a left sock recolor sock $3$ to color $1$ recolor sock $4$ to color $1$ There are now $3$ matching pairs. For example, pairs $(1, 3)$, $(2, 4)$, and $(5, 6)$ are matching. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In the good old Hachioji railroad station located in the west of Tokyo, there are several parking lines, and lots of freight trains come and go every day. All freight trains travel at night, so these trains containing various types of cars are settled in your parking lines early in the morning. Then, during the daytime, you must reorganize cars in these trains according to the request of the railroad clients, so that every line contains the “right” train, i.e. the right number of cars of the right types, in the right order. As shown in Figure 7, all parking lines run in the East-West direction. There are exchange lines connecting them through which you can move cars. An exchange line connects two ends of different parking lines. Note that an end of a parking line can be connected to many ends of other lines. Also note that an exchange line may connect the East-end of a parking line and the West-end of another. <image> Cars of the same type are not discriminated between each other. The cars are symmetric, so directions of cars don’t matter either. You can divide a train at an arbitrary position to make two sub-trains and move one of them through an exchange line connected to the end of its side. Alternatively, you may move a whole train as is without dividing it. Anyway, when a (sub-) train arrives at the destination parking line and the line already has another train in it, they are coupled to form a longer train. Your superautomatic train organization system can do these without any help of locomotive engines. Due to the limitation of the system, trains cannot stay on exchange lines; when you start moving a (sub-) train, it must arrive at the destination parking line before moving another train. In what follows, a letter represents a car type and a train is expressed as a sequence of letters. For example in Figure 8, from an initial state having a train "aabbccdee" on line 0 and no trains on other lines, you can make "bbaadeecc" on line 2 with the four moves shown in the figure. <image> To cut the cost out, your boss wants to minimize the number of (sub-) train movements. For example, in the case of Figure 8, the number of movements is 4 and this is the minimum. Given the configurations of the train cars in the morning (arrival state) and evening (departure state), your job is to write a program to find the optimal train reconfiguration plan. Input The input consists of one or more datasets. A dataset has the following format: x y p1 P1 q1 Q1 p2 P2 q2 Q2 . . . py Py qy Qy s0 s1 . . . sx-1 t0 t1 . . . tx-1 x is the number of parking lines, which are numbered from 0 to x-1. y is the number of exchange lines. Then y lines of the exchange line data follow, each describing two ends connected by the exchange line; pi and qi are integers between 0 and x - 1 which indicate parking line numbers, and Pi and Qi are either "E" (East) or "W" (West) which indicate the ends of the parking lines. Then x lines of the arrival (initial) configuration data, s0, ... , sx-1, and x lines of the departure (target) configuration data, t0, ... tx-1, follow. Each of these lines contains one or more lowercase letters "a", "b", ..., "z", which indicate types of cars of the train in the corresponding parking line, in west to east order, or alternatively, a single "-" when the parking line is empty. You may assume that x does not exceed 4, the total number of cars contained in all the trains does not exceed 10, and every parking line has sufficient length to park all the cars. You may also assume that each dataset has at least one solution and that the minimum number of moves is between one and six, inclusive. Two zeros in a line indicate the end of the input. Output For each dataset, output the number of moves for an optimal reconfiguration plan, in a separate line. Example Input 3 5 0W 1W 0W 2W 0W 2E 0E 1E 1E 2E aabbccdee - - - - bbaadeecc 3 3 0E 1W 1E 2W 2E 0W aabb bbcc aa bbbb cc aaaa 3 4 0E 1W 0E 2E 1E 2W 2E 0W ababab - - aaabbb - - 0 0 Output 4 2 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. Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people. But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him. Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that: * the number of different users online did not exceed M at any moment, * at some second the number of distinct users online reached value M, * the total number of users (the number of distinct identifiers) was as much as possible. Help Polycarpus cope with the test. Input The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59). Output In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes). Examples Input 4 2 10 17:05:53 17:05:58 17:06:01 22:39:47 Output 3 1 2 2 3 Input 1 2 86400 00:00:00 Output No solution Note Consider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56. In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.) Read the inputs from stdin solve the problem and write the answer to stdout (do 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 decided to make a Christmas Tree for the Christmas party in AtCoder, Inc. A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i. He would like to make one as follows: * Specify two non-negative integers A and B. * Prepare A Christmas Paths whose lengths are at most B. Here, a Christmas Path of length X is a graph with X+1 vertices and X edges such that, if we properly number the vertices 1 through X+1, the i-th edge (1\leq i\leq X) will connect Vertex i and i+1. * Repeat the following operation until he has one connected tree: * Select two vertices x and y that belong to different connected components. Combine x and y into one vertex. More precisely, for each edge (p,y) incident to the vertex y, add the edge (p,x). Then, delete the vertex y and all the edges incident to y. * Properly number the vertices in the tree. Takahashi would like to find the lexicographically smallest pair (A,B) such that he can make a Christmas Tree, that is, find the smallest A, and find the smallest B under the condition that A is minimized. Solve this problem for him. Constraints * 2 \leq N \leq 10^5 * 1 \leq a_i,b_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output For the lexicographically smallest (A,B), print A and B with a space in between. Examples Input 7 1 2 2 3 2 4 4 5 4 6 6 7 Output 3 2 Input 8 1 2 2 3 3 4 4 5 5 6 5 7 5 8 Output 2 5 Input 10 1 2 2 3 3 4 2 5 6 5 6 7 7 8 5 9 10 5 Output 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. Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided to upsolve the following problem: You have an array $a$ with $n$ integers. You need to count the number of funny pairs $(l, r)$ $(l \leq r)$. To check if a pair $(l, r)$ is a funny pair, take $mid = \frac{l + r - 1}{2}$, then if $r - l + 1$ is an even number and $a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$, then the pair is funny. In other words, $\oplus$ of elements of the left half of the subarray from $l$ to $r$ should be equal to $\oplus$ of elements of the right half. Note that $\oplus$ denotes the bitwise XOR operation. It is time to continue solving the contest, so Sasha asked you to solve this task. -----Input----- The first line contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the size of the array. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i < 2^{20}$) — array itself. -----Output----- Print one integer — the number of funny pairs. You should consider only pairs where $r - l + 1$ is even number. -----Examples----- Input 5 1 2 3 4 5 Output 1 Input 6 3 2 2 3 7 6 Output 3 Input 3 42 4 2 Output 0 -----Note----- Be as cool as Sasha, upsolve problems! In the first example, the only funny pair is $(2, 5)$, as $2 \oplus 3 = 4 \oplus 5 = 1$. In the second example, funny pairs are $(2, 3)$, $(1, 4)$, and $(3, 6)$. In the third example, there are no funny pairs. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Laura really hates people using acronyms in her office and wants to force her colleagues to remove all acronyms before emailing her. She wants you to build a system that will edit out all known acronyms or else will notify the sender if unknown acronyms are present. Any combination of three or more letters in upper case will be considered an acronym. Acronyms will not be combined with lowercase letters, such as in the case of 'KPIs'. They will be kept isolated as a word/words within a string. For any string: All instances of 'KPI' must become "key performance indicators" All instances of 'EOD' must become "the end of the day" All instances of 'TBD' must become "to be decided" All instances of 'WAH' must become "work at home" All instances of 'IAM' must become "in a meeting" All instances of 'OOO' must become "out of office" All instances of 'NRN' must become "no reply necessary" All instances of 'CTA' must become "call to action" All instances of 'SWOT' must become "strengths, weaknesses, opportunities and threats" If there are any unknown acronyms in the string, Laura wants you to return only the message: '[acronym] is an acronym. I do not like acronyms. Please remove them from your email.' So if the acronym in question was 'BRB', you would return the string: 'BRB is an acronym. I do not like acronyms. Please remove them from your email.' If there is more than one unknown acronym in the string, return only the first in your answer. If all acronyms can be replaced with full words according to the above, however, return only the altered string. If this is the case, ensure that sentences still start with capital letters. '!' or '?' will not be used. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You've got two rectangular tables with sizes na × ma and nb × mb cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the i-th row and the j-th column, as ai, j; we will define the element of the second table, located at the intersection of the i-th row and the j-th column, as bi, j. We will call the pair of integers (x, y) a shift of the second table relative to the first one. We'll call the overlap factor of the shift (x, y) value: <image> where the variables i, j take only such values, in which the expression ai, j·bi + x, j + y makes sense. More formally, inequalities 1 ≤ i ≤ na, 1 ≤ j ≤ ma, 1 ≤ i + x ≤ nb, 1 ≤ j + y ≤ mb must hold. If there are no values of variables i, j, that satisfy the given inequalities, the value of the sum is considered equal to 0. Your task is to find the shift with the maximum overlap factor among all possible shifts. Input The first line contains two space-separated integers na, ma (1 ≤ na, ma ≤ 50) — the number of rows and columns in the first table. Then na lines contain ma characters each — the elements of the first table. Each character is either a "0", or a "1". The next line contains two space-separated integers nb, mb (1 ≤ nb, mb ≤ 50) — the number of rows and columns in the second table. Then follow the elements of the second table in the format, similar to the first table. It is guaranteed that the first table has at least one number "1". It is guaranteed that the second table has at least one number "1". Output Print two space-separated integers x, y (|x|, |y| ≤ 109) — a shift with maximum overlap factor. If there are multiple solutions, print any of them. Examples Input 3 2 01 10 00 2 3 001 111 Output 0 1 Input 3 3 000 010 000 1 1 1 Output -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. A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer. Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards. He is allowed to at most once discard two or three cards with the same number. Of course, he won't discard cards if it's impossible to choose two or three cards with the same number. Given five numbers written on cards, cay you find the minimum sum of numbers on remaining cards? -----Input----- The only line of the input contains five integers t_1, t_2, t_3, t_4 and t_5 (1 ≤ t_{i} ≤ 100) — numbers written on cards. -----Output----- Print the minimum possible sum of numbers written on remaining cards. -----Examples----- Input 7 3 7 3 20 Output 26 Input 7 9 3 1 8 Output 28 Input 10 10 10 10 10 Output 20 -----Note----- In the first sample, Limak has cards with numbers 7, 3, 7, 3 and 20. Limak can do one of the following. Do nothing and the sum would be 7 + 3 + 7 + 3 + 20 = 40. Remove two cards with a number 7. The remaining sum would be 3 + 3 + 20 = 26. Remove two cards with a number 3. The remaining sum would be 7 + 7 + 20 = 34. You are asked to minimize the sum so the answer is 26. In the second sample, it's impossible to find two or three cards with the same number. Hence, Limak does nothing and the sum is 7 + 9 + 1 + 3 + 8 = 28. In the third sample, all cards have the same number. It's optimal to discard any three cards. The sum of two remaining numbers is 10 + 10 = 20. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters. Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name. Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of clubs in the league. Each of the next n lines contains two words — the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. -----Output----- It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. -----Examples----- Input 2 DINAMO BYTECITY FOOTBALL MOSCOW Output YES DIN FOO Input 2 DINAMO BYTECITY DINAMO BITECITY Output NO Input 3 PLAYFOOTBALL MOSCOW PLAYVOLLEYBALL SPB GOGO TECHNOCUP Output YES PLM PLS GOG Input 3 ABC DEF ABC EFG ABD OOO Output YES ABD ABE ABO -----Note----- In the first sample Innokenty can choose first option for both clubs. In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs. In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club. In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 calculates the *least common multiple* of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return `1`. ~~~if:objc NOTE: The first (and only named) argument of the function `n` specifies the number of arguments in the variable-argument list. Do **not** take `n` into account when computing the LCM of the numbers. ~~~ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections such that the total number of the letters in the word(s) of the first section is five, that of the second is seven, and those of the rest are five, seven, and seven, respectively. The following is an example of a Short Phrase. > > do the best > and enjoy today > at acm icpc > In this example, the sequence of the nine words can be divided into five sections (1) "do" and "the", (2) "best" and "and", (3) "enjoy", (4) "today" and "at", and (5) "acm" and "icpc" such that they have 5, 7, 5, 7, and 7 letters in this order, respectively. This surely satisfies the condition of a Short Phrase. Now, Short Phrase Parnassus published by your company has received a lot of contributions. By an unfortunate accident, however, some irrelevant texts seem to be added at beginnings and ends of contributed Short Phrases. Your mission is to write a program that finds the Short Phrase from a sequence of words that may have an irrelevant prefix and/or a suffix. Input The input consists of multiple datasets, each in the following format. > n > w1 > ... > wn > Here, n is the number of words, which is a positive integer not exceeding 40; wi is the i-th word, consisting solely of lowercase letters from 'a' to 'z'. The length of each word is between 1 and 10, inclusive. You can assume that every dataset includes a Short Phrase. The end of the input is indicated by a line with a single zero. Output For each dataset, output a single line containing i where the first word of the Short Phrase is wi. When multiple Short Phrases occur in the dataset, you should output the first one. Sample Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output for the Sample Input 1 2 6 Example Input 9 do the best and enjoy today at acm icpc 14 oh yes by far it is wow so bad to me you know hey 15 abcde fghijkl mnopq rstuvwx yzz abcde fghijkl mnopq rstuvwx yz abcde fghijkl mnopq rstuvwx yz 0 Output 1 2 6 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You will receive 5 points for solving this problem. Manao has invented a new operation on strings that is called folding. Each fold happens between a pair of consecutive letters and places the second part of the string above first part, running in the opposite direction and aligned to the position of the fold. Using this operation, Manao converts the string into a structure that has one more level than there were fold operations performed. See the following examples for clarity. We will denote the positions of folds with '|' characters. For example, the word "ABRACADABRA" written as "AB|RACA|DAB|RA" indicates that it has been folded three times: first, between the leftmost pair of 'B' and 'R' letters; second, between 'A' and 'D'; and third, between the rightmost pair of 'B' and 'R' letters. Here are several examples of folded strings: "ABCDEF|GHIJK" | "A|BCDEFGHIJK" | "AB|RACA|DAB|RA" | "X|XXXXX|X|X|XXXXXX" | | | XXXXXX KJIHG | KJIHGFEDCB | AR | X ABCDEF | A | DAB | X | | ACAR | XXXXX | | AB | X One last example for "ABCD|EFGH|IJ|K": K IJ HGFE ABCD Manao noticed that each folded string can be viewed as several piles of letters. For instance, in the previous example, there are four piles, which can be read as "AHI", "BGJK", "CF", and "DE" from bottom to top. Manao wonders what is the highest pile of identical letters he can build using fold operations on a given word. Note that the pile should not contain gaps and should start at the bottom level. For example, in the rightmost of the four examples above, none of the piles would be considered valid since each of them has gaps, starts above the bottom level, or both. -----Input----- The input will consist of one line containing a single string of n characters with 1 ≤ n ≤ 1000 and no spaces. All characters of the string will be uppercase letters. This problem doesn't have subproblems. You will get 5 points for the correct submission. -----Output----- Print a single integer — the size of the largest pile composed of identical characters that can be seen in a valid result of folding operations on the given string. -----Examples----- Input ABRACADABRA Output 3 Input ABBBCBDB Output 3 Input AB Output 1 -----Note----- Consider the first example. Manao can create a pile of three 'A's using the folding "AB|RACAD|ABRA", which results in the following structure: ABRA DACAR AB In the second example, Manao can create a pile of three 'B's using the following folding: "AB|BB|CBDB". CBDB BB AB Another way for Manao to create a pile of three 'B's with "ABBBCBDB" is the following folding: "AB|B|BCBDB". BCBDB B AB In the third example, there are no folds performed and the string is just written in one line. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a n × m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle). Input The first line contains two positive integer numbers n and m (1 ≤ n, m ≤ 1000). The following n lines consist of m characters each, describing the field. Only '.' and '*' are allowed. Output Output a single number — total number of square triangles in the field. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 2 2 ** *. Output 1 Input 3 4 *..* .**. *.** Output 9 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order. The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d]. You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls. Input The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 106). Each character in s will be either "l" or "r". Output Output n lines — on the i-th line you should print the i-th stone's number from the left. Examples Input llrlr Output 3 5 4 2 1 Input rrlll Output 1 2 5 4 3 Input lrlrr Output 2 4 5 3 1 Note In the first example, the positions of stones 1, 2, 3, 4, 5 will be <image>, respectively. So you should print the sequence: 3, 5, 4, 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. There is an empty array. The following N operations will be performed to insert integers into the array. In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array. Find the K-th smallest integer in the array after the N operations. For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3. -----Constraints----- - 1≤N≤10^5 - 1≤a_i,b_i≤10^5 - 1≤K≤b_1…+…b_n - All input values are integers. -----Input----- Input is given from Standard Input in the following format: N K a_1 b_1 : a_N b_N -----Output----- Print the K-th smallest integer in the array after the N operations. -----Sample Input----- 3 4 1 1 2 2 3 3 -----Sample Output----- 3 The resulting array is the same as the one in the problem statement. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a string q. A sequence of k strings s_1, s_2, ..., s_{k} is called beautiful, if the concatenation of these strings is string q (formally, s_1 + s_2 + ... + s_{k} = q) and the first characters of these strings are distinct. Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist. -----Input----- The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence. The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive. -----Output----- If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s_1, s_2, ..., s_{k}. If there are multiple possible answers, print any of them. -----Examples----- Input 1 abca Output YES abca Input 2 aaacas Output YES aaa cas Input 4 abc Output NO -----Note----- In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two integers $a$ and $m$. Calculate the number of integers $x$ such that $0 \le x < m$ and $\gcd(a, m) = \gcd(a + x, m)$. Note: $\gcd(a, b)$ is the greatest common divisor of $a$ and $b$. -----Input----- The first line contains the single integer $T$ ($1 \le T \le 50$) — the number of test cases. Next $T$ lines contain test cases — one per line. Each line contains two integers $a$ and $m$ ($1 \le a < m \le 10^{10}$). -----Output----- Print $T$ integers — one per test case. For each test case print the number of appropriate $x$-s. -----Example----- Input 3 4 9 5 10 42 9999999967 Output 6 1 9999999966 -----Note----- In the first test case appropriate $x$-s are $[0, 1, 3, 4, 6, 7]$. In the second test case the only appropriate $x$ is $0$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor. Heidi figured out that Madame Kovarian uses a very complicated hashing function in order to change the names of the babies she steals. In order to prevent this from happening to future Doctors, Heidi decided to prepare herself by learning some basic hashing techniques. The first hashing function she designed is as follows. Given two positive integers $(x, y)$ she defines $H(x,y):=x^2+2xy+x+1$. Now, Heidi wonders if the function is reversible. That is, given a positive integer $r$, can you find a pair $(x, y)$ (of positive integers) such that $H(x, y) = r$? If multiple such pairs exist, output the one with smallest possible $x$. If there is no such pair, output "NO". -----Input----- The first and only line contains an integer $r$ ($1 \le r \le 10^{12}$). -----Output----- Output integers $x, y$ such that $H(x,y) = r$ and $x$ is smallest possible, or "NO" if no such pair exists. -----Examples----- Input 19 Output 1 8 Input 16 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. There are $n$ benches in the Berland Central park. It is known that $a_i$ people are currently sitting on the $i$-th bench. Another $m$ people are coming to the park and each of them is going to have a seat on some bench out of $n$ available. Let $k$ be the maximum number of people sitting on one bench after additional $m$ people came to the park. Calculate the minimum possible $k$ and the maximum possible $k$. Nobody leaves the taken seat during the whole process. -----Input----- The first line contains a single integer $n$ $(1 \le n \le 100)$ — the number of benches in the park. The second line contains a single integer $m$ $(1 \le m \le 10\,000)$ — the number of people additionally coming to the park. Each of the next $n$ lines contains a single integer $a_i$ $(1 \le a_i \le 100)$ — the initial number of people on the $i$-th bench. -----Output----- Print the minimum possible $k$ and the maximum possible $k$, where $k$ is the maximum number of people sitting on one bench after additional $m$ people came to the park. -----Examples----- Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 -----Note----- In the first example, each of four benches is occupied by a single person. The minimum $k$ is $3$. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum $k$ is $7$. That requires all six new people to occupy the same bench. The second example has its minimum $k$ equal to $15$ and maximum $k$ equal to $15$, as there is just a single bench in the park and all $10$ people will occupy 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. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost a_{i} Egyptian pounds. If Sagheer buys k items with indices x_1, x_2, ..., x_{k}, then the cost of item x_{j} is a_{x}_{j} + x_{j}·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? -----Input----- The first line contains two integers n and S (1 ≤ n ≤ 10^5 and 1 ≤ S ≤ 10^9) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5) — the base costs of the souvenirs. -----Output----- On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. -----Examples----- Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 -----Note----- In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy 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. There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state). You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A). You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007. Input The first line of input will contain two integers n, m (3 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000). The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 ≤ ai, bi ≤ n, ai ≠ bi, <image>). Each pair of people will be described no more than once. Output Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007. Examples Input 3 0 Output 4 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 0 Output 1 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 1 Output 0 Note In the first sample, the four ways are to: * Make everyone love each other * Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Bob is playing a game named "Walk on Matrix". In this game, player is given an n × m matrix A=(a_{i,j}), i.e. the element in the i-th row in the j-th column is a_{i,j}. Initially, player is located at position (1,1) with score a_{1,1}. To reach the goal, position (n,m), player can move right or down, i.e. move from (x,y) to (x,y+1) or (x+1,y), as long as player is still on the matrix. However, each move changes player's score to the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of the current score and the value at the position he moves to. Bob can't wait to find out the maximum score he can get using the tool he recently learnt — dynamic programming. Here is his algorithm for this problem. <image> However, he suddenly realize that the algorithm above fails to output the maximum score for some matrix A. Thus, for any given non-negative integer k, he wants to find out an n × m matrix A=(a_{i,j}) such that * 1 ≤ n,m ≤ 500 (as Bob hates large matrix); * 0 ≤ a_{i,j} ≤ 3 ⋅ 10^5 for all 1 ≤ i≤ n,1 ≤ j≤ m (as Bob hates large numbers); * the difference between the maximum score he can get and the output of his algorithm is exactly k. It can be shown that for any given integer k such that 0 ≤ k ≤ 10^5, there exists a matrix satisfying the above constraints. Please help him with it! Input The only line of the input contains one single integer k (0 ≤ k ≤ 10^5). Output Output two integers n, m (1 ≤ n,m ≤ 500) in the first line, representing the size of the matrix. Then output n lines with m integers in each line, a_{i,j} in the (i+1)-th row, j-th column. Examples Input 0 Output 1 1 300000 Input 1 Output 3 4 7 3 3 1 4 8 3 6 7 7 7 3 Note In the first example, the maximum score Bob can achieve is 300000, while the output of his algorithm is 300000. In the second example, the maximum score Bob can achieve is 7\&3\&3\&3\&7\&3=3, while the output of his algorithm is 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Petya loves looking for numbers' divisors. One day Petya came across the following problem: You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him. Input The first line contains an integer n (1 ≤ n ≤ 105). Each of the following n lines contain two space-separated integers xi and yi (1 ≤ xi ≤ 105, 0 ≤ yi ≤ i - 1, where i is the query's ordinal number; the numeration starts with 1). If yi = 0 for the query, then the answer to the query will be the number of divisors of the number xi. In this case you do not need to take the previous numbers x into consideration. Output For each query print the answer on a single line: the number of positive integers k such that <image> Examples Input 6 4 0 3 1 5 2 6 2 18 4 10000 3 Output 3 1 1 2 2 22 Note Let's write out the divisors that give answers for the first 5 queries: 1) 1, 2, 4 2) 3 3) 5 4) 2, 6 5) 9, 18 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. Once Chef decided to divide the tangerine into several parts. At first, he numbered tangerine's segments from 1 to n in the clockwise order starting from some segment. Then he intended to divide the fruit into several parts. In order to do it he planned to separate the neighbouring segments in k places, so that he could get k parts: the 1^{st} - from segment l_{1} to segment r_{1} (inclusive), the 2^{nd} - from l_{2} to r_{2}, ..., the k^{th} - from l_{k} to r_{k} (in all cases in the clockwise order). Suddenly, when Chef was absent, one naughty boy came and divided the tangerine into p parts (also by separating the neighbouring segments one from another): the 1^{st} - from segment a_{1} to segment b_{1}, the 2^{nd} - from a_{2} to b_{2}, ..., the p^{th} - from a_{p} to b_{p} (in all cases in the clockwise order). Chef became very angry about it! But maybe little boy haven't done anything wrong, maybe everything is OK? Please, help Chef to determine whether he is able to obtain the parts he wanted to have (in order to do it he can divide p current parts, but, of course, he can't join several parts into one). Please, note that parts are not cyclic. That means that even if the tangerine division consists of only one part, but that part include more than one segment, there are two segments which were neighbouring in the initial tangerine but are not neighbouring in the division. See the explanation of example case 2 to ensure you understood that clarification. ------ Input ------ The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains three space separated integers n, k, p, denoting the number of tangerine's segments and number of parts in each of the two divisions. The next k lines contain pairs of space-separated integers l_{i} and r_{i}. The next p lines contain pairs of space-separated integers a_{i} and b_{i}. It is guaranteed that each tangerine's segment is contained in exactly one of the first k parts and in exactly one of the next p parts. ------ Output ------ For each test case, output a single line containing either "Yes" or "No" (without the quotes), denoting whether Chef is able to obtain the parts he wanted to have.   ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ n ≤ 5 * 10^{7}$ $1 ≤ k ≤ min(500, n)$ $1 ≤ p ≤ min(500, n)$ $1 ≤ l_{i}, r_{i}, a_{i}, b_{i} ≤ n$   ----- Sample Input 1 ------ 2 10 3 2 1 4 5 5 6 10 1 5 6 10 10 3 1 2 5 10 1 6 9 1 10 ----- Sample Output 1 ------ Yes No ----- explanation 1 ------ Example case 1: To achieve his goal Chef should divide the first part (1-5) in two by separating segments 4 and 5 one from another. Example case 2: The boy didn't left the tangerine as it was (though you may thought that way), he separated segments 1 and 10 one from another. But segments 1 and 10 are in one part in Chef's division, so he is unable to achieve his goal. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n × m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a × b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible. Input The first line contains two integers n and m (1 ≤ n, m ≤ 50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1 ≤ a, b ≤ 50). Note that Vasya can choose for building an a × b rectangle as well a b × a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m. Output Print the minimum number of trees that needs to be chopped off to select a land lot a × b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a ≤ n and b ≤ m, or a ≤ m и b ≤ n. Examples Input 2 2 1 0 1 1 1 1 Output 0 Input 4 5 0 0 1 0 1 0 1 1 1 0 1 0 1 0 1 1 1 1 1 1 2 3 Output 2 Note In the second example the upper left square is (1,1) and the lower right is (3,2). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In this Kata, you will be given two positive integers `a` and `b` and your task will be to apply the following operations: ``` i) If a = 0 or b = 0, return [a,b]. Otherwise, go to step (ii); ii) If a ≥ 2*b, set a = a - 2*b, and repeat step (i). Otherwise, go to step (iii); iii) If b ≥ 2*a, set b = b - 2*a, and repeat step (i). Otherwise, return [a,b]. ``` `a` and `b` will both be lower than 10E8. More examples in tests cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a string $s$ of length $n$, which consists only of the first $k$ letters of the Latin alphabet. All letters in string $s$ are uppercase. A subsequence of string $s$ is a string that can be derived from $s$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not. A subsequence of $s$ called good if the number of occurences of each of the first $k$ letters of the alphabet is the same. Find the length of the longest good subsequence of $s$. -----Input----- The first line of the input contains integers $n$ ($1\le n \le 10^5$) and $k$ ($1 \le k \le 26$). The second line of the input contains the string $s$ of length $n$. String $s$ only contains uppercase letters from 'A' to the $k$-th letter of Latin alphabet. -----Output----- Print the only integer — the length of the longest good subsequence of string $s$. -----Examples----- Input 9 3 ACAABCCAB Output 6 Input 9 4 ABCABCABC Output 0 -----Note----- In the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length. In the second example, none of the subsequences can have 'D', hence the answer is $0$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Chef talks a lot on his mobile phone. As a result he exhausts his talk-value (in Rokdas) very quickly. One day at a mobile recharge shop, he noticed that his service provider gives add-on plans which can lower his calling rates (Rokdas/minute). One of the plans said "Recharge for 28 Rokdas and enjoy call rates of 0.50 Rokdas/min for one month". Chef was very pleased. His normal calling rate is 1 Rokda/min. And he talked for 200 minutes in last month, which costed him 200 Rokdas. If he had this plan activated, it would have costed him: 28 + 0.5*200 = 128 Rokdas only! Chef could have saved 72 Rokdas. But if he pays for this add-on and talks for very little in the coming month, he may end up saving nothing or even wasting money. Now, Chef is a simple guy and he doesn't worry much about future. He decides to choose the plan based upon his last month’s usage. There are numerous plans. Some for 1 month, some for 15 months. Some reduce call rate to 0.75 Rokdas/min, some reduce it to 0.60 Rokdas/min. And of course each of them differ in their activation costs. Note - If a plan is valid for M months, then we must pay for (re)activation after every M months (once in M months). Naturally, Chef is confused, and you (as always) are given the task to help him choose the best plan. ------ Input ------ First line contains T- the number of test cases. In each test case, first line contains D- the default rate (Rokdas/minute, real number), U- the number of minutes Chef talked in last month and N- the number of add-on plans available. Then N lines follow, each containing M- the number of months the plan is valid for, R- the calling rate for the plan (Rokdas/minute, real number) and C- the cost of the plan. ------ Output ------ For each test case, output one integer- the number of the best plan (from 1 to N). Output '0' if no plan is advantageous for Chef. No two plans are equally advantageous. ------ Constraints ------ 1 ≤ T ≤ 100 0.5 ≤ D ≤ 10.0 (exactly 2 digits after the decimal point) 1 ≤ U ≤ 10000 1 ≤ N ≤ 100 1 ≤ M ≤ 36 0.05 ≤ R < D (exactly 2 digits after the decimal point) 1 ≤ C ≤ 1000 ----- Sample Input 1 ------ 4 1.00 200 1 1 0.50 28 1.00 200 2 1 0.75 40 3 0.60 100 1.00 50 2 1 0.75 40 3 0.60 100 1.00 100 2 3 0.50 10 2 0.10 20 ----- Sample Output 1 ------ 1 2 0 2 ----- explanation 1 ------ Test Case 1: This test case is same as the example in the problem statement.Test Case 2: This is for you to work out!Test Case 3: Chef's monthly usage is only 50 Rokdas and none of the 2 plans are advantageous, hence the answer is zero '0'.Test Case 4: Again solve it yourself, but NOTE - if Chef had chosen plan 1, he would have to pay 10 Rokdas (Activation cost), after every 3 months and NOT every month. Similarly had he chosen plan 2, he would have to pay 20 Rokdas (Activation cost), after every 2 months. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left. The square (i, j) has two numbers A_{ij} and B_{ij} written on it. First, for each square, Takahashi paints one of the written numbers red and the other blue. Then, he travels from the square (1, 1) to the square (H, W). In one move, he can move from a square (i, j) to the square (i+1, j) or the square (i, j+1). He must not leave the grid. Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares (1, 1) and (H, W). Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it. Find the minimum unbalancedness possible. -----Constraints----- - 2 \leq H \leq 80 - 2 \leq W \leq 80 - 0 \leq A_{ij} \leq 80 - 0 \leq B_{ij} \leq 80 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: H W A_{11} A_{12} \ldots A_{1W} : A_{H1} A_{H2} \ldots A_{HW} B_{11} B_{12} \ldots B_{1W} : B_{H1} B_{H2} \ldots B_{HW} -----Output----- Print the minimum unbalancedness possible. -----Sample Input----- 2 2 1 2 3 4 3 4 2 1 -----Sample Output----- 0 By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are 3+3+1=7 and 1+2+4=7, respectively, for the unbalancedness of 0. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In Morse code, an letter of English alphabet is represented as a string of some length from $1$ to $4$. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1". Because there are $2^1+2^2+2^3+2^4 = 30$ strings with length $1$ to $4$ containing only "0" and/or "1", not all of them correspond to one of the $26$ English letters. In particular, each string of "0" and/or "1" of length at most $4$ translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111". You will work with a string $S$, which is initially empty. For $m$ times, either a dot or a dash will be appended to $S$, one at a time. Your task is to find and report, after each of these modifications to string $S$, the number of non-empty sequences of English letters that are represented with some substring of $S$ in Morse code. Since the answers can be incredibly tremendous, print them modulo $10^9 + 7$. -----Input----- The first line contains an integer $m$ ($1 \leq m \leq 3\,000$) — the number of modifications to $S$. Each of the next $m$ lines contains either a "0" (representing a dot) or a "1" (representing a dash), specifying which character should be appended to $S$. -----Output----- Print $m$ lines, the $i$-th of which being the answer after the $i$-th modification to $S$. -----Examples----- Input 3 1 1 1 Output 1 3 7 Input 5 1 0 1 0 1 Output 1 4 10 22 43 Input 9 1 1 0 0 0 1 1 0 1 Output 1 3 10 24 51 109 213 421 833 -----Note----- Let us consider the first sample after all characters have been appended to $S$, so S is "111". As you can see, "1", "11", and "111" all correspond to some distinct English letter. In fact, they are translated into a 'T', an 'M', and an 'O', respectively. All non-empty sequences of English letters that are represented with some substring of $S$ in Morse code, therefore, are as follows. "T" (translates into "1") "M" (translates into "11") "O" (translates into "111") "TT" (translates into "11") "TM" (translates into "111") "MT" (translates into "111") "TTT" (translates into "111") Although unnecessary for this task, a conversion table from English alphabets into Morse code can be found here. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Create a program that reads the attendance numbers of students in a class and the data that stores the ABO blood group and outputs the number of people for each blood type. There are four types of ABO blood types: A, B, AB, and O. Input A comma-separated pair of attendance numbers and blood types is given over multiple lines. The attendance number is an integer between 1 and 50, and the blood type is one of the strings "A", "B", "AB" or "O". The number of students does not exceed 50. Output Number of people of type A on the first line Number of people of type B on the second line Number of people of AB type on the 3rd line Number of O-shaped people on the 4th line Is output. Example Input 1,B 2,A 3,B 4,AB 5,B 6,O 7,A 8,O 9,AB 10,A 11,A 12,B 13,AB 14,A Output 5 4 3 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Complete the function to determine the number of bits required to convert integer `A` to integer `B` (where `A` and `B` >= 0) The upper limit for `A` and `B` is 2^(16), `int.MaxValue` or similar. For example, you can change 31 to 14 by flipping the 4th and 0th bit: ``` 31 0 0 0 1 1 1 1 1 14 0 0 0 0 1 1 1 0 --- --------------- bit 7 6 5 4 3 2 1 0 ``` Thus `31` and `14` should return `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. ## Witamy! You are in Poland and want to order a drink. You need to ask "One beer please": "Jedno piwo poprosze" ``` java Translator.orderingBeers(1) = "Jedno piwo poprosze" ``` But let's say you are really thirsty and want several beers. Then you need to count in Polish. And more difficult, you need to understand the Polish grammar and cases (nominative, genitive, accustative and more). ## The grammar In English, the plural of "beer" is simply "beers", with an "s". In Polish, the plural of "piwo" (nominative singular) is "piw" (genitive plural) or "piwa" (nominative plural). It depends! The rules: * usually the plural is genitive: "piw" * but after the numerals 2, 3, 4, and compound numbers ending with them (e.g. 22, 23, 24), the noun is plural and takes the same case as the numeral, so nominative: "piwa" * and exception to the exception: for 12, 13 and 14, it's the genitive plural again: "piw" (yes, I know, it's crazy!) ## The numbers From 0 to 9: "zero", "jeden", "dwa", "trzy", "cztery", "piec", "szesc" , "siedem", "osiem", "dziewiec" From 10 to 19 it's nearly the same, with "-ascie" at the end: "dziesiec", "jedenascie", "dwanascie", "trzynascie", "czternascie", "pietnascie", "szesnascie", "siedemnascie", "osiemnascie", "dziewietnascie" Tens from 10 to 90 are nearly the same, with "-ziesci" or "ziesiat" at the end: "dziesiec", "dwadziescia", "trzydziesci", "czterdziesci", "piecdziesiat", "szescdziesiat", "siedemdziesiat", "osiemdziesiat", "dziewiecdziesiat" Compound numbers are constructed similarly to English: tens + units. For example, 22 is "dwadziescia dwa". "One" could be male ("Jeden"), female ("Jedna") or neuter ("Jedno"), which is the case for "beer" (piwo). But all other numbers are invariant, even if ending with "jeden". Ah, and by the way, if you don't want to drink alcohol (so no beers are ordered), ask for mineral water instead: "Woda mineralna". Note: if the number of beers is outside your (limited) Polish knowledge (0-99), raise an error! --- More about the crazy polish grammar: https://en.wikipedia.org/wiki/Polish_grammar Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Problem statement Meatishi can increase or decrease the number of fingers. There are n buns in front of Nikunishi-kun. Meatishi is trying to count the number of steamed buns by breaking his finger. There are only two shapes that Nishikun's fingers can take, whether they are broken or not. Nikunishi understands binary numbers. Nikunishi-kun can count numbers by associating each finger with a binary digit. Nikunishi doesn't understand the logarithm. Find the minimum number of fingers needed to count the buns instead of Nishikun. input n Constraint * An integer * 0 ≤ n ≤ 1018 output Print the answer on one line, and print a newline at the end. sample Sample input 1 0 Sample output 1 0 Sample input 2 Four Sample output 2 3 Sample input 3 31 Sample output 3 Five Sample input 4 36028797018963968 Sample output 4 56 Example Input 0 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. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. $\left. \begin{array}{l}{\text{Rey}} \\{\text{to my}} \\{\text{heart}} \end{array} \right.$ Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a_1, a_2, ..., a_{k} such that $n = \prod_{i = 1}^{k} a_{i}$ in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that $\operatorname{gcd}(p, q) = 1$, where $gcd$ is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 10^9 + 7. Please note that we want $gcd$ of p and q to be 1, not $gcd$ of their remainders after dividing by 10^9 + 7. -----Input----- The first line of input contains a single integer k (1 ≤ k ≤ 10^5) — the number of elements in array Barney gave you. The second line contains k integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ 10^18) — the elements of the array. -----Output----- In the only line of output print a single string x / y where x is the remainder of dividing p by 10^9 + 7 and y is the remainder of dividing q by 10^9 + 7. -----Examples----- Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/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 an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development. For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph. Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output. 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 c1 c2 :: cn The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9). The number of datasets does not exceed 20. Output For each input dataset, the number of sales is output in numerical order of each ice cream type. Example Input 15 2 6 7 0 1 9 8 7 3 8 9 4 8 2 2 3 9 1 5 0 Output * * *** * * - * ** *** ** - * - - - * - - - * Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square. For a given string $s$ determine if it is square. -----Input----- The first line of input data contains an integer $t$ ($1 \le t \le 100$) —the number of test cases. This is followed by $t$ lines, each containing a description of one test case. The given strings consist only of lowercase Latin letters and have lengths between $1$ and $100$ inclusive. -----Output----- For each test case, output on a separate line: YES if the string in the corresponding test case is square, NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response). -----Examples----- Input 10 a aa aaa aaaa abab abcabc abacaba xxyy xyyx xyxy Output NO YES NO YES YES YES NO NO NO YES -----Note----- None Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have to write two methods to *encrypt* and *decrypt* strings. Both methods have two parameters: ``` 1. The string to encrypt/decrypt 2. The Qwerty-Encryption-Key (000-999) ``` The rules are very easy: ``` The crypting-regions are these 3 lines from your keyboard: 1. "qwertyuiop" 2. "asdfghjkl" 3. "zxcvbnm,." If a char of the string is not in any of these regions, take the char direct in the output. If a char of the string is in one of these regions: Move it by the part of the key in the region and take this char at the position from the region. If the movement is over the length of the region, continue at the beginning. The encrypted char must have the same case like the decrypted char! So for upperCase-chars the regions are the same, but with pressed "SHIFT"! The Encryption-Key is an integer number from 000 to 999. E.g.: 127 The first digit of the key (e.g. 1) is the movement for the first line. The second digit of the key (e.g. 2) is the movement for the second line. The third digit of the key (e.g. 7) is the movement for the third line. (Consider that the key is an integer! When you got a 0 this would mean 000. A 1 would mean 001. And so on.) ``` You do not need to do any prechecks. The strings will always be not null and will always have a length > 0. You do not have to throw any exceptions. An Example: ``` Encrypt "Ball" with key 134 1. "B" is in the third region line. Move per 4 places in the region. -> ">" (Also "upperCase"!) 2. "a" is in the second region line. Move per 3 places in the region. -> "f" 3. "l" is in the second region line. Move per 3 places in the region. -> "d" 4. "l" is in the second region line. Move per 3 places in the region. -> "d" --> Output would be ">fdd" ``` *Hint: Don't forget: The regions are from an US-Keyboard!* *In doubt google for "US Keyboard."* This kata is part of the Simple Encryption Series: Simple Encryption #1 - Alternating Split Simple Encryption #2 - Index-Difference Simple Encryption #3 - Turn The Bits Around Simple Encryption #4 - Qwerty Have fun coding it and please don't forget to vote and rank this kata! :-) Read the inputs from stdin solve the problem and write the answer to stdout (do 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, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one. Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task. -----Input----- The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p_1, then coin located at position p_2 and so on. Coins are numbered from left to right. -----Output----- Print n + 1 numbers a_0, a_1, ..., a_{n}, where a_0 is a hardness of ordering at the beginning, a_1 is a hardness of ordering after the first replacement and so on. -----Examples----- Input 4 1 3 4 2 Output 1 2 3 2 1 Input 8 6 8 3 4 7 2 1 5 Output 1 2 2 3 4 3 4 5 1 -----Note----- Let's denote as O coin out of circulation, and as X — coin is circulation. At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges. After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process. XOOO → OOOX After replacement of the third coin, Dima's actions look this way: XOXO → OXOX → OOXX After replacement of the fourth coin, Dima's actions look this way: XOXX → OXXX Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes. Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe x_{i}. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg. The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather. -----Input----- The first line of input contains three space-separated integers, a, b and c (1 ≤ b < a < c ≤ 10^9), denoting the positions of Oleg, the first security guard and the second security guard, respectively. The next line of input contains a single integer n (1 ≤ n ≤ 10^5), denoting the number of banknotes. The next line of input contains n space-separated integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^9), denoting that the i-th banknote is located in the x_{i}-th safe. Note that x_{i} are not guaranteed to be distinct. -----Output----- Output a single integer: the maximum number of banknotes Oleg can take. -----Examples----- Input 5 3 7 8 4 7 5 5 3 6 2 8 Output 4 Input 6 5 7 5 1 5 7 92 3 Output 0 -----Note----- In the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes. For the second sample, Oleg can't take any banknotes without bumping into any of the security guards. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sheldon Cooper, Leonard Hofstadter and Penny decide to go for drinks at Cheese cake factory. Sheldon proposes to make a game out of this. Sheldon proposes as follows, To decide the amount of beverage they plan to consume, say X. Then order for a random number of different drinks, say {A, B, C, D, E, F} of quantities {a, b, c, d, e, f} respectively. If quantity of any three drinks add up to X then we'll have it else we'll return the order. E.g. If a + d + f = X then True else False. You are given Number of bottles N corresponding to different beverages and hence their sizes. Next line contains the size of bottles present in string format. Last line consists of an integer value, denoted by X above. Your task is to help find out if there can be any combination of three beverage sizes that can sum up to the quantity they intend to consume. If such a combination is possible print True else False Input Format First line contains number of bottles ordered denoted by N. Next line contains the size of bottles(a) present in string format. Last line contains the quantity they intend to consume denoted by X in text above. Output Format True, if combination is possible False, if combination is not possible. constraints N ≥ 3 X,a ≤ 30000 SAMPLE INPUT 6 1 4 45 6 10 8 22 SAMPLE OUTPUT True Explanation The sum of 2nd, 5th and 6th beverage size is equal to 22. So the output will be True. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $100^{500}$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $i$-th attack is performed at the beginning of the $a_i$-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals $1$ damage during each of the next $k$ seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one). For example, suppose $k = 4$, and Monocarp stabs the dragon during the seconds $2$, $4$ and $10$. Then the poison effect is applied at the start of the $2$-nd second and deals $1$ damage during the $2$-nd and $3$-rd seconds; then, at the beginning of the $4$-th second, the poison effect is reapplied, so it deals exactly $1$ damage during the seconds $4$, $5$, $6$ and $7$; then, during the $10$-th second, the poison effect is applied again, and it deals $1$ damage during the seconds $10$, $11$, $12$ and $13$. In total, the dragon receives $10$ damage. Monocarp knows that the dragon has $h$ hit points, and if he deals at least $h$ damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of $k$ (the number of seconds the poison effect lasts) that is enough to deal at least $h$ damage to the dragon. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The first line of the test case contains two integers $n$ and $h$ ($1 \le n \le 100; 1 \le h \le 10^{18}$) — the number of Monocarp's attacks and the amount of damage that needs to be dealt. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9; a_i < a_{i + 1}$), where $a_i$ is the second when the $i$-th attack is performed. -----Output----- For each test case, print a single integer — the minimum value of the parameter $k$, such that Monocarp will cause at least $h$ damage to the dragon. -----Examples----- Input 4 2 5 1 5 3 10 2 4 10 5 3 1 2 4 5 7 4 1000 3 25 64 1337 Output 3 4 1 470 -----Note----- In the first example, for $k=3$, damage is dealt in seconds $[1, 2, 3, 5, 6, 7]$. In the second example, for $k=4$, damage is dealt in seconds $[2, 3, 4, 5, 6, 7, 10, 11, 12, 13]$. In the third example, for $k=1$, damage is dealt in seconds $[1, 2, 4, 5, 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. Champernown constant is an irrational number represented in decimal by "0." followed by concatenation of all positive integers in the increasing order. The first few digits of this constant are: 0.123456789101112... Your task is to write a program that outputs the K digits of Chapnernown constant starting at the N-th place for given two natural numbers K and N. Input The input has multiple lines. Each line has two positive integers N and K (N ≤ 109, K ≤ 100) separated by a space. The end of input is indicated by a line with two zeros. This line should not be processed. Output For each line, output a line that contains the K digits. Example Input 4 5 6 7 0 0 Output 45678 6789101 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 back at your newly acquired decrypting job for the secret organization when a new assignment comes in. Apparently the enemy has been communicating using a device they call "The Mirror". It is a rudimentary device with encrypts the message by switching its letter with its mirror opposite (A => Z), (B => Y), (C => X) etc. Your job is to build a method called "mirror" which will decrypt the messages. Resulting messages will be in lowercase. To add more secrecy, you are to accept a second optional parameter, telling you which letters or characters are to be reversed; if it is not given, consider the whole alphabet as a default. To make it a bit more clear: e.g. in case of "abcdefgh" as the second optional parameter, you replace "a" with "h", "b" with "g" etc. . For example: ```python mirror("Welcome home"), "dvoxlnv slnv" #whole alphabet mirrored here mirror("hello", "abcdefgh"), "adllo" #notice only "h" and "e" get reversed ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of n square cells (that is, on a 1 × n table). At the beginning of the game Alice puts k ships on the field without telling their positions to Bob. Each ship looks as a 1 × a rectangle (that is, it occupies a sequence of a consecutive squares of the field). The ships cannot intersect and even touch each other. After that Bob makes a sequence of "shots". He names cells of the field and Alice either says that the cell is empty ("miss"), or that the cell belongs to some ship ("hit"). But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a "miss". Help Bob catch Alice cheating — find Bob's first move, such that after it you can be sure that Alice cheated. -----Input----- The first line of the input contains three integers: n, k and a (1 ≤ n, k, a ≤ 2·10^5) — the size of the field, the number of the ships and the size of each ship. It is guaranteed that the n, k and a are such that you can put k ships of size a on the field, so that no two ships intersect or touch each other. The second line contains integer m (1 ≤ m ≤ n) — the number of Bob's moves. The third line contains m distinct integers x_1, x_2, ..., x_{m}, where x_{i} is the number of the cell where Bob made the i-th shot. The cells are numbered from left to right from 1 to n. -----Output----- Print a single integer — the number of such Bob's first move, after which you can be sure that Alice lied. Bob's moves are numbered from 1 to m in the order the were made. If the sought move doesn't exist, then print "-1". -----Examples----- Input 11 3 3 5 4 8 6 1 11 Output 3 Input 5 1 3 2 1 5 Output -1 Input 5 1 3 1 3 Output 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Look for the Winner! The citizens of TKB City are famous for their deep love in elections and vote counting. Today they hold an election for the next chairperson of the electoral commission. Now the voting has just been closed and the counting is going to start. The TKB citizens have strong desire to know the winner as early as possible during vote counting. The election candidate receiving the most votes shall be the next chairperson. Suppose for instance that we have three candidates A, B, and C and ten votes. Suppose also that we have already counted six of the ten votes and the vote counts of A, B, and C are four, one, and one, respectively. At this moment, every candidate has a chance to receive four more votes and so everyone can still be the winner. However, if the next vote counted is cast for A, A is ensured to be the winner since A already has five votes and B or C can have at most four votes at the end. In this example, therefore, the TKB citizens can know the winner just when the seventh vote is counted. Your mission is to write a program that receives every vote counted, one by one, identifies the winner, and determines when the winner gets ensured. Input The input consists of at most 1500 datasets, each consisting of two lines in the following format. n c1 c2 … cn n in the first line represents the number of votes, and is a positive integer no greater than 100. The second line represents the n votes, separated by a space. Each ci (1 ≤ i ≤ n) is a single uppercase letter, i.e. one of 'A' through 'Z'. This represents the election candidate for which the i-th vote was cast. Counting shall be done in the given order from c1 to cn. You should assume that at least two stand as candidates even when all the votes are cast for one candidate. The end of the input is indicated by a line containing a zero. Output For each dataset, unless the election ends in a tie, output a single line containing an uppercase letter c and an integer d separated by a space: c should represent the election winner and d should represent after counting how many votes the winner is identified. Otherwise, that is, if the election ends in a tie, output a single line containing `TIE'. Sample Input 1 A 4 A A B B 5 L M N L N 6 K K K K K K 6 X X X Y Z X 10 A A A B A C A C C B 10 U U U U U V V W W W 0 Output for the Sample Input A 1 TIE TIE K 4 X 5 A 7 U 8 Example Input 1 A 4 A A B B 5 L M N L N 6 K K K K K K 6 X X X Y Z X 10 A A A B A C A C C B 10 U U U U U V V W W W 0 Output A 1 TIE TIE K 4 X 5 A 7 U 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. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG Read the inputs from stdin solve the problem and write the answer to stdout (do 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 bookshelf which can fit $n$ books. The $i$-th position of bookshelf is $a_i = 1$ if there is a book on this position and $a_i = 0$ otherwise. It is guaranteed that there is at least one book on the bookshelf. In one move, you can choose some contiguous segment $[l; r]$ consisting of books (i.e. for each $i$ from $l$ to $r$ the condition $a_i = 1$ holds) and: Shift it to the right by $1$: move the book at index $i$ to $i + 1$ for all $l \le i \le r$. This move can be done only if $r+1 \le n$ and there is no book at the position $r+1$. Shift it to the left by $1$: move the book at index $i$ to $i-1$ for all $l \le i \le r$. This move can be done only if $l-1 \ge 1$ and there is no book at the position $l-1$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps). For example, for $a = [0, 0, 1, 0, 1]$ there is a gap between books ($a_4 = 0$ when $a_3 = 1$ and $a_5 = 1$), for $a = [1, 1, 0]$ there are no gaps between books and for $a = [0, 0,0]$ there are also no gaps between books. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 200$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($1 \le n \le 50$) — the number of places on a bookshelf. The second line of the test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 1$), where $a_i$ is $1$ if there is a book at this position and $0$ otherwise. It is guaranteed that there is at least one book on the bookshelf. -----Output----- For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps). -----Example----- Input 5 7 0 0 1 0 1 0 1 3 1 0 0 5 1 1 0 0 1 6 1 0 0 0 0 1 5 1 1 0 1 1 Output 2 0 2 4 1 -----Note----- In the first test case of the example, you can shift the segment $[3; 3]$ to the right and the segment $[4; 5]$ to the right. After all moves, the books form the contiguous segment $[5; 7]$. So the answer is $2$. In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already. In the third test case of the example, you can shift the segment $[5; 5]$ to the left and then the segment $[4; 4]$ to the left again. After all moves, the books form the contiguous segment $[1; 3]$. So the answer is $2$. In the fourth test case of the example, you can shift the segment $[1; 1]$ to the right, the segment $[2; 2]$ to the right, the segment $[6; 6]$ to the left and then the segment $[5; 5]$ to the left. After all moves, the books form the contiguous segment $[3; 4]$. So the answer is $4$. In the fifth test case of the example, you can shift the segment $[1; 2]$ to the right. After all moves, the books form the contiguous segment $[2; 5]$. So the answer is $1$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarp took $n$ videos, the duration of the $i$-th video is $a_i$ seconds. The videos are listed in the chronological order, i.e. the $1$-st video is the earliest, the $2$-nd video is the next, ..., the $n$-th video is the last. Now Polycarp wants to publish exactly $k$ ($1 \le k \le n$) posts in Instabram. Each video should be a part of a single post. The posts should preserve the chronological order, it means that the first post should contain one or more of the earliest videos, the second post should contain a block (one or more videos) going next and so on. In other words, if the number of videos in the $j$-th post is $s_j$ then: $s_1+s_2+\dots+s_k=n$ ($s_i>0$), the first post contains the videos: $1, 2, \dots, s_1$; the second post contains the videos: $s_1+1, s_1+2, \dots, s_1+s_2$; the third post contains the videos: $s_1+s_2+1, s_1+s_2+2, \dots, s_1+s_2+s_3$; ... the $k$-th post contains videos: $n-s_k+1,n-s_k+2,\dots,n$. Polycarp is a perfectionist, he wants the total duration of videos in each post to be the same. Help Polycarp to find such positive integer values $s_1, s_2, \dots, s_k$ that satisfy all the conditions above. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 10^5$). The next line contains $n$ positive integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^4$), where $a_i$ is the duration of the $i$-th video. -----Output----- If solution exists, print "Yes" in the first line. Print $k$ positive integers $s_1, s_2, \dots, s_k$ ($s_1+s_2+\dots+s_k=n$) in the second line. The total duration of videos in each post should be the same. It can be easily proven that the answer is unique (if it exists). If there is no solution, print a single line "No". -----Examples----- Input 6 3 3 3 1 4 1 6 Output Yes 2 3 1 Input 3 3 1 1 1 Output Yes 1 1 1 Input 3 3 1 1 2 Output No Input 3 1 1 10 100 Output Yes 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. Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type. Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets — they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change. We shall assume that the widget a is packed in the widget b if there exists a chain of widgets a = c1, c2, ..., ck = b, k ≥ 2, for which ci is packed directly to ci + 1 for any 1 ≤ i < k. In Vasya's library the situation when the widget a is packed in the widget a (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error. Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal 0. <image> The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox — vertically. The parameter spacing sets the distance between adjacent widgets, and border — a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to 0 × 0, regardless of the options border and spacing. The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data. For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript. Input The first line contains an integer n — the number of instructions (1 ≤ n ≤ 100). Next n lines contain instructions in the language VasyaScript — one instruction per line. There is a list of possible instructions below. * "Widget [name]([x],[y])" — create a new widget [name] of the type Widget possessing the width of [x] units and the height of [y] units. * "HBox [name]" — create a new widget [name] of the type HBox. * "VBox [name]" — create a new widget [name] of the type VBox. * "[name1].pack([name2])" — pack the widget [name2] in the widget [name1]. At that, the widget [name1] must be of type HBox or VBox. * "[name].set_border([x])" — set for a widget [name] the border parameter to [x] units. The widget [name] must be of type HBox or VBox. * "[name].set_spacing([x])" — set for a widget [name] the spacing parameter to [x] units. The widget [name] must be of type HBox or VBox. All instructions are written without spaces at the beginning and at the end of the string. The words inside the instruction are separated by exactly one space. There are no spaces directly before the numbers and directly after them. The case matters, for example, "wiDget x" is not a correct instruction. The case of the letters is correct in the input data. All names of the widgets consist of lowercase Latin letters and has the length from 1 to 10 characters inclusive. The names of all widgets are pairwise different. All numbers in the script are integers from 0 to 100 inclusive It is guaranteed that the above-given script is correct, that is that all the operations with the widgets take place after the widgets are created and no widget is packed in itself. It is guaranteed that the script creates at least one widget. Output For each widget print on a single line its name, width and height, separated by spaces. The lines must be ordered lexicographically by a widget's name. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d specificator) Examples Input 12 Widget me(50,40) VBox grandpa HBox father grandpa.pack(father) father.pack(me) grandpa.set_border(10) grandpa.set_spacing(20) Widget brother(30,60) father.pack(brother) Widget friend(20,60) Widget uncle(100,20) grandpa.pack(uncle) Output brother 30 60 father 80 60 friend 20 60 grandpa 120 120 me 50 40 uncle 100 20 Input 15 Widget pack(10,10) HBox dummy HBox x VBox y y.pack(dummy) y.set_border(5) y.set_spacing(55) dummy.set_border(10) dummy.set_spacing(20) x.set_border(10) x.set_spacing(10) x.pack(pack) x.pack(dummy) x.pack(pack) x.set_border(0) Output dummy 0 0 pack 10 10 x 40 10 y 10 10 Note In the first sample the widgets are arranged as follows: <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. Akari has n kinds of flowers, one of each kind. She is going to choose one or more of these flowers to make a bouquet. However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b. How many different bouquets are there that Akari can make? Find the count modulo (10^9 + 7). Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet. -----Constraints----- - All values in input are integers. - 2 \leq n \leq 10^9 - 1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5) -----Input----- Input is given from Standard Input in the following format: n a b -----Output----- Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print 0.) -----Sample Input----- 4 1 3 -----Sample Output----- 7 In this case, Akari can choose 2 or 4 flowers to make the bouquet. There are 6 ways to choose 2 out of the 4 flowers, and 1 way to choose 4, so there are a total of 7 different bouquets that Akari can make. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. -----Input----- The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. -----Output----- If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). -----Examples----- Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO -----Note----- In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 $LCM(x, y)$ be the minimum positive integer that is divisible by both $x$ and $y$. For example, $LCM(13, 37) = 481$, $LCM(9, 6) = 18$. You are given two integers $l$ and $r$. Find two integers $x$ and $y$ such that $l \le x < y \le r$ and $l \le LCM(x, y) \le r$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10000$) — the number of test cases. Each test case is represented by one line containing two integers $l$ and $r$ ($1 \le l < r \le 10^9$). -----Output----- For each test case, print two integers: if it is impossible to find integers $x$ and $y$ meeting the constraints in the statement, print two integers equal to $-1$; otherwise, print the values of $x$ and $y$ (if there are multiple valid answers, you may print any of them). -----Example----- Input 4 1 1337 13 69 2 4 88 89 Output 6 7 14 21 2 4 -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. Read problems statements in Mandarin Chinese and Russian. You are given an array A of N integers. You are to fulfill M queries. Each query has one of the following three types: C d : Rotate the array A clockwise by d units. A d : Rotate the array A anticlockwise by d units. R d : Query for the value of the element, currently being the d-th in the array A. ------ Input ------ The first line contains two numbers - N and M respectively. The next line contains N space separated Integers, denoting the array A. Each of the following M lines contains a query in the one of the forms described above. ------ Output ------ For each query of type R output the answer on a separate line. ------ Constraints ------ $1 ≤ N ≤ 100000 $ $1 ≤ M ≤ 100000 $ $1 ≤ d ≤ N, in all the queries$ $1 ≤ elements of A ≤ 1000000$ $The array A and the queries of the type R are 1-based. $  ----- Sample Input 1 ------ 5 5 5 4 3 3 9 R 1 C 4 R 5 A 3 R 2 ----- Sample Output 1 ------ 5 3 3 ----- explanation 1 ------ The initial array : 5 4 3 3 9 The answer for R 1 : 5 The array after C 4 : 9 5 4 3 3 The answer for R 5 : 3 The array after A 3 : 4 3 3 9 5 The answer for R 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. Calculate the product of all elements in an array. ```if:csharp If the array is *null*, you should throw `ArgumentNullException` and if the array is empty, you should throw `InvalidOperationException`. As a challenge, try writing your method in just one line of code. It's possible to have only 36 characters within your method. ``` ```if:javascript If the array is `null` or is empty, the function should return `null`. ``` ```if:haskell If the array is empty then return Nothing, else return Just product. ``` ```if:php If the array is `NULL` or empty, return `NULL`. ``` ```if:python If the array is empty or `None`, return `None`. ``` ```if:ruby If the array is `nil` or is empty, the function should return `nil`. ``` ```if:crystal If the array is `nil` or is empty, the function should return `nil`. ``` ```if:groovy If the array is `null` or `empty` return `null`. ``` ```if:julia If the input is `nothing` or an empty array, return `nothing` ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve. The camera's memory is d megabytes. Valera's camera can take photos of high and low quality. One low quality photo takes a megabytes of memory, one high quality photo take b megabytes of memory. For unknown reasons, each client asks him to make several low quality photos and several high quality photos. More formally, the i-th client asks to make xi low quality photos and yi high quality photos. Valera wants to serve as many clients per day as possible, provided that they will be pleased with his work. To please the i-th client, Valera needs to give him everything he wants, that is, to make xi low quality photos and yi high quality photos. To make one low quality photo, the camera must have at least a megabytes of free memory space. Similarly, to make one high quality photo, the camera must have at least b megabytes of free memory space. Initially the camera's memory is empty. Valera also does not delete photos from the camera so that the camera's memory gradually fills up. Calculate the maximum number of clients Valera can successfully serve and print the numbers of these clients. Input The first line contains two integers n and d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) — the number of clients and the camera memory size, correspondingly. The second line contains two integers a and b (1 ≤ a ≤ b ≤ 104) — the size of one low quality photo and of one high quality photo, correspondingly. Next n lines describe the clients. The i-th line contains two integers xi and yi (0 ≤ xi, yi ≤ 105) — the number of low quality photos and high quality photos the i-th client wants, correspondingly. All numbers on all lines are separated by single spaces. Output On the first line print the answer to the problem — the maximum number of clients that Valera can successfully serve. Print on the second line the numbers of the client in any order. All numbers must be distinct. If there are multiple answers, print any of them. The clients are numbered starting with 1 in the order in which they are defined in the input data. Examples Input 3 10 2 3 1 4 2 1 1 0 Output 2 3 2 Input 3 6 6 6 1 1 1 0 1 0 Output 1 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Take an integer `n (n >= 0)` and a digit `d (0 <= d <= 9)` as an integer. Square all numbers `k (0 <= k <= n)` between 0 and n. Count the numbers of digits `d` used in the writing of all the `k**2`. Call `nb_dig` (or nbDig or ...) the function taking `n` and `d` as parameters and returning this count. #Examples: ``` n = 10, d = 1, the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 We are using the digit 1 in 1, 16, 81, 100. The total count is then 4. nb_dig(25, 1): the numbers of interest are 1, 4, 9, 10, 11, 12, 13, 14, 19, 21 which squared are 1, 16, 81, 100, 121, 144, 169, 196, 361, 441 so there are 11 digits `1` for the squares of numbers between 0 and 25. ``` Note that `121` has twice the digit `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. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number $x$ in an array. For an array $a$ indexed from zero, and an integer $x$ the pseudocode of the algorithm is as follows: BinarySearch(a, x) left = 0 right = a.size() while left < right middle = (left + right) / 2 if a[middle] <= x then left = middle + 1 else right = middle if left > 0 and a[left - 1] == x then return true else return false Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find $x$! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size $n$ such that the algorithm finds $x$ in them. A permutation of size $n$ is an array consisting of $n$ distinct integers between $1$ and $n$ in arbitrary order. Help Andrey and find the number of permutations of size $n$ which contain $x$ at position $pos$ and for which the given implementation of the binary search algorithm finds $x$ (returns true). As the result may be extremely large, print the remainder of its division by $10^9+7$. -----Input----- The only line of input contains integers $n$, $x$ and $pos$ ($1 \le x \le n \le 1000$, $0 \le pos \le n - 1$) — the required length of the permutation, the number to search, and the required position of that number, respectively. -----Output----- Print a single number — the remainder of the division of the number of valid permutations by $10^9+7$. -----Examples----- Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 -----Note----- All possible permutations in the first test case: $(2, 3, 1, 4)$, $(2, 4, 1, 3)$, $(3, 2, 1, 4)$, $(3, 4, 1, 2)$, $(4, 2, 1, 3)$, $(4, 3, 1, 2)$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i. First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing. Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa. -----Constraints----- - 2 \leq N \leq 10^5 - 0 \leq M \leq \min(10^5, N (N-1)) - 1 \leq u_i, v_i \leq N(1 \leq i \leq M) - u_i \neq v_i (1 \leq i \leq M) - If i \neq j, (u_i, v_i) \neq (u_j, v_j). - 1 \leq S, T \leq N - S \neq T -----Input----- Input is given from Standard Input in the following format: N M u_1 v_1 : u_M v_M S T -----Output----- If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T. -----Sample Input----- 4 4 1 2 2 3 3 4 4 1 1 3 -----Sample Output----- 2 Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them. The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $(0, 0)$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $OX$ or $OY$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification. Alexey wants to make a polyline in such a way that its end is as far as possible from $(0, 0)$. Please help him to grow the tree this way. Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches. -----Input----- The first line contains an integer $n$ ($1 \le n \le 100\,000$) — the number of sticks Alexey got as a present. The second line contains $n$ integers $a_1, \ldots, a_n$ ($1 \le a_i \le 10\,000$) — the lengths of the sticks. -----Output----- Print one integer — the square of the largest possible distance from $(0, 0)$ to the tree end. -----Examples----- Input 3 1 2 3 Output 26 Input 4 1 1 2 2 Output 20 -----Note----- The following pictures show optimal trees for example tests. The squared distance in the first example equals $5 \cdot 5 + 1 \cdot 1 = 26$, and in the second example $4 \cdot 4 + 2 \cdot 2 = 20$. [Image] [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first r_{i} numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m). Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence a_{i} of length n and the description of each manager, that is value r_{i} and his favourite order. You are asked to speed up the process and determine how the final report will look like. -----Input----- The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively. The second line contains n integers a_{i} (|a_{i}| ≤ 10^9) — the initial report before it gets to the first manager. Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers t_{i} and r_{i} ($t_{i} \in \{1,2 \}$, 1 ≤ r_{i} ≤ n), meaning that the i-th manager sorts the first r_{i} numbers either in the non-descending (if t_{i} = 1) or non-ascending (if t_{i} = 2) order. -----Output----- Print n integers — the final report, which will be passed to Blake by manager number m. -----Examples----- Input 3 1 1 2 3 2 2 Output 2 1 3 Input 4 2 1 2 4 3 2 3 1 2 Output 2 4 1 3 -----Note----- In the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form. In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. <image> The International Clown and Pierrot Competition (ICPC), is one of the most distinguished and also the most popular events on earth in the show business. One of the unique features of this contest is the great number of judges that sometimes counts up to one hundred. The number of judges may differ from one contestant to another, because judges with any relationship whatsoever with a specific contestant are temporarily excluded for scoring his/her performance. Basically, scores given to a contestant's performance by the judges are averaged to decide his/her score. To avoid letting judges with eccentric viewpoints too much influence the score, the highest and the lowest scores are set aside in this calculation. If the same highest score is marked by two or more judges, only one of them is ignored. The same is with the lowest score. The average, which may contain fractions, are truncated down to obtain final score as an integer. You are asked to write a program that computes the scores of performances, given the scores of all the judges, to speed up the event to be suited for a TV program. Input The input consists of a number of datasets, each corresponding to a contestant's performance. There are no more than 20 datasets in the input. A dataset begins with a line with an integer n, the number of judges participated in scoring the performance (3 ≤ n ≤ 100). Each of the n lines following it has an integral score s (0 ≤ s ≤ 1000) marked by a judge. No other characters except for digits to express these numbers are in the input. Judges' names are kept secret. The end of the input is indicated by a line with a single zero in it. Output For each dataset, a line containing a single decimal integer indicating the score for the corresponding performance should be output. No other characters should be on the output line. Example Input 3 1000 342 0 5 2 2 9 11 932 5 300 1000 0 200 400 8 353 242 402 274 283 132 402 523 0 Output 342 7 300 326 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have integer $n$. Calculate how many ways are there to fully cover belt-like area of $4n-2$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $2$ coverings are different if some $2$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one. Please look at pictures below for better understanding. $\theta$ On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. [Image] These are the figures of the area you want to fill for $n = 1, 2, 3, 4$. You have to answer $t$ independent test cases. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^{4}$) — the number of test cases. Each of the next $t$ lines contains a single integer $n$ ($1 \le n \le 10^{9}$). -----Output----- For each test case, print the number of ways to fully cover belt-like area of $4n-2$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $10^{18}$. -----Example----- Input 2 2 1 Output 2 1 -----Note----- In the first test case, there are the following $2$ ways to fill the area: [Image] In the second test case, there is a unique way to fill the area: [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s_1 and s_2 be a RBS then the strings <s_1>s_2, {s_1}s_2, [s_1]s_2, (s_1)s_2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. -----Input----- The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 10^6. -----Output----- If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. -----Examples----- Input [<}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has n gyms. The i-th gym has g_{i} Pokemon in it. There are m distinct Pokemon types in the Himalayan region numbered from 1 to m. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving. Formally, an evolution plan is a permutation f of {1, 2, ..., m}, such that f(x) = y means that a Pokemon of type x evolves into a Pokemon of type y. The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol. Two evolution plans f_1 and f_2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an i such that f_1(i) ≠ f_2(i). Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 10^9 + 7. -----Input----- The first line contains two integers n and m (1 ≤ n ≤ 10^5, 1 ≤ m ≤ 10^6) — the number of gyms and the number of Pokemon types. The next n lines contain the description of Pokemons in the gyms. The i-th of these lines begins with the integer g_{i} (1 ≤ g_{i} ≤ 10^5) — the number of Pokemon in the i-th gym. After that g_{i} integers follow, denoting types of the Pokemons in the i-th gym. Each of these integers is between 1 and m. The total number of Pokemons (the sum of all g_{i}) does not exceed 5·10^5. -----Output----- Output the number of valid evolution plans modulo 10^9 + 7. -----Examples----- Input 2 3 2 1 2 2 2 3 Output 1 Input 1 3 3 1 2 3 Output 6 Input 2 4 2 1 2 3 2 3 4 Output 2 Input 2 2 3 2 2 1 2 1 2 Output 1 Input 3 7 2 1 2 2 3 4 3 5 6 7 Output 24 -----Note----- In the first case, the only possible evolution plan is: $1 \rightarrow 1,2 \rightarrow 2,3 \rightarrow 3$ In the second case, any permutation of (1, 2, 3) is valid. In the third case, there are two possible plans: $1 \rightarrow 1,2 \rightarrow 2,3 \rightarrow 4,4 \rightarrow 3$ $1 \rightarrow 1,2 \rightarrow 2,3 \rightarrow 3,4 \rightarrow 4$ In the fourth case, the only possible evolution plan is: $1 \rightarrow 1,2 \rightarrow 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. We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a. For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times. Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j. -----Constraints----- - 2 \leq N \leq 10^5 - s_i is a string of length 10. - Each character in s_i is a lowercase English letter. - s_1, s_2, \ldots, s_N are all distinct. -----Input----- Input is given from Standard Input in the following format: N s_1 s_2 : s_N -----Output----- Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j. -----Sample Input----- 3 acornistnt peanutbomb constraint -----Sample Output----- 1 s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily $8 \times 8$, but it still is $N \times N$. Each square has some number written on it, all the numbers are from $1$ to $N^2$ and all the numbers are pairwise distinct. The $j$-th square in the $i$-th row has a number $A_{ij}$ written on it. In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number $1$ (you can choose which one). Then you want to reach square $2$ (possibly passing through some other squares in process), then square $3$ and so on until you reach square $N^2$. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times. A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on. You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements. What is the path you should take to satisfy all conditions? -----Input----- The first line contains a single integer $N$ ($3 \le N \le 10$) — the size of the chessboard. Each of the next $N$ lines contains $N$ integers $A_{i1}, A_{i2}, \dots, A_{iN}$ ($1 \le A_{ij} \le N^2$) — the numbers written on the squares of the $i$-th row of the board. It is guaranteed that all $A_{ij}$ are pairwise distinct. -----Output----- The only line should contain two integers — the number of steps in the best answer and the number of replacement moves in it. -----Example----- Input 3 1 9 3 8 6 7 4 2 5 Output 12 1 -----Note----- Here are the steps for the first example (the starting piece is a knight): Move to $(3, 2)$ Move to $(1, 3)$ Move to $(3, 2)$ Replace the knight with a rook Move to $(3, 1)$ Move to $(3, 3)$ Move to $(3, 2)$ Move to $(2, 2)$ Move to $(2, 3)$ Move to $(2, 1)$ Move to $(1, 1)$ Move to $(1, 2)$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function which reduces fractions to their simplest form! Fractions will be presented as an array/tuple (depending on the language), and the reduced fraction must be returned as an array/tuple: ``` input: [numerator, denominator] output: [newNumerator, newDenominator] example: [45, 120] --> [3, 8] ``` All numerators and denominators will be positive integers. Note: This is an introductory Kata for a series... coming soon! Read the inputs from stdin solve the problem and write the answer to stdout (do 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 way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task. Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have n people standing on the first floor, the i-th person wants to go to the f_{i}-th floor. Unfortunately, there is only one elevator and its capacity equal to k (that is at most k people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs |a - b| seconds to move from the a-th floor to the b-th floor (we don't count the time the people need to get on and off the elevator). What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor? -----Input----- The first line contains two integers n and k (1 ≤ n, k ≤ 2000) — the number of people and the maximal capacity of the elevator. The next line contains n integers: f_1, f_2, ..., f_{n} (2 ≤ f_{i} ≤ 2000), where f_{i} denotes the target floor of the i-th person. -----Output----- Output a single integer — the minimal time needed to achieve the goal. -----Examples----- Input 3 2 2 3 4 Output 8 Input 4 2 50 100 50 100 Output 296 Input 10 3 2 2 2 2 2 2 2 2 2 2 Output 8 -----Note----- In first sample, an optimal solution is: The elevator takes up person #1 and person #2. It goes to the 2nd floor. Both people go out of the elevator. The elevator goes back to the 1st floor. Then the elevator takes up person #3. And it goes to the 2nd floor. It picks up person #2. Then it goes to the 3rd floor. Person #2 goes out. Then it goes to the 4th floor, where person #3 goes out. The elevator goes back to the 1st floor. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her. Given an array $a$ of length $n$, consisting only of the numbers $0$ and $1$, and the number $k$. Exactly $k$ times the following happens: Two numbers $i$ and $j$ are chosen equiprobable such that ($1 \leq i < j \leq n$). The numbers in the $i$ and $j$ positions are swapped. Sonya's task is to find the probability that after all the operations are completed, the $a$ array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem. It can be shown that the desired probability is either $0$ or it can be represented as $\dfrac{P}{Q}$, where $P$ and $Q$ are coprime integers and $Q \not\equiv 0~\pmod {10^9+7}$. -----Input----- The first line contains two integers $n$ and $k$ ($2 \leq n \leq 100, 1 \leq k \leq 10^9$) — the length of the array $a$ and the number of operations. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 1$) — the description of the array $a$. -----Output----- If the desired probability is $0$, print $0$, otherwise print the value $P \cdot Q^{-1}$ $\pmod {10^9+7}$, where $P$ and $Q$ are defined above. -----Examples----- Input 3 2 0 1 0 Output 333333336 Input 5 1 1 1 1 0 0 Output 0 Input 6 4 1 0 0 1 1 0 Output 968493834 -----Note----- In the first example, all possible variants of the final array $a$, after applying exactly two operations: $(0, 1, 0)$, $(0, 0, 1)$, $(1, 0, 0)$, $(1, 0, 0)$, $(0, 1, 0)$, $(0, 0, 1)$, $(0, 0, 1)$, $(1, 0, 0)$, $(0, 1, 0)$. Therefore, the answer is $\dfrac{3}{9}=\dfrac{1}{3}$. In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is $0$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers. He has created a method to know how strong his army is. Let the i-th soldier’s strength be a_{i}. For some k he calls i_1, i_2, ..., i_{k} a clan if i_1 < i_2 < i_3 < ... < i_{k} and gcd(a_{i}_1, a_{i}_2, ..., a_{i}_{k}) > 1 . He calls the strength of that clan k·gcd(a_{i}_1, a_{i}_2, ..., a_{i}_{k}). Then he defines the strength of his army by the sum of strengths of all possible clans. Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (10^9 + 7). Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it. -----Input----- The first line contains integer n (1 ≤ n ≤ 200000) — the size of the army. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000000) — denoting the strengths of his soldiers. -----Output----- Print one integer — the strength of John Snow's army modulo 1000000007 (10^9 + 7). -----Examples----- Input 3 3 3 1 Output 12 Input 4 2 3 4 6 Output 39 -----Note----- In the first sample the clans are {1}, {2}, {1, 2} so the answer will be 1·3 + 1·3 + 2·3 = 12 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 9900 * -2 × 107 ≤ di ≤ 2 × 107 * There are no parallel edges * There are no self-loops Input An edge-weighted graph G (V, E). |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 |V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge. Output If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print NEGATIVE CYCLE in a line. Otherwise, print D0,0 D0,1 ... D0,|V|-1 D1,0 D1,1 ... D1,|V|-1 : D|V|-1,0 D1,1 ... D|V|-1,|V|-1 The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs. Examples Input 4 6 0 1 1 0 2 5 1 2 2 1 3 4 2 3 1 3 2 7 Output 0 1 3 4 INF 0 2 3 INF INF 0 1 INF INF 7 0 Input 4 6 0 1 1 0 2 -5 1 2 2 1 3 4 2 3 1 3 2 7 Output 0 1 -5 -4 INF 0 2 3 INF INF 0 1 INF INF 7 0 Input 4 6 0 1 1 0 2 5 1 2 2 1 3 4 2 3 1 3 2 -7 Output NEGATIVE CYCLE Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an infinite 2-dimensional grid. The robot stands in cell $(0, 0)$ and wants to reach cell $(x, y)$. Here is a list of possible commands the robot can execute: move north from cell $(i, j)$ to $(i, j + 1)$; move east from cell $(i, j)$ to $(i + 1, j)$; move south from cell $(i, j)$ to $(i, j - 1)$; move west from cell $(i, j)$ to $(i - 1, j)$; stay in cell $(i, j)$. The robot wants to reach cell $(x, y)$ in as few commands as possible. However, he can't execute the same command two or more times in a row. What is the minimum number of commands required to reach $(x, y)$ from $(0, 0)$? -----Input----- The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of testcases. Each of the next $t$ lines contains two integers $x$ and $y$ ($0 \le x, y \le 10^4$) — the destination coordinates of the robot. -----Output----- For each testcase print a single integer — the minimum number of commands required for the robot to reach $(x, y)$ from $(0, 0)$ if no command is allowed to be executed two or more times in a row. -----Examples----- Input 5 5 5 3 4 7 1 0 0 2 0 Output 10 7 13 0 3 -----Note----- The explanations for the example test: We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively. In the first test case, the robot can use the following sequence: NENENENENE. In the second test case, the robot can use the following sequence: NENENEN. In the third test case, the robot can use the following sequence: ESENENE0ENESE. In the fourth test case, the robot doesn't need to go anywhere at all. In the fifth test case, the robot can use the following sequence: E0E. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 rooted tree (see Notes) with N vertices numbered 1 to N. Each of the vertices, except the root, has a directed edge coming from its parent. Note that the root may not be Vertex 1. Takahashi has added M new directed edges to this graph. Each of these M edges, u \rightarrow v, extends from some vertex u to its descendant v. You are given the directed graph with N vertices and N-1+M edges after Takahashi added edges. More specifically, you are given N-1+M pairs of integers, (A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M}), which represent that the i-th edge extends from Vertex A_i to Vertex B_i. Restore the original rooted tree. Constraints * 3 \leq N * 1 \leq M * N + M \leq 10^5 * 1 \leq A_i, B_i \leq N * A_i \neq B_i * If i \neq j, (A_i, B_i) \neq (A_j, B_j). * The graph in input can be obtained by adding M edges satisfying the condition in the problem statement to a rooted tree with N vertices. Input Input is given from Standard Input in the following format: N M A_1 B_1 : A_{N-1+M} B_{N-1+M} Output Print N lines. In the i-th line, print `0` if Vertex i is the root of the original tree, and otherwise print the integer representing the parent of Vertex i in the original tree. Note that it can be shown that the original tree is uniquely determined. Examples Input 3 1 1 2 1 3 2 3 Output 0 1 2 Input 6 3 2 1 2 3 4 1 4 2 6 1 2 6 4 6 6 5 Output 6 4 2 0 6 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. $n$ heroes fight against each other in the Arena. Initially, the $i$-th hero has level $a_i$. Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute). When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by $1$. The winner of the tournament is the first hero that wins in at least $100^{500}$ fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament. Calculate the number of possible winners among $n$ heroes. -----Input----- The first line contains one integer $t$ ($1 \le t \le 500$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $n$ ($2 \le n \le 100$) — the number of heroes. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the initial level of the $i$-th hero. -----Output----- For each test case, print one integer — the number of possible winners among the given $n$ heroes. -----Examples----- Input 3 3 3 2 2 2 5 5 4 1 3 3 7 Output 1 0 3 -----Note----- In the first test case of the example, the only possible winner is the first hero. In the second test case of the example, each fight between the heroes results in nobody winning it, so the tournament lasts forever and there is no winner. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string $s$ he found is a binary string of length $n$ (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters $s_i$ and $s_{i+1}$, and if $s_i$ is 1 and $s_{i + 1}$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing. Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $s$ as clean as possible. He thinks for two different strings $x$ and $y$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner. Now you should answer $t$ test cases: for the $i$-th test case, print the cleanest possible string that Lee can get by doing some number of moves. Small reminder: if we have two strings $x$ and $y$ of the same length then $x$ is lexicographically smaller than $y$ if there is a position $i$ such that $x_1 = y_1$, $x_2 = y_2$,..., $x_{i - 1} = y_{i - 1}$ and $x_i < y_i$. -----Input----- The first line contains the integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Next $2t$ lines contain test cases — one per two lines. The first line of each test case contains the integer $n$ ($1 \le n \le 10^5$) — the length of the string $s$. The second line contains the binary string $s$. The string $s$ is a string of length $n$ which consists only of zeroes and ones. It's guaranteed that sum of $n$ over test cases doesn't exceed $10^5$. -----Output----- Print $t$ answers — one per test case. The answer to the $i$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero). -----Example----- Input 5 10 0001111111 4 0101 8 11001101 10 1110000000 1 1 Output 0001111111 001 01 0 1 -----Note----- In the first test case, Lee can't perform any moves. In the second test case, Lee should erase $s_2$. In the third test case, Lee can make moves, for example, in the following order: 11001101 $\rightarrow$ 1100101 $\rightarrow$ 110101 $\rightarrow$ 10101 $\rightarrow$ 1101 $\rightarrow$ 101 $\rightarrow$ 01. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 imagine we have a popular online RPG. A player begins with a score of 0 in class E5. A1 is the highest level a player can achieve. Now let's say the players wants to rank up to class E4. To do so the player needs to achieve at least 100 points to enter the qualifying stage. Write a script that will check to see if the player has achieved at least 100 points in his class. If so, he enters the qualifying stage. In that case, we return, ```"Well done! You have advanced to the qualifying stage. Win 2 out of your next 3 games to rank up."```. Otherwise return, ```False/false``` (according to the language n use). NOTE: Remember, in C# you have to cast your output value to Object type! Read the inputs from stdin solve the problem and write the answer to stdout (do 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 house with 4 levels. In that house there is an elevator. You can program this elevator to go up or down, depending on what button the user touches inside the elevator. Valid levels must be only these numbers: `0,1,2,3` Valid buttons must be only these strings: `'0','1','2','3'` Possible return values are these numbers: `-3,-2,-1,0,1,2,3` If the elevator is on the ground floor(0th level) and the user touches button '2' the elevator must go 2 levels up, so our function must return 2. If the elevator is on the 3rd level and the user touches button '0' the elevator must go 3 levels down, so our function must return -3. If the elevator is on the 2nd level, and the user touches button '2' the elevator must remain on the same level, so we return 0. We cannot endanger the lives of our passengers, so if we get erronous inputs, our elevator must remain on the same level. So for example: - `goto(2,'4')` must return 0, because there is no button '4' in the elevator. - `goto(4,'0')` must return 0, because there is no level 4. - `goto(3,undefined)` must return 0. - `goto(undefined,'2')` must return 0. - `goto([],'2')` must return 0 because the type of the input level is array instead of a number. - `goto(3,{})` must return 0 because the type of the input button is object instead of a string. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. With a friend we used to play the following game on a chessboard (8, rows, 8 columns). On the first row at the *bottom* we put numbers: `1/2, 2/3, 3/4, 4/5, 5/6, 6/7, 7/8, 8/9` On row 2 (2nd row from the bottom) we have: `1/3, 2/4, 3/5, 4/6, 5/7, 6/8, 7/9, 8/10` On row 3: `1/4, 2/5, 3/6, 4/7, 5/8, 6/9, 7/10, 8/11` until last row: `1/9, 2/10, 3/11, 4/12, 5/13, 6/14, 7/15, 8/16` When all numbers are on the chessboard each in turn we toss a coin. The one who get "head" wins and the other gives him, in dollars, the **sum of the numbers on the chessboard**. We play for fun, the dollars come from a monopoly game! ### Task How much can I (or my friend) win or loses for each game if the chessboard has n rows and n columns? Add all of the fractional values on an n by n sized board and give the answer as a simplified fraction. - Ruby, Python, JS, Coffee, Clojure, PHP, Elixir, Crystal, Typescript, Go: The function called 'game' with parameter n (integer >= 0) returns as result an irreducible fraction written as an array of integers: [numerator, denominator]. If the denominator is 1 return [numerator]. - Haskell: 'game' returns either a "Left Integer" if denominator is 1 otherwise "Right (Integer, Integer)" - Prolog: 'game' returns an irreducible fraction written as an array of integers: [numerator, denominator]. If the denominator is 1 return [numerator, 1]. - Java, C#, C++, F#, Swift, Reason, Kotlin: 'game' returns a string that mimicks the array returned in Ruby, Python, JS, etc... - Fortran, Bash: 'game' returns a string - Forth: return on the stack the numerator and the denominator (even if the denominator is 1) - 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. #### See Example Test Cases for each language Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem. There are $n$ displays placed along a road, and the $i$-th of them can display a text with font size $s_i$ only. Maria Stepanovna wants to rent such three displays with indices $i < j < k$ that the font size increases if you move along the road in a particular direction. Namely, the condition $s_i < s_j < s_k$ should be held. The rent cost is for the $i$-th display is $c_i$. Please determine the smallest cost Maria Stepanovna should pay. -----Input----- The first line contains a single integer $n$ ($3 \le n \le 3\,000$) — the number of displays. The second line contains $n$ integers $s_1, s_2, \ldots, s_n$ ($1 \le s_i \le 10^9$) — the font sizes on the displays in the order they stand along the road. The third line contains $n$ integers $c_1, c_2, \ldots, c_n$ ($1 \le c_i \le 10^8$) — the rent costs for each display. -----Output----- If there are no three displays that satisfy the criteria, print -1. Otherwise print a single integer — the minimum total rent cost of three displays with indices $i < j < k$ such that $s_i < s_j < s_k$. -----Examples----- Input 5 2 4 5 4 10 40 30 20 10 40 Output 90 Input 3 100 101 100 2 4 5 Output -1 Input 10 1 2 3 4 5 6 7 8 9 10 10 13 11 14 15 12 13 13 18 13 Output 33 -----Note----- In the first example you can, for example, choose displays $1$, $4$ and $5$, because $s_1 < s_4 < s_5$ ($2 < 4 < 10$), and the rent cost is $40 + 10 + 40 = 90$. In the second example you can't select a valid triple of indices, so the answer is -1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded. To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously. When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem. You are suggested to solve an African crossword and print the word encrypted there. Input The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid. Output Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter. Examples Input 3 3 cba bcd cbc Output abcd Input 5 5 fcofd ooedo afaoa rdcdf eofsf Output codeforces Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Did you know that Chwee kueh, a cuisine of Singapore, means water rice cake ? Its a variety of the most popular South Indian savory cake, only that we call it here idli :). The tastiest idlis are made in Chennai, by none other than our famous chef, Dexter Murugan. Being very popular, he is flown from Marina to Miami, to serve idlis in the opening ceremony of icpc world finals ( which is happening right now ! ). There are N students and they are initially served with some idlis. Some of them are angry because they got less idlis than some other. Dexter decides to redistribute the idlis so they all get equal number of idlis finally. He recollects his father's code, "Son, if you ever want to redistribute idlis, follow this method. While there are two persons with unequal number of idlis, repeat the following step. Select two persons A and B, A having the maximum and B having the minimum number of idlis, currently. If there are multiple ways to select A (similarly B), select any one randomly. Let A and B have P and Q number of idlis respectively and R = ceil( ( P - Q ) / 2 ), Transfer R idlis from A to B." Given the initial number of idlis served to each student, find the number of times Dexter has to repeat the above step. If he can not distribute idlis equally by following the above method, print -1. ------ Notes ------ ceil(x) is the smallest integer that is not less than x. ------ Input ------ First line contains an integer T ( number of test cases, around 20 ). T cases follows. Each case starts with an integer N ( 1 ≤ N ≤ 3000 ). Next line contains an array A of N integers separated by spaces, the initial number of idlis served ( 0 ≤ A[i] ≤ N ) ------ Output ------ For each case, output the number of times Dexter has to repeat the given step to distribute idlis equally or -1 if its not possible. Note:There are multiple test sets, and the judge shows the sum of the time taken over all test sets of your submission, if Accepted. Time limit on each test set is 3 sec ----- Sample Input 1 ------ 3 4 1 2 2 3 2 1 2 7 1 2 3 4 5 6 7 ----- Sample Output 1 ------ 1 -1 3 ----- explanation 1 ------ Case 1 : { 1, 2, 2, 3}. Maximum 3, Minimum 1. R = ceil((3-1)/2) = 1. Transfer 1 idli from person having 3 idlis to the person having 1 idli. Each of them has 2 idlis now, so just 1 step is enough. Case 2 : {1,2} R = ceil((2-1)/2) = 1. {1,2} -> {2,1} -> {1,2} .... they can never get equal idlis :( Case 3 : Sorted arrays, in the order encountered {1, 2, 3, 4, 5, 6, 7} -> {2, 3, 4, 4, 4, 5, 6} -> {3, 4, 4, 4, 4, 4, 5} -> {4, 4, 4, 4, 4, 4, 4} Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given $n$ chips on a number line. The $i$-th chip is placed at the integer coordinate $x_i$. Some chips can have equal coordinates. You can perform each of the two following types of moves any (possibly, zero) number of times on any chip: Move the chip $i$ by $2$ to the left or $2$ to the right for free (i.e. replace the current coordinate $x_i$ with $x_i - 2$ or with $x_i + 2$); move the chip $i$ by $1$ to the left or $1$ to the right and pay one coin for this move (i.e. replace the current coordinate $x_i$ with $x_i - 1$ or with $x_i + 1$). Note that it's allowed to move chips to any integer coordinate, including negative and zero. Your task is to find the minimum total number of coins required to move all $n$ chips to the same coordinate (i.e. all $x_i$ should be equal after some sequence of moves). -----Input----- The first line of the input contains one integer $n$ ($1 \le n \le 100$) — the number of chips. The second line of the input contains $n$ integers $x_1, x_2, \dots, x_n$ ($1 \le x_i \le 10^9$), where $x_i$ is the coordinate of the $i$-th chip. -----Output----- Print one integer — the minimum total number of coins required to move all $n$ chips to the same coordinate. -----Examples----- Input 3 1 2 3 Output 1 Input 5 2 2 2 3 3 Output 2 -----Note----- In the first example you need to move the first chip by $2$ to the right and the second chip by $1$ to the right or move the third chip by $2$ to the left and the second chip by $1$ to the left so the answer is $1$. In the second example you need to move two chips with coordinate $3$ by $1$ to the left so the answer is $2$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Little Elephant from the Zoo of Lviv has an array A that consists of N positive integers. Let A[i] be the i-th number in this array (i = 1, 2, ..., N). Find the minimal number x > 1 such that x is a divisor of all integers from array A. More formally, this x should satisfy the following relations: A[1] mod x = 0, A[2] mod x = 0, ..., A[N] mod x = 0, where mod stands for the modulo operation. For example, 8 mod 3 = 2, 2 mod 2 = 0, 100 mod 5 = 0 and so on. If such number does not exist, output -1. -----Input----- The first line of the input contains a single integer T, the number of test cases. T test cases follow. The first line of each test case contains a single integer N, the size of the array A for the corresponding test case. The second line contains N space separated integers A[1], A[2], ..., A[N]. -----Output----- For each test case output a single line containing the answer for the corresponding test case. -----Constraints----- 1 ≤ T ≤ 100000 1 ≤ N ≤ 100000 The sum of values of N in each test file does not exceed 100000 1 ≤ A[i] ≤ 100000 -----Example----- Input: 2 3 2 4 8 3 4 7 5 Output: 2 -1 -----Explanation----- Case 1. Clearly 2 is a divisor of each of the numbers 2, 4 and 8. Since 2 is the least number greater than 1 then it is the answer. Case 2. Let's perform check for several first values of x. x4 mod x7 mod x5 mod x20113112403154206415740584759475 As we see each number up to 9 does not divide all of the numbers in the array. Clearly all larger numbers also will fail to do this. So there is no such number x > 1 and the answer is -1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically. Constraints * $1 \leq n, m \leq 1,000$ * $0 \leq a_i, b_i \leq 1,000$ Input The input is given in the following format. $n$ $a_0 \; a_1, ..., \; a_{n-1}$ $m$ $b_0 \; b_1, ..., \; b_{m-1}$ The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers. Output Print 1 $B$ is greater than $A$, otherwise 0. Examples Input 3 1 2 3 2 2 4 Output 1 Input 4 5 4 7 0 5 1 2 3 4 5 Output 0 Input 3 1 1 2 4 1 1 2 2 Output 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.