question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase. Tenten keeps a record for all events, and she ends up with a list of the following types of records: * + means that she placed another shuriken on the showcase; * - x means that the shuriken of price x was bought. Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out! Input The first line contains the only integer n (1≤ n≤ 10^5) standing for the number of shurikens. The following 2n lines describe the events in the format described above. It's guaranteed that there are exactly n events of the first type, and each price from 1 to n occurs exactly once in the events of the second type. Output If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO". In the first case the second line must contain n space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any. Examples Input 4 + + - 2 + - 3 + - 1 - 4 Output YES 4 2 3 1 Input 1 - 1 + Output NO Input 3 + + + - 2 - 1 - 3 Output NO Note In the first example Tenten first placed shurikens with prices 4 and 2. After this a customer came in and bought the cheapest shuriken which costed 2. Next, Tenten added a shuriken with price 3 on the showcase to the already placed 4-ryo. Then a new customer bought this 3-ryo shuriken. After this she added a 1-ryo shuriken. Finally, the last two customers bought shurikens 1 and 4, respectively. Note that the order [2, 4, 3, 1] is also valid. In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible. In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price 2. This is impossible since the shuriken was not the cheapest, we know that the 1-ryo shuriken was also there. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value $x$ that occurs in the array $2$ or more times. Take the first two occurrences of $x$ in this array (the two leftmost occurrences). Remove the left of these two occurrences, and the right one is replaced by the sum of this two values (that is, $2 \cdot x$). Determine how the array will look after described operations are performed. For example, consider the given array looks like $[3, 4, 1, 2, 2, 1, 1]$. It will be changed in the following way: $[3, 4, 1, 2, 2, 1, 1]~\rightarrow~[3, 4, 2, 2, 2, 1]~\rightarrow~[3, 4, 4, 2, 1]~\rightarrow~[3, 8, 2, 1]$. If the given array is look like $[1, 1, 3, 1, 1]$ it will be changed in the following way: $[1, 1, 3, 1, 1]~\rightarrow~[2, 3, 1, 1]~\rightarrow~[2, 3, 2]~\rightarrow~[3, 4]$. -----Input----- The first line contains a single integer $n$ ($2 \le n \le 150\,000$) — the number of elements in the array. The second line contains a sequence from $n$ elements $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{9}$) — the elements of the array. -----Output----- In the first line print an integer $k$ — the number of elements in the array after all the performed operations. In the second line print $k$ integers — the elements of the array after all the performed operations. -----Examples----- Input 7 3 4 1 2 2 1 1 Output 4 3 8 2 1 Input 5 1 1 3 1 1 Output 2 3 4 Input 5 10 40 20 50 30 Output 5 10 40 20 50 30 -----Note----- The first two examples were considered in the statement. In the third example all integers in the given array are distinct, so it will not change. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 playing euchre and you want to know the new score after finishing a hand. There are two teams and each hand consists of 5 tricks. The team who wins the majority of the tricks will win points but the number of points varies. To determine the number of points, you must know which team called trump, how many tricks each team won, and if anyone went alone. Scoring is as follows: For the team that called trump: - if they win 2 or less tricks -> other team wins 2 points - if they win 3 or 4 tricks -> 1 point - if they don't go alone and win 5 tricks -> 2 points - if they go alone and win 5 tricks -> 4 points Only the team who called trump can go alone and you will notice that it only increases your points if you win all 5 tricks. Your job is to create a method to calculate the new score. When reading the arguments, team 1 is represented by 1 and team 2 is represented by 2. All scores will be stored with this order: { team1, team2 }. Write your solution by modifying this code: ```python def update_score(current_score, called_trump, alone, tricks): ``` Your solution should implemented in the function "update_score". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task Miss X has only two combs in her possession, both of which are old and miss a tooth or two. She also has many purses of different length, in which she carries the combs. The only way they fit is horizontally and without overlapping. Given teeth' positions on both combs, find the minimum length of the purse she needs to take them with her. It is guaranteed that there is at least one tooth at each end of the comb. - Note, that the combs can not be rotated/reversed. # Example For `comb1 = "*..*" and comb2 = "*.*"`, the output should be `5` Although it is possible to place the combs like on the first picture, the best way to do this is either picture 2 or picture 3. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/combs/img/cbs.png?_tm=1484930552851) # Input/Output - `[input]` string `comb1` A comb is represented as a string. If there is an asterisk ('*') in the ith position, there is a tooth there. Otherwise there is a dot ('.'), which means there is a missing tooth on the comb. Constraints: 1 ≤ comb1.length ≤ 10. - `[input]` string `comb2` The second comb is represented in the same way as the first one. Constraints: 1 ≤ comb2.length ≤ 10. - `[output]` an integer The minimum length of a purse Miss X needs. Write your solution by modifying this code: ```python def combs(comb1, comb2): ``` Your solution should implemented in the function "combs". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are N students and M checkpoints on the xy-plane. The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j). When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance. The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|. Here, |x| denotes the absolute value of x. If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index. Which checkpoint will each student go to? -----Constraints----- - 1 \leq N,M \leq 50 - -10^8 \leq a_i,b_i,c_j,d_j \leq 10^8 - All input values are integers. -----Input----- The input is given from Standard Input in the following format: N M a_1 b_1 : a_N b_N c_1 d_1 : c_M d_M -----Output----- Print N lines. The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go. -----Sample Input----- 2 2 2 0 0 0 -1 0 1 0 -----Sample Output----- 2 1 The Manhattan distance between the first student and each checkpoint is: - For checkpoint 1: |2-(-1)|+|0-0|=3 - For checkpoint 2: |2-1|+|0-0|=1 The nearest checkpoint is checkpoint 2. Thus, the first line in the output should contain 2. The Manhattan distance between the second student and each checkpoint is: - For checkpoint 1: |0-(-1)|+|0-0|=1 - For checkpoint 2: |0-1|+|0-0|=1 When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain 1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. AtCoDeer the deer has found two positive integers, a and b. Determine whether the concatenation of a and b in this order is a square number. -----Constraints----- - 1 ≤ a,b ≤ 100 - a and b are integers. -----Input----- Input is given from Standard Input in the following format: a b -----Output----- If the concatenation of a and b in this order is a square number, print Yes; otherwise, print No. -----Sample Input----- 1 21 -----Sample Output----- Yes As 121 = 11 × 11, it is a square number. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease. Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank. To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present. At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one. You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k. Input The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k). Output Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank. Examples Input 4 4 1 2 2 3 Output 4 Input 4 3 1 1 1 1 Output 5 Note In the first example the ranks will be raised in the following manner: 1 2 2 3 → 2 2 3 4 → 2 3 4 4 → 3 4 4 4 → 4 4 4 4 Thus totals to 4 training sessions that require 4 golden coins. Read the inputs from stdin solve the problem and write the answer to stdout (do 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, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps. <image> Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1, ..., 2ak if and only if there exists a non-negative integer x such that 2a1 + 2a2 + ... + 2ak = 2x, i. e. the sum of those numbers is a power of two. Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps. Input The first line of input contains integer n (1 ≤ n ≤ 106), the number of weights. The second line contains n integers w1, ..., wn separated by spaces (0 ≤ wi ≤ 106 for each 1 ≤ i ≤ n), the powers of two forming the weights values. Output Print the minimum number of steps in a single line. Examples Input 5 1 1 2 3 3 Output 2 Input 4 0 1 2 3 Output 4 Note In the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two. In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 was an electronic store heist last night. All keyboards which were in the store yesterday were numbered in ascending order from some integer number $x$. For example, if $x = 4$ and there were $3$ keyboards in the store, then the devices had indices $4$, $5$ and $6$, and if $x = 10$ and there were $7$ of them then the keyboards had indices $10$, $11$, $12$, $13$, $14$, $15$ and $16$. After the heist, only $n$ keyboards remain, and they have indices $a_1, a_2, \dots, a_n$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $x$ nor the number of keyboards in the store before the heist. -----Input----- The first line contains single integer $n$ $(1 \le n \le 1\,000)$ — the number of keyboards in the store that remained after the heist. The second line contains $n$ distinct integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^{9})$ — the indices of the remaining keyboards. The integers $a_i$ are given in arbitrary order and are pairwise distinct. -----Output----- Print the minimum possible number of keyboards that have been stolen if the staff remember neither $x$ nor the number of keyboards in the store before the heist. -----Examples----- Input 4 10 13 12 8 Output 2 Input 5 7 5 6 4 8 Output 0 -----Note----- In the first example, if $x=8$ then minimum number of stolen keyboards is equal to $2$. The keyboards with indices $9$ and $11$ were stolen during the heist. In the second example, if $x=4$ then nothing was stolen during the heist. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem? Input The first input line contains integer n (1 ≤ n ≤ 105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value. Output Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only. Examples Input 4 1 2 3 3 Output 1 Input 5 1 2 3 4 5 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. For this problem you must create a program that says who ate the last cookie. If the input is a string then "Zach" ate the cookie. If the input is a float or an int then "Monica" ate the cookie. If the input is anything else "the dog" ate the cookie. The way to return the statement is: "Who ate the last cookie? It was (name)!" Ex: Input = "hi" --> Output = "Who ate the last cookie? It was Zach! (The reason you return Zach is because the input is a string) Note: Make sure you return the correct message with correct spaces and punctuation. Please leave feedback for this kata. Cheers! Write your solution by modifying this code: ```python def cookie(x): ``` Your solution should implemented in the function "cookie". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let x be an array of integers x = [x_1, x_2, ..., x_n]. Let's define B(x) as a minimal size of a partition of x into subsegments such that all elements in each subsegment are equal. For example, B([3, 3, 6, 1, 6, 6, 6]) = 4 using next partition: [3, 3\ |\ 6\ |\ 1\ |\ 6, 6, 6]. Now you don't have any exact values of x, but you know that x_i can be any integer value from [l_i, r_i] (l_i ≤ r_i) uniformly at random. All x_i are independent. Calculate expected value of (B(x))^2, or E((B(x))^2). It's guaranteed that the expected value can be represented as rational fraction P/Q where (P, Q) = 1, so print the value P ⋅ Q^{-1} mod 10^9 + 7. Input The first line contains the single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the size of the array x. The second line contains n integers l_1, l_2, ..., l_n (1 ≤ l_i ≤ 10^9). The third line contains n integers r_1, r_2, ..., r_n (l_i ≤ r_i ≤ 10^9). Output Print the single integer — E((B(x))^2) as P ⋅ Q^{-1} mod 10^9 + 7. Examples Input 3 1 1 1 1 2 3 Output 166666673 Input 3 3 4 5 4 5 6 Output 500000010 Note Let's describe all possible values of x for the first sample: * [1, 1, 1]: B(x) = 1, B^2(x) = 1; * [1, 1, 2]: B(x) = 2, B^2(x) = 4; * [1, 1, 3]: B(x) = 2, B^2(x) = 4; * [1, 2, 1]: B(x) = 3, B^2(x) = 9; * [1, 2, 2]: B(x) = 2, B^2(x) = 4; * [1, 2, 3]: B(x) = 3, B^2(x) = 9; So E = 1/6 (1 + 4 + 4 + 9 + 4 + 9) = 31/6 or 31 ⋅ 6^{-1} = 166666673. All possible values of x for the second sample: * [3, 4, 5]: B(x) = 3, B^2(x) = 9; * [3, 4, 6]: B(x) = 3, B^2(x) = 9; * [3, 5, 5]: B(x) = 2, B^2(x) = 4; * [3, 5, 6]: B(x) = 3, B^2(x) = 9; * [4, 4, 5]: B(x) = 2, B^2(x) = 4; * [4, 4, 6]: B(x) = 2, B^2(x) = 4; * [4, 5, 5]: B(x) = 2, B^2(x) = 4; * [4, 5, 6]: B(x) = 3, B^2(x) = 9; So E = 1/8 (9 + 9 + 4 + 9 + 4 + 4 + 4 + 9) = 52/8 or 13 ⋅ 2^{-1} = 500000010. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below. Fortunately, you are a skilled magician, capable of causing explosions that damage monsters. In one explosion, you can damage monsters as follows: - Select an alive monster, and cause an explosion centered at that monster. The health of the monster at the center of the explosion will decrease by A, and the health of each of the other monsters will decrease by B. Here, A and B are predetermined parameters, and A > B holds. At least how many explosions do you need to cause in order to vanish all the monsters? -----Constraints----- - All input values are integers. - 1 ≤ N ≤ 10^5 - 1 ≤ B < A ≤ 10^9 - 1 ≤ h_i ≤ 10^9 -----Input----- Input is given from Standard Input in the following format: N A B h_1 h_2 : h_N -----Output----- Print the minimum number of explosions that needs to be caused in order to vanish all the monsters. -----Sample Input----- 4 5 3 8 7 4 2 -----Sample Output----- 2 You can vanish all the monsters in two explosion, as follows: - First, cause an explosion centered at the monster with 8 health. The healths of the four monsters become 3, 4, 1 and -1, respectively, and the last monster vanishes. - Second, cause an explosion centered at the monster with 4 health remaining. The healths of the three remaining monsters become 0, -1 and -2, respectively, and all the monsters are now vanished. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ilya is an experienced player in tic-tac-toe on the 4 × 4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not. The rules of tic-tac-toe on the 4 × 4 field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets three of his signs in a row next to each other (horizontal, vertical or diagonal). -----Input----- The tic-tac-toe position is given in four lines. Each of these lines contains four characters. Each character is '.' (empty cell), 'x' (lowercase English letter x), or 'o' (lowercase English letter o). It is guaranteed that the position is reachable playing tic-tac-toe, and it is Ilya's turn now (in particular, it means that the game is not finished). It is possible that all the cells are empty, it means that the friends left without making single turn. -----Output----- Print single line: "YES" in case Ilya could have won by making single turn, and "NO" otherwise. -----Examples----- Input xx.. .oo. x... oox. Output YES Input x.ox ox.. x.o. oo.x Output NO Input x..x ..oo o... x.xo Output YES Input o.x. o... .x.. ooxx Output NO -----Note----- In the first example Ilya had two winning moves: to the empty cell in the left column and to the leftmost empty cell in the first row. In the second example it wasn't possible to win by making single turn. In the third example Ilya could have won by placing X in the last row between two existing Xs. In the fourth example it wasn't possible to win by making single turn. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sehr Sus is an infinite hexagonal grid as pictured below, controlled by MennaFadali, ZerooCool and Hosssam. They love equilateral triangles and want to create $n$ equilateral triangles on the grid by adding some straight lines. The triangles must all be empty from the inside (in other words, no straight line or hexagon edge should pass through any of the triangles). You are allowed to add straight lines parallel to the edges of the hexagons. Given $n$, what is the minimum number of lines you need to add to create at least $n$ equilateral triangles as described? Adding two red lines results in two new yellow equilateral triangles. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^5$) — the number of test cases. Then $t$ test cases follow. Each test case contains a single integer $n$ ($1 \le n \le 10^{9}$) — the required number of equilateral triangles. -----Output----- For each test case, print the minimum number of lines needed to have $n$ or more equilateral triangles. -----Examples----- Input 4 1 2 3 4567 Output 2 2 3 83 -----Note----- In the first and second test cases only 2 lines are needed. After adding the first line, no equilateral triangles will be created no matter where it is added. But after adding the second line, two more triangles will be created at once. In the third test case, the minimum needed is 3 lines as shown below. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 N integers A_1, ..., A_N, compute A_1 \times ... \times A_N. However, if the result exceeds 10^{18}, print -1 instead. -----Constraints----- - 2 \leq N \leq 10^5 - 0 \leq A_i \leq 10^{18} - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N A_1 ... A_N -----Output----- Print the value A_1 \times ... \times A_N as an integer, or -1 if the value exceeds 10^{18}. -----Sample Input----- 2 1000000000 1000000000 -----Sample Output----- 1000000000000000000 We have 1000000000 \times 1000000000 = 1000000000000000000. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior. There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate superior, the immediate superior of the his immediate superior, and so on. For example, if there are three workers in the company, from which the first is the chief, the second worker's immediate superior is the first, the third worker's immediate superior is the second, then the third worker has two superiors, one of them is immediate and one not immediate. The chief is a superior to all the workers except himself. Some of the workers were in a hurry and made a mistake. You are to find the minimum number of workers that could make a mistake. -----Input----- The first line contains two positive integers n and s (1 ≤ n ≤ 2·10^5, 1 ≤ s ≤ n) — the number of workers and the id of the chief. The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ n - 1), where a_{i} is the number of superiors (not only immediate) the worker with id i reported about. -----Output----- Print the minimum number of workers that could make a mistake. -----Examples----- Input 3 2 2 0 2 Output 1 Input 5 3 1 0 0 4 1 Output 2 -----Note----- In the first example it is possible that only the first worker made a mistake. Then: the immediate superior of the first worker is the second worker, the immediate superior of the third worker is the first worker, the second worker is the chief. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array. More formally, given a suffix array of length $n$ and having an alphabet size $k$, count the number of strings that produce such a suffix array. Let $s$ be a string of length $n$. Then the $i$-th suffix of $s$ is the substring $s[i \ldots n-1]$. A suffix array is the array of integers that represent the starting indexes of all the suffixes of a given string, after the suffixes are sorted in the lexicographic order. For example, the suffix array of oolimry is $[3,2,4,1,0,5,6]$ as the array of sorted suffixes is $[{imry},{limry},{mry},{olimry},{oolimry},{ry},{y}]$. A string $x$ is lexicographically smaller than string $y$, if either $x$ is a prefix of $y$ (and $x\neq y$), or there exists such $i$ that $x_i < y_i$, and for any $1\leq j < i$ , $x_j = y_j$. -----Input----- The first line contain 2 integers $n$ and $k$ ($1 \leq n \leq 200000,1 \leq k \leq 200000$) — the length of the suffix array and the alphabet size respectively. The second line contains $n$ integers $s_0, s_1, s_2, \ldots, s_{n-1}$ ($0 \leq s_i \leq n-1$) where $s_i$ is the $i$-th element of the suffix array i.e. the starting position of the $i$-th lexicographically smallest suffix. It is guaranteed that for all $0 \leq i< j \leq n-1$, $s_i \neq s_j$. -----Output----- Print how many strings produce such a suffix array. Since the number can be very large, print the answer modulo $998244353$. -----Examples----- Input 3 2 0 2 1 Output 1 Input 5 1 0 1 2 3 4 Output 0 Input 6 200000 0 1 2 3 4 5 Output 822243495 Input 7 6 3 2 4 1 0 5 6 Output 36 -----Note----- In the first test case, "abb" is the only possible solution. In the second test case, it can be easily shown no possible strings exist as all the letters have to be equal. In the fourth test case, one possible string is "ddbacef". Please remember to print your answers modulo $998244353$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. We have N squares assigned the numbers 1,2,3,\ldots,N. Each square has an integer written on it, and the integer written on Square i is a_i. How many squares i satisfy both of the following conditions? * The assigned number, i, is odd. * The written integer is odd. Constraints * All values in input are integers. * 1 \leq N, a_i \leq 100 Input Input is given from Standard Input in the following format: N a_1 a_2 \cdots a_N Output Print the number of squares that satisfy both of the conditions. Examples Input 5 1 3 4 5 7 Output 2 Input 15 13 76 46 15 50 98 93 77 31 43 84 90 6 24 14 Output 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Firecrackers scare Nian the monster, but they're wayyyyy too noisy! Maybe fireworks make a nice complement. Little Tommy is watching a firework show. As circular shapes spread across the sky, a splendid view unfolds on the night of Lunar New Year's eve. A wonder strikes Tommy. How many regions are formed by the circles on the sky? We consider the sky as a flat plane. A region is a connected part of the plane with positive area, whose bound consists of parts of bounds of the circles and is a curve or several curves without self-intersections, and that does not contain any curve other than its boundaries. Note that exactly one of the regions extends infinitely. -----Input----- The first line of input contains one integer n (1 ≤ n ≤ 3), denoting the number of circles. The following n lines each contains three space-separated integers x, y and r ( - 10 ≤ x, y ≤ 10, 1 ≤ r ≤ 10), describing a circle whose center is (x, y) and the radius is r. No two circles have the same x, y and r at the same time. -----Output----- Print a single integer — the number of regions on the plane. -----Examples----- Input 3 0 0 1 2 0 1 4 0 1 Output 4 Input 3 0 0 2 3 0 2 6 0 2 Output 6 Input 3 0 0 2 2 0 2 1 1 2 Output 8 -----Note----- For the first example, $000$ For the second example, [Image] For the third example, $\text{Q)}$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees! Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and sees his creation demolished, he'll get extremely upset. To not let that happen, Dima has to recover the binary search tree. Luckily, he noticed that any two vertices connected by a direct edge had their greatest common divisor value exceed $1$. Help Dima construct such a binary search tree or determine that it's impossible. The definition and properties of a binary search tree can be found here. -----Input----- The first line contains the number of vertices $n$ ($2 \le n \le 700$). The second line features $n$ distinct integers $a_i$ ($2 \le a_i \le 10^9$) — the values of vertices in ascending order. -----Output----- If it is possible to reassemble the binary search tree, such that the greatest common divisor of any two vertices connected by the edge is greater than $1$, print "Yes" (quotes for clarity). Otherwise, print "No" (quotes for clarity). -----Examples----- Input 6 3 6 9 18 36 108 Output Yes Input 2 7 17 Output No Input 9 4 8 10 12 15 18 33 44 81 Output Yes -----Note----- The picture below illustrates one of the possible trees for the first example. [Image] The picture below illustrates one of the possible trees for the third example. [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. -----Problem Statement----- Write a program that accepts a number, n, and outputs the same. -----Input----- The only line contains a single integer. -----Output----- Output the answer in a single line. -----Constraints----- - 0 ≤ n ≤ 105 -----Sample Input----- 123 -----Sample Output----- 123 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the students are back in hostel after a long time, the gamers have decided to have a LAN gaming competition to find out who has utilized his time in gaming during vacations. They play "Counter ATOD". However, the scoring of this game is weird. There are N players and there are M rounds. Initially, each player has 0 points. The player gets the points only if he has won the round. Points can be negative too(weird). The winner of the whole contest is the one who has maximum points after any round. However, it isn't necessary at all that the winner will have maximum points at the end of the game. As the scoring is pretty weird, they asks for your help. Input Format : First line of input will consist of N and M denoting the number of players and rounds respectively. Next M lines will contain the name of the player who won the round and the points P he earned after that round. First round will always have positive points. Output Format: The only line of output will contain the name of the winner who got maximum points in the contest at any point of the game. In case of draw, the winner will be the player who got maximum points earlier. Constraints : 1 ≤ N ≤ 100 1 ≤ M ≤ 5000 1 ≤ Length of name ≤ 15 -10^6 ≤ P ≤ 10^6 Problem Setter : Swastik Mundra SAMPLE INPUT 3 5 Murliwala 5 Mithaiwala 4 Mithaiwala 4 Mithaiwala -2 Mirchiwala 8 SAMPLE OUTPUT Mithaiwala Explanation After round 1, Murliwala wins the round and gains 5 points but as Mirchiwala and Mithaiwala has not won the round, they will not gain any point. After round 2, Mithaiwala wins the round and gains 4 points. However Murliwala has still 5 points and Mirchiwala has 0 points. After round 3, Mithaiwala wins the round and gains 4 points. His total is 8 points now and is maximum. However Murliwala has still 5 points and Mirchiwala has 0 points. After round 4, Mithaiwala wins again and gains -2 points which brings his total to 6 points. After round 5, Mirchiwala wins and gains 8 points. Maximum points throughout the game was 8 but as Murliwala earned 8 points first he is the winner. However, the total of Mithaiwala at the end was 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. Drazil likes heap very much. So he created a problem with heap: There is a max heap with a height h implemented on the array. The details of this heap are the following: This heap contains exactly 2^h - 1 distinct positive non-zero integers. All integers are distinct. These numbers are stored in the array a indexed from 1 to 2^h-1. For any 1 < i < 2^h, a[i] < a[\left ⌊{i/2}\right ⌋]. Now we want to reduce the height of this heap such that the height becomes g with exactly 2^g-1 numbers in heap. To reduce the height, we should perform the following action 2^h-2^g times: Choose an index i, which contains an element and call the following function f in index i: <image> Note that we suppose that if a[i]=0, then index i don't contain an element. After all operations, the remaining 2^g-1 element must be located in indices from 1 to 2^g-1. Now Drazil wonders what's the minimum possible sum of the remaining 2^g-1 elements. Please find this sum and find a sequence of the function calls to achieve this value. Input The first line of the input contains an integer t (1 ≤ t ≤ 70 000): the number of test cases. Each test case contain two lines. The first line contains two integers h and g (1 ≤ g < h ≤ 20). The second line contains n = 2^h-1 distinct positive integers a[1], a[2], …, a[n] (1 ≤ a[i] < 2^{20}). For all i from 2 to 2^h - 1, a[i] < a[\left ⌊{i/2}\right ⌋]. The total sum of n is less than 2^{20}. Output For each test case, print two lines. The first line should contain one integer denoting the minimum sum after reducing the height of heap to g. The second line should contain 2^h - 2^g integers v_1, v_2, …, v_{2^h-2^g}. In i-th operation f(v_i) should be called. Example Input 2 3 2 7 6 3 5 4 2 1 3 2 7 6 5 4 3 2 1 Output 10 3 2 3 1 8 2 1 3 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have $n$ sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let $S$ be the area of the rectangle and $P$ be the perimeter of the rectangle. The chosen rectangle should have the value $\frac{P^2}{S}$ minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. -----Input----- The first line contains a single integer $T$ ($T \ge 1$) — the number of lists of sticks in the testcase. Then $2T$ lines follow — lines $(2i - 1)$ and $2i$ of them describe the $i$-th list. The first line of the pair contains a single integer $n$ ($4 \le n \le 10^6$) — the number of sticks in the $i$-th list. The second line of the pair contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_j \le 10^4$) — lengths of the sticks in the $i$-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all $T$ lists doesn't exceed $10^6$ in each testcase. -----Output----- Print $T$ lines. The $i$-th line should contain the answer to the $i$-th list of the input. That is the lengths of the four sticks you choose from the $i$-th list, so that they form a rectangle and the value $\frac{P^2}{S}$ of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. -----Example----- Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 -----Note----- There is only one way to choose four sticks in the first list, they form a rectangle with sides $2$ and $7$, its area is $2 \cdot 7 = 14$, perimeter is $2(2 + 7) = 18$. $\frac{18^2}{14} \approx 23.143$. The second list contains subsets of four sticks that can form rectangles with sides $(1, 2)$, $(2, 8)$ and $(1, 8)$. Their values are $\frac{6^2}{2} = 18$, $\frac{20^2}{16} = 25$ and $\frac{18^2}{8} = 40.5$, respectively. The minimal one of them is the rectangle $(1, 2)$. You can choose any four of the $5$ given sticks from the third list, they will form a square with side $5$, which is still a rectangle with sides $(5, 5)$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Initially Ildar has an empty array. He performs $n$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset $[0, 2, 3]$ is $1$, while the mex of the multiset $[1, 2, 1]$ is $0$. More formally, on the step $m$, when Ildar already has an array $a_1, a_2, \ldots, a_{m-1}$, he chooses some subset of indices $1 \leq i_1 < i_2 < \ldots < i_k < m$ (possibly, empty), where $0 \leq k < m$, and appends the $mex(a_{i_1}, a_{i_2}, \ldots a_{i_k})$ to the end of the array. After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $a_1, a_2, \ldots, a_n$ the minimum step $t$ such that he has definitely made a mistake on at least one of the steps $1, 2, \ldots, t$, or determine that he could have obtained this array without mistakes. -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 100\,000$) — the number of steps Ildar made. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 10^9$) — the array Ildar obtained. -----Output----- If Ildar could have chosen the subsets on each step in such a way that the resulting array is $a_1, a_2, \ldots, a_n$, print $-1$. Otherwise print a single integer $t$ — the smallest index of a step such that a mistake was made on at least one step among steps $1, 2, \ldots, t$. -----Examples----- Input 4 0 1 2 1 Output -1 Input 3 1 0 1 Output 1 Input 4 0 1 2 239 Output 4 -----Note----- In the first example it is possible that Ildar made no mistakes. Here is the process he could have followed. $1$-st step. The initial array is empty. He can choose an empty subset and obtain $0$, because the mex of an empty set is $0$. Appending this value to the end he gets the array $[0]$. $2$-nd step. The current array is $[0]$. He can choose a subset $[0]$ and obtain an integer $1$, because $mex(0) = 1$. Appending this value to the end he gets the array $[0,1]$. $3$-rd step. The current array is $[0,1]$. He can choose a subset $[0,1]$ and obtain an integer $2$, because $mex(0,1) = 2$. Appending this value to the end he gets the array $[0,1,2]$. $4$-th step. The current array is $[0,1,2]$. He can choose a subset $[0]$ and obtain an integer $1$, because $mex(0) = 1$. Appending this value to the end he gets the array $[0,1,2,1]$. Thus, he can get the array without mistakes, so the answer is $-1$. In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from $0$. In the third example he could have obtained $[0, 1, 2]$ without mistakes, but $239$ is definitely wrong. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 are a positive integer N and a string S of length N consisting of lowercase English letters. Determine whether the string is a concatenation of two copies of some string. That is, determine whether there is a string T such that S = T + T. -----Constraints----- - 1 \leq N \leq 100 - S consists of lowercase English letters. - |S| = N -----Input----- Input is given from Standard Input in the following format: N S -----Output----- If S is a concatenation of two copies of some string, print Yes; otherwise, print No. -----Sample Input----- 6 abcabc -----Sample Output----- Yes Let T = abc, and S = T + T. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In this task you need to process a set of stock exchange orders and use them to create order book. An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price p_{i}, direction d_{i} — buy or sell, and integer q_{i}. This means that the participant is ready to buy or sell q_{i} stocks at price p_{i} for one stock. A value q_{i} is also known as a volume of an order. All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders. An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order. An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book. You are given n stock exhange orders. Your task is to print order book of depth s for these orders. -----Input----- The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth. Next n lines contains a letter d_{i} (either 'B' or 'S'), an integer p_{i} (0 ≤ p_{i} ≤ 10^5) and an integer q_{i} (1 ≤ q_{i} ≤ 10^4) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order. -----Output----- Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input. -----Examples----- Input 6 2 B 10 3 S 50 2 S 40 1 S 50 6 B 20 4 B 25 10 Output S 50 8 S 40 1 B 25 10 B 20 4 -----Note----- Denote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample. You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 C Medical Checkup Students of the university have to go for a medical checkup, consisting of lots of checkup items, numbered 1, 2, 3, and so on. Students are now forming a long queue, waiting for the checkup to start. Students are also numbered 1, 2, 3, and so on, from the top of the queue. They have to undergo checkup items in the order of the item numbers, not skipping any of them nor changing the order. The order of students should not be changed either. Multiple checkup items can be carried out in parallel, but each item can be carried out for only one student at a time. Students have to wait in queues of their next checkup items until all the others before them finish. Each of the students is associated with an integer value called health condition. For a student with the health condition $h$, it takes $h$ minutes to finish each of the checkup items. You may assume that no interval is needed between two students on the same checkup item or two checkup items for a single student. Your task is to find the items students are being checked up or waiting for at a specified time $t$. Input The input consists of a single test case in the following format. $n$ $t$ $h_1$ ... $h_n$ $n$ and $t$ are integers. $n$ is the number of the students ($1 \leq n \leq 10^5$). $t$ specifies the time of our concern ($0 \leq t \leq 10^9$). For each $i$, the integer $h_i$ is the health condition of student $i$ ($1 \leq h_ \leq 10^9$). Output Output $n$ lines each containing a single integer. The $i$-th line should contain the checkup item number of the item which the student $i$ is being checked up or is waiting for, at ($t+0.5$) minutes after the checkup starts. You may assume that all the students are yet to finish some of the checkup items at that moment. Sample Input 1 3 20 5 7 3 Sample Output 1 5 3 2 Sample Input 2 5 1000000000 5553 2186 3472 2605 1790 Sample Output 2 180083 180083 180082 180082 180082 Example Input 3 20 5 7 3 Output 5 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. Vasya has found a piece of paper with an array written on it. The array consists of n integers a_1, a_2, ..., a_{n}. Vasya noticed that the following condition holds for the array a_{i} ≤ a_{i} + 1 ≤ 2·a_{i} for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a_1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the size of the array. The second line contains space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — the original array. It is guaranteed that the condition a_{i} ≤ a_{i} + 1 ≤ 2·a_{i} fulfills for any positive integer i (i < n). -----Output----- In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number a_{i}. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a_1. If there are multiple solutions, you are allowed to print any of them. -----Examples----- Input 4 1 2 3 5 Output +++- Input 3 3 3 5 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. Generate and return **all** possible increasing arithmetic progressions of six primes `[a, b, c, d, e, f]` between the given limits. Note: the upper and lower limits are inclusive. An arithmetic progression is a sequence where the difference between consecutive numbers is the same, such as: 2, 4, 6, 8. A prime number is a number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11) Your solutions should be returned as lists inside a list in ascending order of the first item (if there are multiple lists with same first item, return in ascending order for the second item etc) are the e.g: `[ [a, b, c, d, e, f], [g, h, i, j, k, l] ]` where `a < g`. If there are no solutions, return an empty list: `[]` ## Examples Write your solution by modifying this code: ```python def primes_a_p(lower_limit, upper_limit): ``` Your solution should implemented in the function "primes_a_p". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. В самолёте есть n рядов мест. Если смотреть на ряды сверху, то в каждом ряду есть 3 места слева, затем проход между рядами, затем 4 центральных места, затем ещё один проход между рядами, а затем ещё 3 места справа. Известно, что некоторые места уже заняты пассажирами. Всего есть два вида пассажиров — статусные (те, которые часто летают) и обычные. Перед вами стоит задача рассадить ещё k обычных пассажиров так, чтобы суммарное число соседей у статусных пассажиров было минимально возможным. Два пассажира считаются соседями, если они сидят в одном ряду и между ними нет других мест и прохода между рядами. Если пассажир является соседним пассажиром для двух статусных пассажиров, то его следует учитывать в сумме соседей дважды. -----Входные данные----- В первой строке следуют два целых числа n и k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10·n) — количество рядов мест в самолёте и количество пассажиров, которых нужно рассадить. Далее следует описание рядов мест самолёта по одному ряду в строке. Если очередной символ равен '-', то это проход между рядами. Если очередной символ равен '.', то это свободное место. Если очередной символ равен 'S', то на текущем месте будет сидеть статусный пассажир. Если очередной символ равен 'P', то на текущем месте будет сидеть обычный пассажир. Гарантируется, что количество свободных мест не меньше k. Гарантируется, что все ряды удовлетворяют описанному в условии формату. -----Выходные данные----- В первую строку выведите минимальное суммарное число соседей у статусных пассажиров. Далее выведите план рассадки пассажиров, который минимизирует суммарное количество соседей у статусных пассажиров, в том же формате, что и во входных данных. Если в свободное место нужно посадить одного из k пассажиров, выведите строчную букву 'x' вместо символа '.'. -----Примеры----- Входные данные 1 2 SP.-SS.S-S.S Выходные данные 5 SPx-SSxS-S.S Входные данные 4 9 PP.-PPPS-S.S PSP-PPSP-.S. .S.-S..P-SS. P.S-P.PP-PSP Выходные данные 15 PPx-PPPS-S.S PSP-PPSP-xSx xSx-SxxP-SSx P.S-PxPP-PSP -----Примечание----- В первом примере нужно посадить ещё двух обычных пассажиров. Для минимизации соседей у статусных пассажиров, нужно посадить первого из них на третье слева место, а второго на любое из оставшихся двух мест, так как независимо от выбора места он станет соседом двух статусных пассажиров. Изначально, у статусного пассажира, который сидит на самом левом месте уже есть сосед. Также на четвёртом и пятом местах слева сидят статусные пассажиры, являющиеся соседями друг для друга (что добавляет к сумме 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. When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million. Petya wanted to modernize the words we use for numbers and invented a word petricium that represents number k. Moreover, petricium la petricium stands for number k2, petricium la petricium la petricium stands for k3 and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title. Petya's invention brought on a challenge that needed to be solved quickly: does some number l belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it. Input The first input line contains integer number k, the second line contains integer number l (2 ≤ k, l ≤ 231 - 1). Output You should print in the first line of the output "YES", if the number belongs to the set petriciumus cifera and otherwise print "NO". If the number belongs to the set, then print on the seconds line the only number — the importance of number l. Examples Input 5 25 Output YES 1 Input 3 8 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. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a_0 + a_1x^1 + ... + a_{n}x^{n}. Numbers a_{i} are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that $P(t) = a$, and $P(P(t)) = b$, where $t, a$ and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. -----Input----- The input contains three integer positive numbers $t, a, b$ no greater than 10^18. -----Output----- If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 10^9 + 7. -----Examples----- Input 2 2 2 Output 2 Input 2 3 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. # Introduction Ka ka ka cypher is a cypher used by small children in some country. When a girl wants to pass something to the other girls and there are some boys nearby, she can use Ka cypher. So only the other girls are able to understand her. She speaks using KA, ie.: `ka thi ka s ka bo ka y ka i ka s ka u ka gly` what simply means `this boy is ugly`. # Task Write a function `KaCokadekaMe` (`ka_co_ka_de_ka_me` in Python) that accepts a string word and returns encoded message using ka cypher. Our rules: - The encoded word should start from `ka`. - The `ka` goes after vowel (a,e,i,o,u) - When there is multiple vowels together, the `ka` goes only after the last `vowel` - When the word is finished by a vowel, do not add the `ka` after # Input/Output The `word` string consists of only lowercase and uppercase characters. There is only 1 word to convert - no white spaces. # Example ``` KaCokadekaMe("a"); //=> "kaa" KaCokadekaMe("ka"); //=> "kaka" KaCokadekaMe("aa"); //=> "kaaa" KaCokadekaMe("Abbaa"); //=> kaAkabbaa KaCokadekaMe("maintenance"); //=> kamaikantekanakance KaCokadekaMe("Woodie"); //=> kaWookadie KacokadekaMe("Incomprehensibilities"); //=> kaIkancokamprekahekansikabikalikatiekas ``` # Remark Ka cypher's country residents, please don't hate me for simplifying the way how we divide the words into "syllables" in the Kata. I don't want to make it too hard for other nations ;-P Write your solution by modifying this code: ```python def ka_co_ka_de_ka_me(word): ``` Your solution should implemented in the function "ka_co_ka_de_ka_me". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This function should test if the `factor` is a factor of `base`. Return `true` if it is a factor or `false` if it is not. ## About factors Factors are numbers you can multiply together to get another number. 2 and 3 are factors of 6 because: `2 * 3 = 6` - You can find a factor by dividing numbers. If the remainder is 0 then the number is a factor. - You can use the mod operator (`%`) in most languages to check for a remainder For example 2 is not a factor of 7 because: `7 % 2 = 1` Note: `base` is a non-negative number, `factor` is a positive number. Write your solution by modifying this code: ```python def check_for_factor(base, factor): ``` Your solution should implemented in the function "check_for_factor". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are a_{i} oskols sitting on the i-th wire. $40$ Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i - 1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i + 1, if there exists no such wire they fly away. Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots. -----Input----- The first line of the input contains an integer n, (1 ≤ n ≤ 100). The next line contains a list of space-separated integers a_1, a_2, ..., a_{n}, (0 ≤ a_{i} ≤ 100). The third line contains an integer m, (0 ≤ m ≤ 100). Each of the next m lines contains two integers x_{i} and y_{i}. The integers mean that for the i-th time Shaass shoot the y_{i}-th (from left) bird on the x_{i}-th wire, (1 ≤ x_{i} ≤ n, 1 ≤ y_{i}). It's guaranteed there will be at least y_{i} birds on the x_{i}-th wire at that moment. -----Output----- On the i-th line of the output print the number of birds on the i-th wire. -----Examples----- Input 5 10 10 10 10 10 5 2 5 3 13 2 12 1 13 4 6 Output 0 12 5 0 16 Input 3 2 4 1 1 2 2 Output 3 0 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. An atom of element X can exist in n distinct states with energies E_1 < E_2 < ... < E_{n}. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens: initially the atom is in the state i, we spend E_{k} - E_{i} energy to put the atom in the state k, the atom emits a photon with useful energy E_{k} - E_{j} and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy E_{j} - E_{i}, the process repeats from step 1. Let's define the energy conversion efficiency as $\eta = \frac{E_{k} - E_{j}}{E_{k} - E_{i}}$, i. e. the ration between the useful energy of the photon and spent energy. Due to some limitations, Arkady can only choose such three states that E_{k} - E_{i} ≤ U. Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints. -----Input----- The first line contains two integers n and U (3 ≤ n ≤ 10^5, 1 ≤ U ≤ 10^9) — the number of states and the maximum possible difference between E_{k} and E_{i}. The second line contains a sequence of integers E_1, E_2, ..., E_{n} (1 ≤ E_1 < E_2... < E_{n} ≤ 10^9). It is guaranteed that all E_{i} are given in increasing order. -----Output----- If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number η — the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10^{ - 9}. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if $\frac{|a - b|}{\operatorname{max}(1,|b|)} \leq 10^{-9}$. -----Examples----- Input 4 4 1 3 5 7 Output 0.5 Input 10 8 10 13 15 16 17 19 20 22 24 25 Output 0.875 Input 3 1 2 5 10 Output -1 -----Note----- In the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to $\eta = \frac{5 - 3}{5 - 1} = 0.5$. In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to $\eta = \frac{24 - 17}{24 - 16} = 0.875$. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so. Operation: Choose one character of S and replace it with a different character. -----Constraints----- - S and T have lengths between 1 and 2\times 10^5 (inclusive). - S and T consists of lowercase English letters. - S and T have equal lengths. -----Input----- Input is given from Standard Input in the following format: S T -----Output----- Print the answer. -----Sample Input----- cupofcoffee cupofhottea -----Sample Output----- 4 We can achieve the objective in four operations, such as the following: - First, replace the sixth character c with h. - Second, replace the eighth character f with t. - Third, replace the ninth character f with t. - Fourth, replace the eleventh character e with a. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given a side length `n`, traveling only right and down how many ways are there to get from the top left corner to the bottom right corner of an `n by n` grid? Your mission is to write a program to do just that! Add code to `route(n)` that returns the number of routes for a grid `n by n` (if n is less than 1 return 0). Examples: -100 -> 0 1 -> 2 2 -> 6 20 -> 137846528820 Note: you're traveling on the edges of the squares in the grid not the squares themselves. PS.If anyone has any suggestions of how to improve this kata please let me know. Write your solution by modifying this code: ```python def routes(n): ``` Your solution should implemented in the function "routes". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle α. [Image] Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture. -----Input----- The first line contains three integers w, h, α (1 ≤ w, h ≤ 10^6; 0 ≤ α ≤ 180). Angle α is given in degrees. -----Output----- In a single line print a real number — the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10^{ - 6}. -----Examples----- Input 1 1 45 Output 0.828427125 Input 6 4 30 Output 19.668384925 -----Note----- The second sample has been drawn on the picture above. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's assume that * v(n) is the largest prime number, that does not exceed n; * u(n) is the smallest prime number strictly greater than n. Find <image>. Input The first line contains integer t (1 ≤ t ≤ 500) — the number of testscases. Each of the following t lines of the input contains integer n (2 ≤ n ≤ 109). Output Print t lines: the i-th of them must contain the answer to the i-th test as an irreducible fraction "p/q", where p, q are integers, q > 0. Examples Input 2 2 3 Output 1/6 7/30 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Caracal is fighting with a monster. The health of the monster is H. Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens: - If the monster's health is 1, it drops to 0. - If the monster's health, X, is greater than 1, that monster disappears. Then, two new monsters appear, each with the health of \lfloor X/2 \rfloor. (\lfloor r \rfloor denotes the greatest integer not exceeding r.) Caracal wins when the healths of all existing monsters become 0 or below. Find the minimum number of attacks Caracal needs to make before winning. -----Constraints----- - 1 \leq H \leq 10^{12} - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: H -----Output----- Find the minimum number of attacks Caracal needs to make before winning. -----Sample Input----- 2 -----Sample Output----- 3 When Caracal attacks the initial monster, it disappears, and two monsters appear, each with the health of 1. Then, Caracal can attack each of these new monsters once and win with a total of three attacks. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese, Russian and Vietnamese as well. Eugene loves sequences, especially arithmetic progressions. One day he was asked to solve a difficult problem. If a sequence of numbers A_{1}, A_{2}, ... , A_{N} form an arithmetic progression A, he was asked to calculate sum of F(A_{i}), for L ≤ i ≤ R. F(X) is defined as: If X < 10 then F(X) = X. Else F(X) = F(sum_{of}_digits(X)). Example: F(1378) = F(1+3+7+8) = F(19) = F(1 + 9) = F(10) = F(1+0) = F(1) = 1 ------ Input ------ The first line of the input contains an integer T denoting the number of test cases. Each test case is described in one line containing four integers: A_{1} denoting the first element of the arithmetic progression A, D denoting the common difference between successive members of A, and L and R as described in the problem statement. ------ Output ------ For each test case, output a single line containing one integer denoting sum of F(A_{i}). ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ A_{1} ≤ 10^{9}$ $0 ≤ D ≤ 10^{9}$ $1 ≤ R ≤ 10^{18}$ $1 ≤ L ≤ R$ ------ Subtasks ------ $Subtask 1: 0 ≤ D ≤ 100, 1 ≤ A_{1} ≤ 10^{9}, 1 ≤ R ≤ 100 - 15 points$ $Subtask 2: 0 ≤ D ≤ 10^{9}, 1 ≤ A_{1} ≤ 10^{9}, 1 ≤ R ≤ 10^{6} - 25 points$ $Subtask 3: Original constraints - 60 points$ ----- Sample Input 1 ------ 2 1 1 1 3 14 7 2 4 ----- Sample Output 1 ------ 6 12 ----- explanation 1 ------ Example case 1. A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...} A1 = 1 A2 = 2 A3 = 3 F(A1) = 1 F(A2) = 2 F(A3) = 3 1+2+3=6 Example case 2. A = {14, 21, 28, 35, 42, 49, 56, 63, 70, 77, ...} A2 = 21 A3 = 28 A4 = 35 F(A2) = 3 F(A3) = 1 F(A4) = 8 3+1+8=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. Alice and Borys are playing tennis. A tennis match consists of games. In each game, one of the players is serving and the other one is receiving. Players serve in turns: after a game where Alice is serving follows a game where Borys is serving, and vice versa. Each game ends with a victory of one of the players. If a game is won by the serving player, it's said that this player holds serve. If a game is won by the receiving player, it's said that this player breaks serve. It is known that Alice won a games and Borys won b games during the match. It is unknown who served first and who won which games. Find all values of k such that exactly k breaks could happen during the match between Alice and Borys in total. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^3). Description of the test cases follows. Each of the next t lines describes one test case and contains two integers a and b (0 ≤ a, b ≤ 10^5; a + b > 0) — the number of games won by Alice and Borys, respectively. It is guaranteed that the sum of a + b over all test cases does not exceed 2 ⋅ 10^5. Output For each test case print two lines. In the first line, print a single integer m (1 ≤ m ≤ a + b + 1) — the number of values of k such that exactly k breaks could happen during the match. In the second line, print m distinct integers k_1, k_2, …, k_m (0 ≤ k_1 < k_2 < … < k_m ≤ a + b) — the sought values of k in increasing order. Example Input 3 2 1 1 1 0 5 Output 4 0 1 2 3 2 0 2 2 2 3 Note In the first test case, any number of breaks between 0 and 3 could happen during the match: * Alice holds serve, Borys holds serve, Alice holds serve: 0 breaks; * Borys holds serve, Alice holds serve, Alice breaks serve: 1 break; * Borys breaks serve, Alice breaks serve, Alice holds serve: 2 breaks; * Alice breaks serve, Borys breaks serve, Alice breaks serve: 3 breaks. In the second test case, the players could either both hold serves (0 breaks) or both break serves (2 breaks). In the third test case, either 2 or 3 breaks could happen: * Borys holds serve, Borys breaks serve, Borys holds serve, Borys breaks serve, Borys holds serve: 2 breaks; * Borys breaks serve, Borys holds serve, Borys breaks serve, Borys holds serve, Borys breaks serve: 3 breaks. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions: * After the cutting each ribbon piece should have length a, b or c. * After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces after the required cutting. Input The first line contains four space-separated integers n, a, b and c (1 ≤ n, a, b, c ≤ 4000) — the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide. Output Print a single number — the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists. Examples Input 5 5 3 2 Output 2 Input 7 5 5 2 Output 2 Note In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3. In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 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 $n$ bags with candies, initially the $i$-th bag contains $i$ candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: Choose $m$ such that $1 \le m \le 1000$ Perform $m$ operations. In the $j$-th operation, you will pick one bag and add $j$ candies to all bags apart from the chosen one. Your goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies. It can be proved that for the given constraints such a sequence always exists. You don't have to minimize $m$. If there are several valid sequences, you can output any. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows. The first and only line of each test case contains one integer $n$ ($2 \le n\le 100$). -----Output----- For each testcase, print two lines with your answer. In the first line print $m$ ($1\le m \le 1000$) — the number of operations you want to take. In the second line print $m$ positive integers $a_1, a_2, \dots, a_m$ ($1 \le a_i \le n$), where $a_j$ is the number of bag you chose on the $j$-th operation. -----Examples----- Input 2 2 3 Output 1 2 5 3 3 3 1 2 -----Note----- In the first case, adding $1$ candy to all bags except of the second one leads to the arrangement with $[2, 2]$ candies. In the second case, firstly you use first three operations to add $1+2+3=6$ candies in total to each bag except of the third one, which gives you $[7, 8, 3]$. Later, you add $4$ candies to second and third bag, so you have $[7, 12, 7]$, and $5$ candies to first and third bag — and the result is $[12, 12, 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. Create a function xMasTree(height) that returns a christmas tree of the correct height. The height is passed through to the function and the function should return a list containing each line of the tree. ``` xMasTree(5) should return : ['____#____', '___###___', '__#####__', '_#######_', '#########', '____#____', '____#____'] xMasTree(3) should return : ['__#__', '_###_', '#####', '__#__', '__#__'] ``` The final idea is for the tree to look like this if you decide to print each element of the list: ``` xMasTree(5) will result in: ____#____ 1 ___###___ 2 __#####__ 3 _#######_ 4 ######### -----> 5 - Height of Tree ____#____ 1 ____#____ 2 - Trunk/Stem of Tree xMasTree(3) will result in: __#__ 1 _###_ 2 ##### -----> 3 - Height of Tree __#__ 1 __#__ 2 - Trunk/Stem of Tree ``` Pad with underscores i.e _ so each line is the same length. The last line forming the tree having only hashtags, no spaces. Also remember the trunk/stem of the tree. Write your solution by modifying this code: ```python def xMasTree(n): ``` Your solution should implemented in the function "xMasTree". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?" Input The first line contains five integers n, m, c_l, c_e, v (2 ≤ n, m ≤ 10^8, 0 ≤ c_l, c_e ≤ 10^5, 1 ≤ c_l + c_e ≤ m - 1, 1 ≤ v ≤ n - 1) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≤ l_i ≤ m), denoting the positions of the stairs. If c_l = 0, the second line is empty. The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct. The fourth line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries. The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≤ x_1, x_2 ≤ n, 1 ≤ y_1, y_2 ≤ m) — the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i. Output Print q integers, one per line — the answers for the queries. Example Input 5 6 1 1 3 2 5 3 1 1 5 6 1 3 5 4 3 3 5 3 Output 7 5 4 Note In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 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. problem Chairman K is a regular customer of the JOI pizza shop in the center of JOI city. For some reason, he decided to start a life-saving life this month. So he wanted to order the pizza with the highest calories per dollar among the pizzas he could order at the JOI pizza store. Let's call such a pizza the "best pizza". The "best pizza" is not limited to one type. At JOI Pizza, you can freely choose from N types of toppings and order the ones placed on the basic dough. You cannot put more than one topping of the same type. You can also order a pizza that doesn't have any toppings on the dough. The price of the dough is $ A and the price of the toppings is $ B. The price of pizza is the sum of the price of the dough and the price of the toppings. That is, the price of a pizza with k types of toppings (0 ≤ k ≤ N) is A + k x B dollars. The total calorie of the pizza is the sum of the calories of the dough and the calories of the toppings placed. Create a program to find the number of calories per dollar for the "best pizza" given the price of the dough and the price of the toppings, and the calorie value of the dough and each topping. input The input consists of N + 3 lines. On the first line, one integer N (1 ≤ N ≤ 100) representing the number of topping types is written. On the second line, two integers A and B (1 ≤ A ≤ 1000, 1 ≤ B ≤ 1000) are written with a blank as a delimiter. A is the price of the dough and B is the price of the toppings. On the third line, one integer C (1 ≤ C ≤ 10000) representing the number of calories in the dough is written. On the 3 + i line (1 ≤ i ≤ N), one integer Di (1 ≤ Di ≤ 10000) representing the number of calories in the i-th topping is written. output Print the number of calories per dollar for the "best pizza" in one line. However, round down the numbers after the decimal point and output as an integer value. Input / output example Input example 1 3 12 2 200 50 300 100 Output example 1 37 In I / O Example 1, with the second and third toppings, 200 + 300 + 100 = 600 calories gives a pizza of $ 12 + 2 x 2 = $ 16. This pizza has 600/16 = 37.5 calories per dollar. Since this is the "best pizza", we output 37, rounded down to the nearest whole number of 37.5. Input example 2 Four 20 3 900 300 100 400 1300 Output example 2 100 The question text and the data used for the automatic referee are the question text and the test data for scoring, which are created and published by the Japan Committee for Information Olympics. Example Input 3 12 2 200 50 300 100 Output 37 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an array $a_1, a_2, \dots, a_n$ consisting of $n$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $a_i$ and $a_j$ ($i \ne j$) such that $\gcd(a_i, a_j)$ is not present in the array, and add $\gcd(a_i, a_j)$ to the end of the array. Here $\gcd(x, y)$ denotes greatest common divisor (GCD) of integers $x$ and $y$. Note that the array changes after each operation, and the subsequent operations are performed on the new array. What is the maximum number of times you can perform the operation on the array? -----Input----- The first line consists of a single integer $n$ ($2 \le n \le 10^6$). The second line consists of $n$ integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq 10^6$). All $a_i$ are distinct. -----Output----- Output a single line containing one integer — the maximum number of times the operation can be performed on the given array. -----Examples----- Input 5 4 20 1 25 30 Output 3 Input 3 6 10 15 Output 4 -----Note----- In the first example, one of the ways to perform maximum number of operations on the array is: Pick $i = 1, j= 5$ and add $\gcd(a_1, a_5) = \gcd(4, 30) = 2$ to the array. Pick $i = 2, j= 4$ and add $\gcd(a_2, a_4) = \gcd(20, 25) = 5$ to the array. Pick $i = 2, j= 5$ and add $\gcd(a_2, a_5) = \gcd(20, 30) = 10$ to the array. It can be proved that there is no way to perform more than $3$ operations on the original array. In the second example one can add $3$, then $1$, then $5$, and $2$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A: Isono, let's do that! --Sendame - story Nakajima "Isono ~, let's do that!" Isono "What is that, Nakajima" Nakajima "Look, that's that. It's hard to explain because I have to express it in letters for some reason." Isono "No, it seems that you can put in figures and photos, right?" <image> Nakajima "It's true!" Isono "So what are you going to do?" Nakajima "Look, the guy who rhythmically clapping his hands twice and then poses for defense, accumulation, and attack." Isono "Hmm, I don't know ..." Nakajima "After clapping hands twice, for example, if it was defense" <image> Nakajima "And if it was a reservoir" <image> Nakajima "If it was an attack" <image> Nakajima "Do you know who you are?" Isono "Oh! It's dramatically easier to understand when a photo is included!" Nakajima "This is the progress of civilization!" (It's been a long time since then) Hanazawa "Iso's" "I'm" "I'm" Two people "(cracking ... crackling ... crackling ...)" Hanazawa "You guys are doing that while sleeping ...!?" Hanazawa: "You've won the game right now ... Isono-kun, have you won now?" Isono "... Mr. Hanazawa was here ... Nakajima I'll do it again ... zzz" Nakajima "(Kokuri)" Two people "(cracking ... crackling ...)" Hanazawa "Already ... I'll leave that winning / losing judgment robot here ..." Then Mr. Hanazawa left. Please write that winning / losing judgment program. problem "That" is a game played by two people. According to the rhythm, the two people repeat the pose of defense, accumulation, or attack at the same time. Here, the timing at which two people pose is referred to as "times". In this game, when there is a victory or defeat in a certain time and there is no victory or defeat in the previous times, the victory or defeat is the victory or defeat of the game. Each of the two has a parameter called "attack power", and the attack power is 0 at the start of the game. When the attack pose is taken, it becomes as follows according to the attack power at that time. * If you pose for an attack when the attack power is 0, you will lose the foul. However, if the opponent also poses for an attack with an attack power of 0, he cannot win or lose at that time. * If you pose for an attack when your attack power is 1 or more, you will attack your opponent. Also, if the opponent also poses for an attack at that time, the player with the higher attack power wins. However, if both players pose for an attack with the same attack power, they cannot win or lose at that time. Also, at the end of the attack pose, your attack power becomes 0. Taking a puddle pose increases the player's attack power by 1. However, if the attack power is 5, the attack power remains at 5 even if the player poses in the pool. If the opponent attacks in the time when you take the pose of the pool, the opponent wins. In addition, if the opponent takes a pose other than the attack in the time when the pose of the pool is taken, the victory or defeat cannot be determined. If the opponent makes an attack with an attack power of 5 each time he takes a defensive pose, the opponent wins. On the other hand, if the opponent makes an attack with an attack power of 4 or less in the defense pose, or if the opponent poses for accumulation or defense, the victory or defeat cannot be achieved at that time. Even if you take a defensive pose, the attack power of that player does not change. Since the poses of both players are given in order, output the victory or defeat. Both players may continue to pose after the victory or defeat is decided, but the pose after the victory or defeat is decided is ignored. Input format The input is given in the following format. K I_1_1 ... I_K N_1_1 ... N_K The first line of input is given an integer K (1 ≤ K ≤ 100). The pose I_i (1 ≤ i ≤ K) taken by Isono is given to the K lines from the second line in order. Immediately after that, the pose N_i (1 ≤ i ≤ K) taken by Nakajima is given to the K line in order. I_i and N_i are one of “mamoru”, “tameru”, and “kougekida”. These strings, in order, represent defense, pool, and attack poses. Output format Output “Isono-kun” if Isono wins, “Nakajima-kun” if Nakajima wins, and “Hikiwake-kun” if you cannot win or lose in K times. Input example 1 3 tameru tameru tameru tameru kougekida tameru Output example 1 Nakajima-kun In the second time, Isono is in the pose of the pool, while Nakajima is attacking with an attack power of 1, so Nakajima wins. Input example 2 3 mamoru mamoru mamoru tameru tameru tameru Output example 2 Hikiwake-kun Neither attacked, so I couldn't win or lose. Input example 3 Five tameru tameru mamoru mamoru kougekida tameru tameru kougekida tameru kougekida Output example 3 Isono-kun There is no victory or defeat from the 1st to the 4th. In the 5th time, both players are posing for attack, but Isono's attack power is 2, while Nakajima's attack power is 1, so Isono wins. Input example 4 3 kougekida kougekida tameru kougekida mamoru kougekida Output example 4 Nakajima-kun In the first time, both players are posing for attack with 0 attack power, so there is no victory or defeat. In the second time, only Isono poses for an attack with an attack power of 0, so Nakajima wins. Input example 5 8 tameru mamoru tameru tameru tameru tameru tameru kougekida tameru kougekida mamoru mamoru mamoru mamoru mamoru mamoru Output example 5 Isono-kun In the second time, Nakajima poses for attack with an attack power of 1, but Isono poses for defense, so there is no victory or defeat. In the 7th time, Isono poses with an attack power of 5, so Isono's attack power remains at 5. In the 8th time, Isono poses for attack with an attack power of 5, and Nakajima poses for defense, so Isono wins. Example Input 3 tameru tameru tameru tameru kougekida tameru Output Nakajima-kun Read the inputs from stdin solve the problem and write the answer to stdout (do 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 is going to participate in the contest. It starts at $h_1:m_1$ and ends at $h_2:m_2$. It is guaranteed that the contest lasts an even number of minutes (i.e. $m_1 \% 2 = m_2 \% 2$, where $x \% y$ is $x$ modulo $y$). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes. Polycarp wants to know the time of the midpoint of the contest. For example, if the contest lasts from $10:00$ to $11:00$ then the answer is $10:30$, if the contest lasts from $11:10$ to $11:12$ then the answer is $11:11$. -----Input----- The first line of the input contains two integers $h_1$ and $m_1$ in the format hh:mm. The second line of the input contains two integers $h_2$ and $m_2$ in the same format (hh:mm). It is guaranteed that $0 \le h_1, h_2 \le 23$ and $0 \le m_1, m_2 \le 59$. It is guaranteed that the contest lasts an even number of minutes (i.e. $m_1 \% 2 = m_2 \% 2$, where $x \% y$ is $x$ modulo $y$). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes. -----Output----- Print two integers $h_3$ and $m_3$ ($0 \le h_3 \le 23, 0 \le m_3 \le 59$) corresponding to the midpoint of the contest in the format hh:mm. Print each number as exactly two digits (prepend a number with leading zero if needed), separate them with ':'. -----Examples----- Input 10:00 11:00 Output 10:30 Input 11:10 11:12 Output 11:11 Input 01:02 03:02 Output 02:02 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules: Problemset of each division should be non-empty. Each problem should be used in exactly one division (yes, it is unusual requirement). Each problem used in division 1 should be harder than any problem used in division 2. If two problems are similar, they should be used in different divisions. Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other. Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k. -----Input----- The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000) — the number of problems prepared for the round and the number of pairs of similar problems, respectively. Each of the following m lines contains a pair of similar problems u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}). It's guaranteed, that no pair of problems meets twice in the input. -----Output----- Print one integer — the number of ways to split problems in two divisions. -----Examples----- Input 5 2 1 4 5 2 Output 2 Input 3 3 1 2 2 3 1 3 Output 0 Input 3 2 3 1 3 2 Output 1 -----Note----- In the first sample, problems 1 and 2 should be used in division 2, while problems 4 and 5 in division 1. Problem 3 may be used either in division 1 or in division 2. In the second sample, all pairs of problems are similar and there is no way to split problem between two divisions without breaking any rules. Third sample reminds you that the similarity relation is not transitive. Problem 3 is similar to both 1 and 2, but 1 is not similar to 2, so they may be used together. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!' The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least p of n coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects? Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting. Input The first line contains integers n and p (3 ≤ n ≤ 3·105; 0 ≤ p ≤ n) — the number of coders in the F company and the minimum number of agreed people. Each of the next n lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the numbers of coders named by the i-th coder. It is guaranteed that xi ≠ i, yi ≠ i, xi ≠ yi. Output Print a single integer — the number of possible two-suspect sets. Note that the order of the suspects doesn't matter, that is, sets (1, 2) and (2, 1) are considered identical. Examples Input 4 2 2 3 1 4 1 4 2 1 Output 6 Input 8 6 5 6 5 7 5 8 6 2 2 1 7 3 1 3 1 4 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. Takahashi has N days of summer vacation. His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment. He cannot do multiple assignments on the same day, or hang out on a day he does an assignment. What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation? If Takahashi cannot finish all the assignments during the vacation, print -1 instead. -----Constraints----- - 1 \leq N \leq 10^6 - 1 \leq M \leq 10^4 - 1 \leq A_i \leq 10^4 -----Input----- Input is given from Standard Input in the following format: N M A_1 ... A_M -----Output----- Print the maximum number of days Takahashi can hang out during the vacation, or -1. -----Sample Input----- 41 2 5 6 -----Sample Output----- 30 For example, he can do the first assignment on the first 5 days, hang out on the next 30 days, and do the second assignment on the last 6 days of the vacation. In this way, he can safely spend 30 days hanging out. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. — This is not playing but duty as allies of justice, Nii-chan! — Not allies but justice itself, Onii-chan! With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands! There are three clusters of islands, conveniently coloured red, blue and purple. The clusters consist of a, b and c distinct islands respectively. Bridges have been built between some (possibly all or none) of the islands. A bridge bidirectionally connects two different islands and has length 1. For any two islands of the same colour, either they shouldn't be reached from each other through bridges, or the shortest distance between them is at least 3, apparently in order to prevent oddities from spreading quickly inside a cluster. The Fire Sisters are ready for the unknown, but they'd also like to test your courage. And you're here to figure out the number of different ways to build all bridges under the constraints, and give the answer modulo 998 244 353. Two ways are considered different if a pair of islands exist, such that there's a bridge between them in one of them, but not in the other. -----Input----- The first and only line of input contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 5 000) — the number of islands in the red, blue and purple clusters, respectively. -----Output----- Output one line containing an integer — the number of different ways to build bridges, modulo 998 244 353. -----Examples----- Input 1 1 1 Output 8 Input 1 2 2 Output 63 Input 1 3 5 Output 3264 Input 6 2 9 Output 813023575 -----Note----- In the first example, there are 3 bridges that can possibly be built, and no setup of bridges violates the restrictions. Thus the answer is 2^3 = 8. In the second example, the upper two structures in the figure below are instances of valid ones, while the lower two are invalid due to the blue and purple clusters, respectively. [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. Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa". Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y". There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon". Sergey is very busy and asks you to help him and write the required program. -----Input----- The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of letters in the word written by Stepan. The second line contains the string s which has length that equals to n and contains only lowercase English letters — the word written by Stepan. -----Output----- Print the single string — the word written by Stepan converted according to the rules described in the statement. -----Examples----- Input 13 pobeeeedaaaaa Output pobeda Input 22 iiiimpleeemeentatiioon Output implemeentatioon Input 18 aeiouyaaeeiioouuyy Output aeiouyaeeioouy Input 24 aaaoooiiiuuuyyyeeeggghhh Output aoiuyeggghhh Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. 500-yen Saving "500-yen Saving" is one of Japanese famous methods to save money. The method is quite simple; whenever you receive a 500-yen coin in your change of shopping, put the coin to your 500-yen saving box. Typically, you will find more than one million yen in your saving box in ten years. Some Japanese people are addicted to the 500-yen saving. They try their best to collect 500-yen coins efficiently by using 1000-yen bills and some coins effectively in their purchasing. For example, you will give 1320 yen (one 1000-yen bill, three 100-yen coins and two 10-yen coins) to pay 817 yen, to receive one 500-yen coin (and three 1-yen coins) in the change. A friend of yours is one of these 500-yen saving addicts. He is planning a sightseeing trip and wants to visit a number of souvenir shops along his way. He will visit souvenir shops one by one according to the trip plan. Every souvenir shop sells only one kind of souvenir goods, and he has the complete list of their prices. He wants to collect as many 500-yen coins as possible through buying at most one souvenir from a shop. On his departure, he will start with sufficiently many 1000-yen bills and no coins at all. The order of shops to visit cannot be changed. As far as he can collect the same number of 500-yen coins, he wants to cut his expenses as much as possible. Let's say that he is visiting shops with their souvenir prices of 800 yen, 700 yen, 1600 yen, and 600 yen, in this order. He can collect at most two 500-yen coins spending 2900 yen, the least expenses to collect two 500-yen coins, in this case. After skipping the first shop, the way of spending 700-yen at the second shop is by handing over a 1000-yen bill and receiving three 100-yen coins. In the next shop, handing over one of these 100-yen coins and two 1000-yen bills for buying a 1600-yen souvenir will make him receive one 500-yen coin. In almost the same way, he can obtain another 500-yen coin at the last shop. He can also collect two 500-yen coins buying at the first shop, but his total expenditure will be at least 3000 yen because he needs to buy both the 1600-yen and 600-yen souvenirs in this case. You are asked to make a program to help his collecting 500-yen coins during the trip. Receiving souvenirs' prices listed in the order of visiting the shops, your program is to find the maximum number of 500-yen coins that he can collect during his trip, and the minimum expenses needed for that number of 500-yen coins. For shopping, he can use an arbitrary number of 1-yen, 5-yen, 10-yen, 50-yen, and 100-yen coins he has, and arbitrarily many 1000-yen bills. The shop always returns the exact change, i.e., the difference between the amount he hands over and the price of the souvenir. The shop has sufficient stock of coins and the change is always composed of the smallest possible number of 1-yen, 5-yen, 10-yen, 50-yen, 100-yen, and 500-yen coins and 1000-yen bills. He may use more money than the price of the souvenir, even if he can put the exact money, to obtain desired coins as change; buying a souvenir of 1000 yen, he can hand over one 1000-yen bill and five 100-yen coins and receive a 500-yen coin. Note that using too many coins does no good; handing over ten 100-yen coins and a 1000-yen bill for a souvenir of 1000 yen, he will receive a 1000-yen bill as the change, not two 500-yen coins. Input The input consists of at most 50 datasets, each in the following format. > n > p1 > ... > pn > n is the number of souvenir shops, which is a positive integer not greater than 100. pi is the price of the souvenir of the i-th souvenir shop. pi is a positive integer not greater than 5000. The end of the input is indicated by a line with a single zero. Output For each dataset, print a line containing two integers c and s separated by a space. Here, c is the maximum number of 500-yen coins that he can get during his trip, and s is the minimum expenses that he need to pay to get c 500-yen coins. Sample Input 4 800 700 1600 600 4 300 700 1600 600 4 300 700 1600 650 3 1000 2000 500 3 250 250 1000 4 1251 667 876 299 0 Output for the Sample Input 2 2900 3 2500 3 3250 1 500 3 1500 3 2217 Example Input 4 800 700 1600 600 4 300 700 1600 600 4 300 700 1600 650 3 1000 2000 500 3 250 250 1000 4 1251 667 876 299 0 Output 2 2900 3 2500 3 3250 1 500 3 1500 3 2217 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom! Leha came up with a task for himself to relax a little. He chooses two integers A and B and then calculates the greatest common divisor of integers "A factorial" and "B factorial". Formally the hacker wants to find out GCD(A!, B!). It's well known that the factorial of an integer x is a product of all positive integers less than or equal to x. Thus x! = 1·2·3·...·(x - 1)·x. For example 4! = 1·2·3·4 = 24. Recall that GCD(x, y) is the largest positive integer q that divides (without a remainder) both x and y. Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you? -----Input----- The first and single line contains two integers A and B (1 ≤ A, B ≤ 10^9, min(A, B) ≤ 12). -----Output----- Print a single integer denoting the greatest common divisor of integers A! and B!. -----Example----- Input 4 3 Output 6 -----Note----- Consider the sample. 4! = 1·2·3·4 = 24. 3! = 1·2·3 = 6. The greatest common divisor of integers 24 and 6 is exactly 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. There is an infinite board of square tiles. Initially all tiles are white. Vova has a red marker and a blue marker. Red marker can color $a$ tiles. Blue marker can color $b$ tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly $a$ red tiles and exactly $b$ blue tiles across the board. Vova wants to color such a set of tiles that: they would form a rectangle, consisting of exactly $a+b$ colored tiles; all tiles of at least one color would also form a rectangle. Here are some examples of correct colorings: [Image] Here are some examples of incorrect colorings: [Image] Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain? It is guaranteed that there exists at least one correct coloring. -----Input----- A single line contains two integers $a$ and $b$ ($1 \le a, b \le 10^{14}$) — the number of tiles red marker should color and the number of tiles blue marker should color, respectively. -----Output----- Print a single integer — the minimal perimeter of a colored rectangle Vova can obtain by coloring exactly $a$ tiles red and exactly $b$ tiles blue. It is guaranteed that there exists at least one correct coloring. -----Examples----- Input 4 4 Output 12 Input 3 9 Output 14 Input 9 3 Output 14 Input 3 6 Output 12 Input 506 2708 Output 3218 -----Note----- The first four examples correspond to the first picture of the statement. Note that for there exist multiple correct colorings for all of the examples. In the first example you can also make a rectangle with sides $1$ and $8$, though its perimeter will be $18$ which is greater than $8$. In the second example you can make the same resulting rectangle with sides $3$ and $4$, but red tiles will form the rectangle with sides $1$ and $3$ and blue tiles will form the rectangle with sides $3$ and $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. CQXYM is counting permutations length of $2n$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). A permutation $p$(length of $2n$) will be counted only if the number of $i$ satisfying $p_i<p_{i+1}$ is no less than $n$. For example: Permutation $[1, 2, 3, 4]$ will count, because the number of such $i$ that $p_i<p_{i+1}$ equals $3$ ($i = 1$, $i = 2$, $i = 3$). Permutation $[3, 2, 1, 4]$ won't count, because the number of such $i$ that $p_i<p_{i+1}$ equals $1$ ($i = 3$). CQXYM wants you to help him to count the number of such permutations modulo $1000000007$ ($10^9+7$). In addition, modulo operation is to get the remainder. For example: $7 \mod 3=1$, because $7 = 3 \cdot 2 + 1$, $15 \mod 4=3$, because $15 = 4 \cdot 3 + 3$. -----Input----- The input consists of multiple test cases. The first line contains an integer $t (t \geq 1)$ — the number of test cases. The description of the test cases follows. Only one line of each test case contains an integer $n(1 \leq n \leq 10^5)$. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$ -----Output----- For each test case, print the answer in a single line. -----Examples----- Input 4 1 2 9 91234 Output 1 12 830455698 890287984 -----Note----- $n=1$, there is only one permutation that satisfies the condition: $[1,2].$ In permutation $[1,2]$, $p_1<p_2$, and there is one $i=1$ satisfy the condition. Since $1 \geq n$, this permutation should be counted. In permutation $[2,1]$, $p_1>p_2$. Because $0<n$, this permutation should not be counted. $n=2$, there are $12$ permutations: $[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[2,1,3,4],[2,3,1,4],[2,3,4,1],[2,4,1,3],[3,1,2,4],[3,4,1,2],[4,1,2,3].$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function that takes a single array as an argument (containing multiple strings and/or positive numbers and/or arrays), and returns one of four possible string values, depending on the ordering of the lengths of the elements in the input array: Your function should return... - “Increasing” - if the lengths of the elements increase from left to right (although it is possible that some neighbouring elements may also be equal in length) - “Decreasing” - if the lengths of the elements decrease from left to right (although it is possible that some neighbouring elements may also be equal in length) - “Unsorted” - if the lengths of the elements fluctuate from left to right - “Constant” - if all element's lengths are the same. Numbers and Strings should be evaluated based on the number of characters or digits used to write them. Arrays should be evaluated based on the number of elements counted directly in the parent array (but not the number of elements contained in any sub-arrays). Happy coding! :) Write your solution by modifying this code: ```python def order_type(arr): ``` Your solution should implemented in the function "order_type". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are a mayor of Berlyatov. There are $n$ districts and $m$ two-way roads between them. The $i$-th road connects districts $x_i$ and $y_i$. The cost of travelling along this road is $w_i$. There is some path between each pair of districts, so the city is connected. There are $k$ delivery routes in Berlyatov. The $i$-th route is going from the district $a_i$ to the district $b_i$. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district $a_i$ to the district $b_i$ to deliver products. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently). You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $0$). Let $d(x, y)$ be the cheapest cost of travel between districts $x$ and $y$. Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $0$. In other words, you have to find the minimum possible value of $\sum\limits_{i = 1}^{k} d(a_i, b_i)$ after applying the operation described above optimally. -----Input----- The first line of the input contains three integers $n$, $m$ and $k$ ($2 \le n \le 1000$; $n - 1 \le m \le min(1000, \frac{n(n-1)}{2})$; $1 \le k \le 1000$) — the number of districts, the number of roads and the number of courier routes. The next $m$ lines describe roads. The $i$-th road is given as three integers $x_i$, $y_i$ and $w_i$ ($1 \le x_i, y_i \le n$; $x_i \ne y_i$; $1 \le w_i \le 1000$), where $x_i$ and $y_i$ are districts the $i$-th road connects and $w_i$ is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts. The next $k$ lines describe courier routes. The $i$-th route is given as two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le n$) — the districts of the $i$-th route. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently). -----Output----- Print one integer — the minimum total courier routes cost you can achieve (i.e. the minimum value $\sum\limits_{i=1}^{k} d(a_i, b_i)$, where $d(x, y)$ is the cheapest cost of travel between districts $x$ and $y$) if you can make some (at most one) road cost zero. -----Examples----- Input 6 5 2 1 2 5 2 3 7 2 4 4 4 5 2 4 6 8 1 6 5 3 Output 22 Input 5 5 4 1 2 5 2 3 4 1 4 3 4 3 7 3 5 2 1 5 1 3 3 3 1 5 Output 13 -----Note----- The picture corresponding to the first example: [Image] There, you can choose either the road $(2, 4)$ or the road $(4, 6)$. Both options lead to the total cost $22$. The picture corresponding to the second example: $A$ There, you can choose the road $(3, 4)$. This leads to the total cost $13$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Suppose $a_1, a_2, \dots, a_n$ is a sorted integer sequence of length $n$ such that $a_1 \leq a_2 \leq \dots \leq a_n$. For every $1 \leq i \leq n$, the prefix sum $s_i$ of the first $i$ terms $a_1, a_2, \dots, a_i$ is defined by $$ s_i = \sum_{k=1}^i a_k = a_1 + a_2 + \dots + a_i. $$ Now you are given the last $k$ terms of the prefix sums, which are $s_{n-k+1}, \dots, s_{n-1}, s_{n}$. Your task is to determine whether this is possible. Formally, given $k$ integers $s_{n-k+1}, \dots, s_{n-1}, s_{n}$, the task is to check whether there is a sequence $a_1, a_2, \dots, a_n$ such that $a_1 \leq a_2 \leq \dots \leq a_n$, and $s_i = a_1 + a_2 + \dots + a_i$ for all $n-k+1 \leq i \leq n$. -----Input----- Each test contains multiple test cases. The first line contains an integer $t$ ($1 \leq t \leq 10^5$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains two integers $n$ ($1 \leq n \leq 10^5$) and $k$ ($1 \leq k \leq n$), indicating the length of the sequence $a$ and the number of terms of prefix sums, respectively. The second line of each test case contains $k$ integers $s_{n-k+1}, \dots, s_{n-1}, s_{n}$ ($-10^9 \leq s_i \leq 10^9$ for every $n-k+1 \leq i \leq n$). It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case, output "YES" (without quotes) if it is possible and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). -----Examples----- Input 4 5 5 1 2 3 4 5 7 4 -6 -5 -3 0 3 3 2 3 4 3 2 3 4 Output Yes Yes No No -----Note----- In the first test case, we have the only sequence $a = [1, 1, 1, 1, 1]$. In the second test case, we can choose, for example, $a = [-3, -2, -1, 0, 1, 2, 3]$. In the third test case, the prefix sums define the only sequence $a = [2, 1, 1]$, but it is not sorted. In the fourth test case, it can be shown that there is no sequence with the given prefix sums. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and n, inclusive. Input Input contains one integer number n (1 ≤ n ≤ 3000). Output Output the amount of almost prime numbers between 1 and n, inclusive. Examples Input 10 Output 2 Input 21 Output 8 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya had a strictly increasing sequence of positive integers a_1, ..., a_{n}. Vasya used it to build a new sequence b_1, ..., b_{n}, where b_{i} is the sum of digits of a_{i}'s decimal representation. Then sequence a_{i} got lost and all that remained is sequence b_{i}. Vasya wonders what the numbers a_{i} could be like. Of all the possible options he likes the one sequence with the minimum possible last number a_{n}. Help Vasya restore the initial sequence. It is guaranteed that such a sequence always exists. -----Input----- The first line contains a single integer number n (1 ≤ n ≤ 300). Next n lines contain integer numbers b_1, ..., b_{n}  — the required sums of digits. All b_{i} belong to the range 1 ≤ b_{i} ≤ 300. -----Output----- Print n integer numbers, one per line — the correct option for numbers a_{i}, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to b_{i}. If there are multiple sequences with least possible number a_{n}, print any of them. Print the numbers without leading zeroes. -----Examples----- Input 3 1 2 3 Output 1 2 3 Input 3 3 2 1 Output 3 11 100 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. #Permutation position In this kata you will have to permutate through a string of lowercase letters, each permutation will start at ```a``` and you must calculate how many iterations it takes to reach the current permutation. ##examples ``` input: 'a' result: 1 input: 'c' result: 3 input: 'z' result: 26 input: 'foo' result: 3759 input: 'aba' result: 27 input: 'abb' result: 28 ``` Write your solution by modifying this code: ```python def permutation_position(perm): ``` Your solution should implemented in the function "permutation_position". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. DNA is a biomolecule that carries genetic information. It is composed of four different building blocks, called nucleotides: adenine (A), thymine (T), cytosine (C) and guanine (G). Two DNA strands join to form a double helix, whereby the nucleotides of one strand bond to the nucleotides of the other strand at the corresponding positions. The bonding is only possible if the nucleotides are complementary: A always pairs with T, and C always pairs with G. Due to the asymmetry of the DNA, every DNA strand has a direction associated with it. The two strands of the double helix run in opposite directions to each other, which we refer to as the 'up-down' and the 'down-up' directions. Write a function `checkDNA` that takes in two DNA sequences as strings, and checks if they are fit to form a fully complementary DNA double helix. The function should return a Boolean `true` if they are complementary, and `false` if there is a sequence mismatch (Example 1 below). Note: - All sequences will be of non-zero length, and consisting only of `A`, `T`, `C` and `G` characters. - All sequences **will be given in the up-down direction**. - The two sequences to be compared can be of different length. If this is the case and one strand is entirely bonded by the other, and there is no sequence mismatch between the two (Example 2 below), your function should still return `true`. - If both strands are only partially bonded (Example 3 below), the function should return `false`. Example 1: Example 2: Example 3: --- #### If you enjoyed this kata, check out also my other DNA kata: [**Longest Repeated DNA Motif**](http://www.codewars.com/kata/longest-repeated-dna-motif) Write your solution by modifying this code: ```python def check_DNA(seq1, seq2): ``` Your solution should implemented in the function "check_DNA". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. My little sister came back home from school with the following task: given a squared sheet of paper she has to cut it in pieces which, when assembled, give squares the sides of which form an increasing sequence of numbers. At the beginning it was lot of fun but little by little we were tired of seeing the pile of torn paper. So we decided to write a program that could help us and protects trees. ## Task Given a positive integral number n, return a **strictly increasing** sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n². If there are multiple solutions (and there will be), return as far as possible the result with the largest possible values: ## Examples `decompose(11)` must return `[1,2,4,10]`. Note that there are actually two ways to decompose 11², 11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² but don't return `[2,6,9]`, since 9 is smaller than 10. For `decompose(50)` don't return `[1, 1, 4, 9, 49]` but `[1, 3, 5, 8, 49]` since `[1, 1, 4, 9, 49]` doesn't form a strictly increasing sequence. ## Note Neither `[n]` nor `[1,1,1,…,1]` are valid solutions. If no valid solution exists, return `nil`, `null`, `Nothing`, `None` (depending on the language) or `"[]"` (C) ,`{}` (C++), `[]` (Swift, Go). The function "decompose" will take a positive integer n and return the decomposition of N = n² as: - [x1 ... xk] or - "x1 ... xk" or - Just [x1 ... xk] or - Some [x1 ... xk] or - {x1 ... xk} or - "[x1,x2, ... ,xk]" depending on the language (see "Sample tests") # Note for Bash ``` decompose 50 returns "1,3,5,8,49" decompose 4 returns "Nothing" ``` # Hint Very often `xk` will be `n-1`. Write your solution by modifying this code: ```python def decompose(n): ``` Your solution should implemented in the function "decompose". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b. <image> 10 pebbles are arranged in two rows, each row has 5 pebbles Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble. The game process can be represented as a finite sequence of integers c1, ..., ck, where: * c1 = n * ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1. * ck = 1 The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game. Input The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has. The input limitations for getting 30 points are: * 2 ≤ n ≤ 50 The input limitations for getting 100 points are: * 2 ≤ n ≤ 109 Output Print a single number — the maximum possible result of the game. Examples Input 10 Output 16 Input 8 Output 15 Note Consider the first example (c1 = 10). The possible options for the game development are: * Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11. * Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13. * Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain? -----Input----- The first line contains two integers, n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains m integers — the elements of matrix a. The i-th line contains integers a_{i}1, a_{i}2, ..., a_{im} (0 ≤ a_{ij} ≤ 1) — the i-th row of the matrix a. -----Output----- In the single line, print the answer to the problem — the minimum number of rows of matrix b. -----Examples----- Input 4 3 0 0 1 1 1 0 1 1 0 0 0 1 Output 2 Input 3 3 0 0 0 0 0 0 0 0 0 Output 3 Input 8 1 0 1 1 0 0 1 1 0 Output 2 -----Note----- In the first test sample the answer is a 2 × 3 matrix b: 001 110 If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input: 001 110 110 001 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself). Input The first line of the input contains two integers n and m (1 ≤ n ≤ 15, 0 ≤ m ≤ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10000), x, y are edge endpoints, and w is the edge length. Output Output minimal cycle length or -1 if it doesn't exists. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 3 Input 3 2 1 2 3 2 3 4 Output 14 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem: You've got some training set of documents. For each document you know its subject. The subject in this problem is an integer from 1 to 3. Each of these numbers has a physical meaning. For instance, all documents with subject 3 are about trade. You can download the training set of documents at the following link: http://download4.abbyy.com/a2/X2RZ2ZWXBG5VYWAL61H76ZQM/train.zip. The archive contains three directories with names "1", "2", "3". Directory named "1" contains documents on the 1-st subject, directory "2" contains documents on the 2-nd subject, and directory "3" contains documents on the 3-rd subject. Each document corresponds to exactly one file from some directory. All documents have the following format: the first line contains the document identifier, the second line contains the name of the document, all subsequent lines contain the text of the document. The document identifier is used to make installing the problem more convenient and has no useful information for the participants. You need to write a program that should indicate the subject for a given document. It is guaranteed that all documents given as input to your program correspond to one of the three subjects of the training set. Input The first line contains integer id (0 ≤ id ≤ 106) — the document identifier. The second line contains the name of the document. The third and the subsequent lines contain the text of the document. It is guaranteed that the size of any given document will not exceed 10 kilobytes. The tests for this problem are divided into 10 groups. Documents of groups 1 and 2 are taken from the training set, but their identifiers will not match the identifiers specified in the training set. Groups from the 3-rd to the 10-th are roughly sorted by the author in ascending order of difficulty (these groups contain documents which aren't present in the training set). Output Print an integer from 1 to 3, inclusive — the number of the subject the given document corresponds to. Examples Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write function describeList which returns "empty" if the list is empty or "singleton" if it contains only one element or "longer"" if more. Write your solution by modifying this code: ```python def describeList(list): ``` Your solution should implemented in the function "describeList". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given a string of words and numbers. Extract the expression including: 1. the operator: either addition or subtraction 2. the two numbers that we are operating on Return the result of the calculation. Example: "Panda has 48 apples and loses 4" returns 44 "Jerry has 34 apples and gains 6" returns 40 "loses" and "gains" are the only two words describing operators. Should be a nice little kata for you :) Note: No fruit debts nor bitten apples = The numbers are integers and no negatives Write your solution by modifying this code: ```python def calculate(string): ``` Your solution should implemented in the function "calculate". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters. The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let's assume that the point $x = 0$ is where these parts meet. The right part of the corridor is filled with $n$ monsters — for each monster, its initial coordinate $x_i$ is given (and since all monsters are in the right part, every $x_i$ is positive). The left part of the corridor is filled with crusher traps. If some monster enters the left part of the corridor or the origin (so, its current coordinate becomes less than or equal to $0$), it gets instantly killed by a trap. The main weapon Ivan uses to kill the monsters is the Phoenix Rod. It can launch a missile that explodes upon impact, obliterating every monster caught in the explosion and throwing all other monsters away from the epicenter. Formally, suppose that Ivan launches a missile so that it explodes in the point $c$. Then every monster is either killed by explosion or pushed away. Let some monster's current coordinate be $y$, then: if $c = y$, then the monster is killed; if $y < c$, then the monster is pushed $r$ units to the left, so its current coordinate becomes $y - r$; if $y > c$, then the monster is pushed $r$ units to the right, so its current coordinate becomes $y + r$. Ivan is going to kill the monsters as follows: choose some integer point $d$ and launch a missile into that point, then wait until it explodes and all the monsters which are pushed to the left part of the corridor are killed by crusher traps, then, if at least one monster is still alive, choose another integer point (probably the one that was already used) and launch a missile there, and so on. What is the minimum number of missiles Ivan has to launch in order to kill all of the monsters? You may assume that every time Ivan fires the Phoenix Rod, he chooses the impact point optimally. You have to answer $q$ independent queries. -----Input----- The first line contains one integer $q$ ($1 \le q \le 10^5$) — the number of queries. The first line of each query contains two integers $n$ and $r$ ($1 \le n, r \le 10^5$) — the number of enemies and the distance that the enemies are thrown away from the epicenter of the explosion. The second line of each query contains $n$ integers $x_i$ ($1 \le x_i \le 10^5$) — the initial positions of the monsters. It is guaranteed that sum of all $n$ over all queries does not exceed $10^5$. -----Output----- For each query print one integer — the minimum number of shots from the Phoenix Rod required to kill all monsters. -----Example----- Input 2 3 2 1 3 5 4 1 5 2 3 5 Output 2 2 -----Note----- In the first test case, Ivan acts as follows: choose the point $3$, the first monster dies from a crusher trap at the point $-1$, the second monster dies from the explosion, the third monster is pushed to the point $7$; choose the point $7$, the third monster dies from the explosion. In the second test case, Ivan acts as follows: choose the point $5$, the first and fourth monsters die from the explosion, the second monster is pushed to the point $1$, the third monster is pushed to the point $2$; choose the point $2$, the first monster dies from a crusher trap at the point $0$, the second monster dies from the explosion. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 integer sequence A of length N whose values are unknown. Given is an integer sequence B of length N-1 which is known to satisfy the following: B_i \geq \max(A_i, A_{i+1}) Find the maximum possible sum of the elements of A. -----Constraints----- - All values in input are integers. - 2 \leq N \leq 100 - 0 \leq B_i \leq 10^5 -----Input----- Input is given from Standard Input in the following format: N B_1 B_2 ... B_{N-1} -----Output----- Print the maximum possible sum of the elements of A. -----Sample Input----- 3 2 5 -----Sample Output----- 9 A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. At the big break Nastya came to the school dining room. There are $n$ pupils in the school, numbered from $1$ to $n$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils. Formally, there are some pairs $u$, $v$ such that if the pupil with number $u$ stands directly in front of the pupil with number $v$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward. -----Input----- The first line contains two integers $n$ and $m$ ($1 \leq n \leq 3 \cdot 10^{5}$, $0 \leq m \leq 5 \cdot 10^{5}$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $n$ integers $p_1$, $p_2$, ..., $p_n$ — the initial arrangement of pupils in the queue, from the queue start to its end ($1 \leq p_i \leq n$, $p$ is a permutation of integers from $1$ to $n$). In other words, $p_i$ is the number of the pupil who stands on the $i$-th position in the queue. The $i$-th of the following $m$ lines contains two integers $u_i$, $v_i$ ($1 \leq u_i, v_i \leq n, u_i \neq v_i$), denoting that the pupil with number $u_i$ agrees to change places with the pupil with number $v_i$ if $u_i$ is directly in front of $v_i$. It is guaranteed that if $i \neq j$, than $v_i \neq v_j$ or $u_i \neq u_j$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $p_n$. -----Output----- Print a single integer — the number of places in queue she can move forward. -----Examples----- Input 2 1 1 2 1 2 Output 1 Input 3 3 3 1 2 1 2 3 1 3 2 Output 2 Input 5 2 3 1 5 4 2 5 2 5 4 Output 1 -----Note----- In the first example Nastya can just change places with the first pupil in the queue. Optimal sequence of changes in the second example is change places for pupils with numbers $1$ and $3$. change places for pupils with numbers $3$ and $2$. change places for pupils with numbers $1$ and $2$. The queue looks like $[3, 1, 2]$, then $[1, 3, 2]$, then $[1, 2, 3]$, and finally $[2, 1, 3]$ after these 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. Takahashi participated in a contest on AtCoder. The contest had N problems. Takahashi made M submissions during the contest. The i-th submission was made for the p_i-th problem and received the verdict S_i (AC or WA). The number of Takahashi's correct answers is the number of problems on which he received an AC once or more. The number of Takahashi's penalties is the sum of the following count for the problems on which he received an AC once or more: the number of WAs received before receiving an AC for the first time on that problem. Find the numbers of Takahashi's correct answers and penalties. -----Constraints----- - N, M, and p_i are integers. - 1 \leq N \leq 10^5 - 0 \leq M \leq 10^5 - 1 \leq p_i \leq N - S_i is AC or WA. -----Input----- Input is given from Standard Input in the following format: N M p_1 S_1 : p_M S_M -----Output----- Print the number of Takahashi's correct answers and the number of Takahashi's penalties. -----Sample Input----- 2 5 1 WA 1 AC 2 WA 2 AC 2 WA -----Sample Output----- 2 2 In his second submission, he received an AC on the first problem for the first time. Before this, he received one WA on this problem. In his fourth submission, he received an AC on the second problem for the first time. Before this, he received one WA on this problem. Thus, he has two correct answers and two penalties. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 series or sequence of numbers is usually the product of a function and can either be infinite or finite. In this kata we will only consider finite series and you are required to return a code according to the type of sequence: |Code|Type|Example| |-|-|-| |`0`|`unordered`|`[3,5,8,1,14,3]`| |`1`|`strictly increasing`|`[3,5,8,9,14,23]`| |`2`|`not decreasing`|`[3,5,8,8,14,14]`| |`3`|`strictly decreasing`|`[14,9,8,5,3,1]`| |`4`|`not increasing`|`[14,14,8,8,5,3]`| |`5`|`constant`|`[8,8,8,8,8,8]`| You can expect all the inputs to be non-empty and completely numerical arrays/lists - no need to validate the data; do not go for sloppy code, as rather large inputs might be tested. Try to achieve a good solution that runs in linear time; also, do it functionally, meaning you need to build a *pure* function or, in even poorer words, do NOT modify the initial input! Write your solution by modifying this code: ```python def sequence_classifier(arr): ``` Your solution should implemented in the function "sequence_classifier". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let S(n) denote the sum of the digits in the decimal notation of n. For example, S(101) = 1 + 0 + 1 = 2. Given an integer N, determine if S(N) divides N. -----Constraints----- - 1 \leq N \leq 10^9 -----Input----- Input is given from Standard Input in the following format: N -----Output----- If S(N) divides N, print Yes; if it does not, print No. -----Sample Input----- 12 -----Sample Output----- Yes In this input, N=12. As S(12) = 1 + 2 = 3, S(N) divides N. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market. She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and also she gave a half of an apple to some of them as a gift (if the number of apples at the moment of purchase was odd), until she sold all the apples she had. So each buyer took some integral positive number of apples, but maybe he didn't pay for a half of an apple (if the number of apples at the moment of the purchase was odd). For each buyer grandma remembers if she gave a half of an apple as a gift or not. The cost of an apple is p (the number p is even). Print the total money grandma should have at the end of the day to check if some buyers cheated her. -----Input----- The first line contains two integers n and p (1 ≤ n ≤ 40, 2 ≤ p ≤ 1000) — the number of the buyers and the cost of one apple. It is guaranteed that the number p is even. The next n lines contains the description of buyers. Each buyer is described with the string half if he simply bought half of the apples and with the string halfplus if grandma also gave him a half of an apple as a gift. It is guaranteed that grandma has at least one apple at the start of the day and she has no apples at the end of the day. -----Output----- Print the only integer a — the total money grandma should have at the end of the day. Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type. -----Examples----- Input 2 10 half halfplus Output 15 Input 3 10 halfplus halfplus halfplus Output 55 -----Note----- In the first sample at the start of the day the grandma had two apples. First she sold one apple and then she sold a half of the second apple and gave a half of the second apple as a present to the second buyer. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 say you are standing on the $XY$-plane at point $(0, 0)$ and you want to reach point $(n, n)$. You can move only in two directions: to the right, i. e. horizontally and in the direction that increase your $x$ coordinate, or up, i. e. vertically and in the direction that increase your $y$ coordinate. In other words, your path will have the following structure: initially, you choose to go to the right or up; then you go some positive integer distance in the chosen direction (distances can be chosen independently); after that you change your direction (from right to up, or from up to right) and repeat the process. You don't like to change your direction too much, so you will make no more than $n - 1$ direction changes. As a result, your path will be a polygonal chain from $(0, 0)$ to $(n, n)$, consisting of at most $n$ line segments where each segment has positive integer length and vertical and horizontal segments alternate. Not all paths are equal. You have $n$ integers $c_1, c_2, \dots, c_n$ where $c_i$ is the cost of the $i$-th segment. Using these costs we can define the cost of the path as the sum of lengths of the segments of this path multiplied by their cost, i. e. if the path consists of $k$ segments ($k \le n$), then the cost of the path is equal to $\sum\limits_{i=1}^{k}{c_i \cdot length_i}$ (segments are numbered from $1$ to $k$ in the order they are in the path). Find the path of the minimum cost and print its cost. -----Input----- The first line contains the single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The first line of each test case contains the single integer $n$ ($2 \le n \le 10^5$). The second line of each test case contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le 10^9$) — the costs of each segment. It's guaranteed that the total sum of $n$ doesn't exceed $10^5$. -----Output----- For each test case, print the minimum possible cost of the path from $(0, 0)$ to $(n, n)$ consisting of at most $n$ alternating segments. -----Examples----- Input 3 2 13 88 3 2 3 1 5 4 3 2 1 4 Output 202 13 19 -----Note----- In the first test case, to reach $(2, 2)$ you need to make at least one turn, so your path will consist of exactly $2$ segments: one horizontal of length $2$ and one vertical of length $2$. The cost of the path will be equal to $2 \cdot c_1 + 2 \cdot c_2 = 26 + 176 = 202$. In the second test case, one of the optimal paths consists of $3$ segments: the first segment of length $1$, the second segment of length $3$ and the third segment of length $2$. The cost of the path is $1 \cdot 2 + 3 \cdot 3 + 2 \cdot 1 = 13$. In the third test case, one of the optimal paths consists of $4$ segments: the first segment of length $1$, the second one — $1$, the third one — $4$, the fourth one — $4$. The cost of the path is $1 \cdot 4 + 1 \cdot 3 + 4 \cdot 2 + 4 \cdot 1 = 19$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mr. F has n positive integers, a_1, a_2, …, a_n. He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers. But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward. Your task is to calculate the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers. Input The first line contains an integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of integers Mr. F has. The second line contains n integers, a_1, a_2, …, a_n (1 ≤ a_i ≤ 1.5 ⋅ 10^7). Output Print an integer — the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers. You should not remove all of the integers. If there is no solution, print «-1» (without quotes). Examples Input 3 1 2 4 Output 1 Input 4 6 9 15 30 Output 2 Input 3 1 1 1 Output -1 Note In the first example, the greatest common divisor is 1 in the beginning. You can remove 1 so that the greatest common divisor is enlarged to 2. The answer is 1. In the second example, the greatest common divisor is 3 in the beginning. You can remove 6 and 9 so that the greatest common divisor is enlarged to 15. There is no solution which removes only one integer. So the answer is 2. In the third example, there is no solution to enlarge the greatest common divisor. 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've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers — the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number — the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 × 1 × 1, in the second one — 2 × 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. Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent. Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers x_1, x_2, …, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question. At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions. Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all. You are given n and Bob's questions x_1, …, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions. Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i ≠ a_j or b_i ≠ b_j. Input The first line contains two integers n and k (1 ≤ n,k ≤ 10^5) — the number of cells and the number of questions Bob asked. The second line contains k integers x_1, x_2, …, x_k (1 ≤ x_i ≤ n) — Bob's questions. Output Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions. Examples Input 5 3 5 1 4 Output 9 Input 4 8 1 2 3 4 4 3 2 1 Output 0 Input 100000 1 42 Output 299997 Note The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j. In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question. (4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once. In the second example, Alice has no valid scenarios. In the last example, all (i,j) where |i-j| ≤ 1 except for (42, 42) are valid scenarios. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. She loves e-mail so much! She sends e-mails by her cellular phone to her friends when she has breakfast, she talks with other friends, and even when she works in the library! Her cellular phone has somewhat simple layout (Figure 1). Pushing button 1 once displays a character (’), pushing <image> it twice in series displays a character (,), and so on, and pushing it 6 times displays (’) again. Button 2 corresponds to charaters (abcABC), and, for example, pushing it four times displays (A). Button 3-9 have is similar to button 1. Button 0 is a special button: pushing it once make her possible to input characters in the same button in series. For example, she has to push “20202” to display “aaa” and “660666” to display “no”. In addition, pushing button 0 n times in series (n > 1) displays n − 1 spaces. She never pushes button 0 at the very beginning of her input. Here are some examples of her input and output: 666660666 --> No 44444416003334446633111 --> I’m fine. 20202202000333003330333 --> aaba f ff One day, the chief librarian of the library got very angry with her and hacked her cellular phone when she went to the second floor of the library to return books in shelves. Now her cellular phone can only display button numbers she pushes. Your task is to write a program to convert the sequence of button numbers into correct characters and help her continue her e-mails! Input Input consists of several lines. Each line contains the sequence of button numbers without any spaces. You may assume one line contains no more than 10000 numbers. Input terminates with EOF. Output For each line of input, output the corresponding sequence of characters in one line. Example Input 666660666 44444416003334446633111 20202202000333003330333 Output No I'm fine. aaba f ff Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Character recognition software is widely used to digitise printed texts. Thus the texts can be edited, searched and stored on a computer. When documents (especially pretty old ones written with a typewriter), are digitised character recognition softwares often make mistakes. Your task is correct the errors in the digitised text. You only have to handle the following mistakes: * `S` is misinterpreted as `5` * `O` is misinterpreted as `0` * `I` is misinterpreted as `1` The test cases contain numbers only by mistake. Write your solution by modifying this code: ```python def correct(string): ``` Your solution should implemented in the function "correct". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Your job is to write a function which increments a string, to create a new string. - If the string already ends with a number, the number should be incremented by 1. - If the string does not end with a number. the number 1 should be appended to the new string. Examples: `foo -> foo1` `foobar23 -> foobar24` `foo0042 -> foo0043` `foo9 -> foo10` `foo099 -> foo100` *Attention: If the number has leading zeros the amount of digits should be considered.* Write your solution by modifying this code: ```python def increment_string(strng): ``` Your solution should implemented in the function "increment_string". The i Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Alice and Bob begin their day with a quick game. They first choose a starting number X_0 ≥ 3 and try to reach one million by the process described below. Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number. Formally, he or she selects a prime p < X_{i} - 1 and then finds the minimum X_{i} ≥ X_{i} - 1 such that p divides X_{i}. Note that if the selected prime p already divides X_{i} - 1, then the number does not change. Eve has witnessed the state of the game after two turns. Given X_2, help her determine what is the smallest possible starting number X_0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions. -----Input----- The input contains a single integer X_2 (4 ≤ X_2 ≤ 10^6). It is guaranteed that the integer X_2 is composite, that is, is not prime. -----Output----- Output a single integer — the minimum possible X_0. -----Examples----- Input 14 Output 6 Input 20 Output 15 Input 8192 Output 8191 -----Note----- In the first test, the smallest possible starting number is X_0 = 6. One possible course of the game is as follows: Alice picks prime 5 and announces X_1 = 10 Bob picks prime 7 and announces X_2 = 14. In the second case, let X_0 = 15. Alice picks prime 2 and announces X_1 = 16 Bob picks prime 5 and announces X_2 = 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. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task. Input The single line contains four integers a1, a2, a3 and a4 (1 ≤ a1, a2, a3, a4 ≤ 106). Output On the single line print without leading zeroes the answer to the problem — the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes). Examples Input 2 2 1 1 Output 4774 Input 4 7 3 1 Output -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" — thought Petya. He know for a fact that if he fulfills the parents' task in the i-th (1 ≤ i ≤ 12) month of the year, then the flower will grow by ai centimeters, and if he doesn't water the flower in the i-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by k centimeters. Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by k centimeters. Input The first line contains exactly one integer k (0 ≤ k ≤ 100). The next line contains twelve space-separated integers: the i-th (1 ≤ i ≤ 12) number in the line represents ai (0 ≤ ai ≤ 100). Output Print the only integer — the minimum number of months when Petya has to water the flower so that the flower grows no less than by k centimeters. If the flower can't grow by k centimeters in a year, print -1. Examples Input 5 1 1 1 1 2 2 3 2 2 1 1 1 Output 2 Input 0 0 0 0 0 0 0 0 1 1 2 3 0 Output 0 Input 11 1 1 4 1 1 5 1 1 4 1 1 1 Output 3 Note Let's consider the first sample test. There it is enough to water the flower during the seventh and the ninth month. Then the flower grows by exactly five centimeters. In the second sample Petya's parents will believe him even if the flower doesn't grow at all (k = 0). So, it is possible for Petya not to water the flower at all. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal! He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities. All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city. Help Shapur find how much He should travel. Input First line contains a single natural number n (1 ≤ n ≤ 105) — the amount of cities. Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 ≤ xi, yi ≤ n, 0 ≤ wi ≤ 2 × 104). xi and yi are two ends of a road and wi is the length of that road. Output A single integer number, the minimal length of Shapur's travel. 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 3 1 2 3 2 3 4 Output 7 Input 3 1 2 3 1 3 3 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. A cricket team consists of 11 players and some are good at batting, others are good at bowling and some of them are good at both batting and bowling. The batting coach wants to select exactly K players having maximum possible sum of scores. Given the batting score of each of the 11 players, find the number of ways in which we can select exactly K players such that the sum of their scores is the maximum possible. Two ways are different if there is a player who is selected in one of them is not in the other. See explanation of sample cases for more clarity. ------ Input ------ First line contains T, number of test cases ( 1 ≤ T ≤ 100 ). T cases follow, each having 2 lines. First line of each case contains scores of 11 players ( 1 ≤ score ≤ 100 ) and the second line contains K (1 ≤ K ≤ 11) ------ Output ------ For each test case, output the answer in a new line. ----- Sample Input 1 ------ 2 1 2 3 4 5 6 7 8 9 10 11 3 2 5 1 2 4 1 6 5 2 2 1 6 ----- Sample Output 1 ------ 1 6 ----- explanation 1 ------ Case 1 : Maximum possible sum of scores = 11 + 10 + 9 = 30 and can be achieved only by selecting the last 3 players. Only one possible way. Case 2 : Maximum possible sum of scores = 6 + 5 + 5 + 4 + 2 + 2 = 24 and considering the players as p1 p2 p3 ... p11 in that order, the ones with maximum possible sum of scores is as follows {p1, p2, p4, p5, p7, p8 } {p10, p2, p4, p5, p7, p8 } {p1, p2, p10, p5, p7, p8 } {p9, p2, p4, p5, p7, p8 } {p1, p2, p9, p5, p7, p8 } {p10, p2, p9, p5, p7, p8 } Read the inputs from stdin solve the problem and write the answer to stdout (do 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 are playing a game on a line with $n$ cells. There are $n$ cells labeled from $1$ through $n$. For each $i$ from $1$ to $n-1$, cells $i$ and $i+1$ are adjacent. Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers $x_1, x_2, \ldots, x_k$ in order. In the $i$-th question, Bob asks Alice if her token is currently on cell $x_i$. That is, Alice can answer either "YES" or "NO" to each Bob's question. At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions. Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all. You are given $n$ and Bob's questions $x_1, \ldots, x_k$. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions. Let $(a,b)$ denote a scenario where Alice starts at cell $a$ and ends at cell $b$. Two scenarios $(a_i, b_i)$ and $(a_j, b_j)$ are different if $a_i \neq a_j$ or $b_i \neq b_j$. -----Input----- The first line contains two integers $n$ and $k$ ($1 \leq n,k \leq 10^5$) — the number of cells and the number of questions Bob asked. The second line contains $k$ integers $x_1, x_2, \ldots, x_k$ ($1 \leq x_i \leq n$) — Bob's questions. -----Output----- Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions. -----Examples----- Input 5 3 5 1 4 Output 9 Input 4 8 1 2 3 4 4 3 2 1 Output 0 Input 100000 1 42 Output 299997 -----Note----- The notation $(i,j)$ denotes a scenario where Alice starts at cell $i$ and ends at cell $j$. In the first example, the valid scenarios are $(1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5)$. For example, $(3,4)$ is valid since Alice can start at cell $3$, stay there for the first three questions, then move to cell $4$ after the last question. $(4,5)$ is valid since Alice can start at cell $4$, stay there for the first question, the move to cell $5$ for the next two questions. Note that $(4,5)$ is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once. In the second example, Alice has no valid scenarios. In the last example, all $(i,j)$ where $|i-j| \leq 1$ except for $(42, 42)$ are valid scenarios. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 ножек. Каждая ножка состоит из двух частей, которые соединяются друг с другом. Каждая часть может быть произвольной положительной длины, но гарантируется, что из всех 2n частей возможно составить n ножек одинаковой длины. При составлении ножки любые две части могут быть соединены друг с другом. Изначально все ножки стола разобраны, а вам заданы длины 2n частей в произвольном порядке. Помогите Васе собрать все ножки стола так, чтобы все они были одинаковой длины, разбив заданные 2n части на пары правильным образом. Каждая ножка обязательно должна быть составлена ровно из двух частей, не разрешается использовать как ножку только одну часть. -----Входные данные----- В первой строке задано число n (1 ≤ n ≤ 1000) — количество ножек у стола, купленного Васей. Во второй строке следует последовательность из 2n целых положительных чисел a_1, a_2, ..., a_2n (1 ≤ a_{i} ≤ 100 000) — длины частей ножек стола в произвольном порядке. -----Выходные данные----- Выведите n строк по два целых числа в каждой — длины частей ножек, которые надо соединить друг с другом. Гарантируется, что всегда возможно собрать n ножек одинаковой длины. Если ответов несколько, разрешается вывести любой из них. -----Примеры----- Входные данные 3 1 3 2 4 5 3 Выходные данные 1 5 2 4 3 3 Входные данные 3 1 1 1 2 2 2 Выходные данные 1 2 2 1 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. Soroush and Keshi each have a labeled and rooted tree on n vertices. Both of their trees are rooted from vertex 1. Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph on n vertices. They add an edge between vertices u and v in the memorial graph if both of the following conditions hold: * One of u or v is the ancestor of the other in Soroush's tree. * Neither of u or v is the ancestor of the other in Keshi's tree. Here vertex u is considered ancestor of vertex v, if u lies on the path from 1 (the root) to the v. Popping out of nowhere, Mashtali tried to find the maximum clique in the memorial graph for no reason. He failed because the graph was too big. Help Mashtali by finding the size of the maximum clique in the memorial graph. As a reminder, clique is a subset of vertices of the graph, each two of which are connected by an edge. Input The first line contains an integer t (1≤ t≤ 3 ⋅ 10^5) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (2≤ n≤ 3 ⋅ 10^5). The second line of each test case contains n-1 integers a_2, …, a_n (1 ≤ a_i < i), a_i being the parent of the vertex i in Soroush's tree. The third line of each test case contains n-1 integers b_2, …, b_n (1 ≤ b_i < i), b_i being the parent of the vertex i in Keshi's tree. It is guaranteed that the given graphs are trees. It is guaranteed that the sum of n over all test cases doesn't exceed 3 ⋅ 10^5. Output For each test case print a single integer — the size of the maximum clique in the memorial graph. Example Input 4 4 1 2 3 1 2 3 5 1 2 3 4 1 1 1 1 6 1 1 1 1 2 1 2 1 2 2 7 1 1 3 4 4 5 1 2 1 4 2 5 Output 1 4 1 3 Note In the first and third test cases, you can pick any vertex. In the second test case, one of the maximum cliques is \{2, 3, 4, 5\}. In the fourth test case, one of the maximum cliques is \{3, 4, 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. People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects. Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied: every integer from 1 to n^2 appears in the table exactly once; in each row numbers are situated in increasing order; the sum of numbers in the k-th column is maximum possible. Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right. -----Input----- The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum. -----Output----- First print the sum of the integers in the k-th column of the required table. Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on. If there are multiple suitable table, you are allowed to print any. -----Examples----- Input 4 1 Output 28 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Input 5 3 Output 85 5 6 17 18 19 9 10 23 24 25 7 8 20 21 22 3 4 14 15 16 1 2 11 12 13 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not. You are given an integer $n$. Your goal is to construct and print exactly $n$ different regular bracket sequences of length $2n$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 50$) — the number of test cases. Each test case consists of one line containing one integer $n$ ($1 \le n \le 50$). -----Output----- For each test case, print $n$ lines, each containing a regular bracket sequence of length exactly $2n$. All bracket sequences you output for a testcase should be different (though they may repeat in different test cases). If there are multiple answers, print any of them. It can be shown that it's always possible. -----Examples----- Input 3 3 1 3 Output ()()() ((())) (()()) () ((())) (())() ()(()) -----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.