question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter. -----Constraints----- - 2\leq K\leq 100 - K is an integer. -----Input----- Input is given from Standard Input in the following format: K -----Output----- Print the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). -----Sample Input----- 3 -----Sample Output----- 2 Two pairs can be chosen: (2,1) and (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. There is a robot on a checkered field that is endless in all directions. Initially, the robot is located in the cell with coordinates (0, 0). He will execute commands which are described by a string of capital Latin letters 'L', 'R', 'D', 'U'. When a command is executed, the robot simply moves in the corresponding direction: * 'L': one cell to the left (the x-coordinate of the current cell decreases by 1); * 'R': one cell to the right (the x-coordinate of the current cell is increased by 1); * 'D': one cell down (the y-coordinate of the current cell decreases by 1); * 'U': one cell up (the y-coordinate of the current cell is increased by 1). Your task is to put an obstacle in one cell of the field so that after executing the commands, the robot will return to the original cell of its path (0, 0). Of course, an obstacle cannot be placed in the starting cell (0, 0). It is guaranteed that if the obstacle is not placed, then the robot will not return to the starting cell. An obstacle affects the movement of the robot in the following way: if it tries to go in a certain direction, and there is an obstacle, then it simply remains in place (the obstacle also remains, that is, it does not disappear). Find any such cell of the field (other than (0, 0)) that if you put an obstacle there, the robot will return to the cell (0, 0) after the execution of all commands. If there is no solution, then report it. Input The first line contains one integer t (1 ≤ t ≤ 500) — the number of test cases. Each test case consists of a single line containing s — the sequence of commands, which are uppercase Latin letters 'L', 'R', 'D', 'U' only. The length of s is between 1 and 5000, inclusive. Additional constraint on s: executing this sequence of commands leads the robot to some cell other than (0, 0), if there are no obstacles. The sum of lengths of all s in a test doesn't exceed 5000. Output For each test case print a single line: * if there is a solution, print two integers x and y (-10^9 ≤ x,y ≤ 10^9) such that an obstacle in (x, y) will force the robot to return back to the cell (0, 0); * otherwise, print two zeroes (i. e. 0 0). If there are multiple answers, you can print any of them. Example Input 4 L RUUDL LLUU DDDUUUUU Output -1 0 1 2 0 0 0 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos. The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. Input The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105). Output Output a single integer — the optimal number of visible kangaroos. Examples Input 8 2 5 7 6 9 8 4 2 Output 5 Input 8 9 1 6 2 6 5 8 3 Output 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. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1. Output Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 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. Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k. -----Input----- The only line contains two integers n and k (1 ≤ n, k ≤ 10^9). -----Output----- Print the smallest integer x > n, so it is divisible by the number k. -----Examples----- Input 5 3 Output 6 Input 25 13 Output 26 Input 26 13 Output 39 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Takahashi is not good at problems about trees in programming contests, and Aoki is helping him practice. First, Takahashi created a tree with N vertices numbered 1 through N, and wrote 0 at each edge. Then, Aoki gave him M queries. The i-th of them is as follows: * Increment the number written at each edge along the path connecting vertices a_i and b_i, by one. After Takahashi executed all of the queries, he told Aoki that, for every edge, the written number became an even number. However, Aoki forgot to confirm that the graph Takahashi created was actually a tree, and it is possible that Takahashi made a mistake in creating a tree or executing queries. Determine whether there exists a tree that has the property mentioned by Takahashi. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ M ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_M b_M Output Print `YES` if there exists a tree that has the property mentioned by Takahashi; print `NO` otherwise. Examples Input 4 4 1 2 2 4 1 3 3 4 Output YES Input 5 5 1 2 3 5 5 1 3 4 2 3 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. () Problem Statement There is a string S. Initially, S is an empty string. Perform the following processing in order of n. * Add x_i p_i (=" (" or") ") to the end of S. After processing, determine if S is a well-balanced string. "The string is balanced" is defined as follows. * The empty string is well-balanced. * For balanced strings a and b, a + b (+ represents a concatenation of strings) is balanced. * For a balanced string a, "(" + a + ")" is balanced. Constraints * 1 ≤ n ≤ 1,000 * 1 ≤ x_i ≤ 10 ^ 6 * p_i is "(" or ")" Input Input follows the following format. All given numbers are integers. n p_1 x_1 .. .. p_n x_n Output Output "YES" if balanced, otherwise output "NO" on one line. Examples Input 3 ( 5 ) 4 ) 1 Output YES Input 5 ( 2 ) 2 ( 3 ) 1 ) 2 Output YES Input 2 ) 1 ( 1 Output NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The city of Fishtopia can be imagined as a grid of 4 rows and an odd number of columns. It has two main villages; the first is located at the top-left cell (1,1), people who stay there love fishing at the Tuna pond at the bottom-right cell (4, n). The second village is located at (4, 1) and its people love the Salmon pond at (1, n). The mayor of Fishtopia wants to place k hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells. A person can move from one cell to another if those cells are not occupied by hotels and share a side. Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? Input The first line of input contain two integers, n and k (3 ≤ n ≤ 99, 0 ≤ k ≤ 2×(n-2)), n is odd, the width of the city, and the number of hotels to be placed, respectively. Output Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra 4 lines that describe the city, each line should have n characters, each of which is "#" if that cell has a hotel on it, or "." if not. Examples Input 7 2 Output YES ....... .#..... .#..... ....... Input 5 3 Output YES ..... .###. ..... ..... Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The only difference between easy and hard versions is constraints. If you write a solution in Python, then prefer to send it in PyPy to speed up execution time. A session has begun at Beland State University. Many students are taking exams. Polygraph Poligrafovich is going to examine a group of $n$ students. Students will take the exam one-by-one in order from $1$-th to $n$-th. Rules of the exam are following: The $i$-th student randomly chooses a ticket. if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam. if the student finds the ticket easy, he spends exactly $t_i$ minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student. The duration of the whole exam for all students is $M$ minutes ($\max t_i \le M$), so students at the end of the list have a greater possibility to run out of time to pass the exam. For each student $i$, you should count the minimum possible number of students who need to fail the exam so the $i$-th student has enough time to pass the exam. For each student $i$, find the answer independently. That is, if when finding the answer for the student $i_1$ some student $j$ should leave, then while finding the answer for $i_2$ ($i_2>i_1$) the student $j$ student does not have to go home. -----Input----- The first line of the input contains two integers $n$ and $M$ ($1 \le n \le 2 \cdot 10^5$, $1 \le M \le 2 \cdot 10^7$) — the number of students and the total duration of the exam in minutes, respectively. The second line of the input contains $n$ integers $t_i$ ($1 \le t_i \le 100$) — time in minutes that $i$-th student spends to answer to a ticket. It's guaranteed that all values of $t_i$ are not greater than $M$. -----Output----- Print $n$ numbers: the $i$-th number must be equal to the minimum number of students who have to leave the exam in order to $i$-th student has enough time to pass the exam. -----Examples----- Input 7 15 1 2 3 4 5 6 7 Output 0 0 0 0 0 2 3 Input 5 100 80 40 40 40 60 Output 0 1 1 2 3 -----Note----- The explanation for the example 1. Please note that the sum of the first five exam times does not exceed $M=15$ (the sum is $1+2+3+4+5=15$). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are $0$. In order for the $6$-th student to pass the exam, it is necessary that at least $2$ students must fail it before (for example, the $3$-rd and $4$-th, then the $6$-th will finish its exam in $1+2+5+6=14$ minutes, which does not exceed $M$). In order for the $7$-th student to pass the exam, it is necessary that at least $3$ students must fail it before (for example, the $2$-nd, $5$-th and $6$-th, then the $7$-th will finish its exam in $1+3+4+7=15$ minutes, which does not exceed $M$). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Some new animals have arrived at the zoo. The zoo keeper is concerned that perhaps the animals do not have the right tails. To help her, you must correct the broken function to make sure that the second argument (tail), is the same as the last letter of the first argument (body) - otherwise the tail wouldn't fit! If the tail is right return true, else return false. The arguments will always be strings, and normal letters. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 got into number sequences. Now he's got sequence a_1, a_2, ..., a_{n}, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence: f(0) = 0; f(2·x) = f(x); f(2·x + 1) = f(x) + 1. Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤ n) are there, such that f(a_{i}) = f(a_{j}). Help him, count the number of such pairs. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5). The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). The numbers in the lines are separated by single spaces. -----Output----- In a single line print the answer to the problem. Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 3 1 2 4 Output 3 Input 3 5 3 1 Output 1 -----Note----- In the first sample any pair (i, j) will do, so the answer is 3. In the second sample only pair (1, 2) will do. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows. There are two armies on the playing field each of which consists of n men (n is always even). The current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. This is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die. It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore. The game "GAGA" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends. You are asked to calculate the maximum total number of soldiers that may be killed during the game. Input The input data consist of a single integer n (2 ≤ n ≤ 108, n is even). Please note that before the game starts there are 2n soldiers on the fields. Output Print a single number — a maximum total number of soldiers that could be killed in the course of the game in three turns. Examples Input 2 Output 3 Input 4 Output 6 Note The first sample test: 1) Valera's soldiers 1 and 2 shoot at Arcady's soldier 1. 2) Arcady's soldier 2 shoots at Valera's soldier 1. 3) Valera's soldier 1 shoots at Arcady's soldier 2. There are 3 soldiers killed in total: Valera's soldier 1 and Arcady's soldiers 1 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. Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west. Some of the squares have a lotus leaf on it and cannot be entered. The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is .. In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west. The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden. Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2). If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact. -----Constraints----- - 1 \leq H,W,K \leq 10^6 - H \times W \leq 10^6 - 1 \leq x_1,x_2 \leq H - 1 \leq y_1,y_2 \leq W - x_1 \neq x_2 or y_1 \neq y_2. - c_{i,j} is . or @. - c_{x_1,y_1} = . - c_{x_2,y_2} = . - All numbers in input are integers. -----Input----- Input is given from Standard Input in the following format: H W K x_1 y_1 x_2 y_2 c_{1,1}c_{1,2} .. c_{1,W} c_{2,1}c_{2,2} .. c_{2,W} : c_{H,1}c_{H,2} .. c_{H,W} -----Output----- Print the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible. -----Sample Input----- 3 5 2 3 2 3 4 ..... .@..@ ..@.. -----Sample Output----- 5 Initially, Snuke is at the square (3,2). He can reach the square (3, 4) by making five strokes as follows: - From (3, 2), go west one square to (3, 1). - From (3, 1), go north two squares to (1, 1). - From (1, 1), go east two squares to (1, 3). - From (1, 3), go east one square to (1, 4). - From (1, 4), go south two squares to (3, 4). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese , Russian and Vietnamese as well. Chef belongs to a very rich family which owns many gold mines. Today, he brought N gold coins and decided to form a triangle using these coins. Isn't it strange? Chef has a unusual way of forming a triangle using gold coins, which is described as follows: He puts 1 coin in the 1^{st} row. then puts 2 coins in the 2^{nd} row. then puts 3 coins in the 3^{rd} row. and so on as shown in the given figure. Chef is interested in forming a triangle with maximum possible height using at most N coins. Can you tell him the maximum possible height of the triangle? ------ Input ------ The first line of input contains a single integer T denoting the number of test cases. The first and the only line of each test case contains an integer N denoting the number of gold coins Chef has. ------ Output ------ For each test case, output a single line containing an integer corresponding to the maximum possible height of the triangle that Chef can get. ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ N ≤ 10^{9}$ ------ Subtasks ------ $Subtask 1 (48 points) : 1 ≤ N ≤ 10^{5}$ $Subtask 2 (52 points) : 1 ≤ N ≤ 10^{9}$ ----- Sample Input 1 ------ 3 3 5 7 ----- Sample Output 1 ------ 2 2 3 ----- explanation 1 ------ Test 1: Chef can't form a triangle with height > 2 as it requires atleast 6 gold coins. Test 2: Chef can't form a triangle with height > 2 as it requires atleast 6 gold coins. Test 3: Chef can't form a triangle with height > 3 as it requires atleast 10 gold 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. After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes. Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree. After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries. Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root. Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree). Input The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid. Output For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid. Example Input 7 4 1 1 3 3 5 3 1 2 3 5 Output 3 2 3 6 Note <image> The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2. The subtree of the second node consists of this node only, so the answer is 2. Node 3 is centroid of its own subtree. The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins. Across all the sets Misha scored a points in total, and Vanya scored b points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible. Note that the game consisted of several complete sets. -----Input----- The first line contains three space-separated integers k, a and b (1 ≤ k ≤ 10^9, 0 ≤ a, b ≤ 10^9, a + b > 0). -----Output----- If the situation is impossible, print a single number -1. Otherwise, print the maximum possible number of sets. -----Examples----- Input 11 11 5 Output 1 Input 11 2 3 Output -1 -----Note----- Note that the rules of the game in this problem differ from the real table tennis game, for example, the rule of "balance" (the winning player has to be at least two points ahead to win a set) has no power within the present problem. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This problem consists of three subproblems: for solving subproblem F1 you will receive 8 points, for solving subproblem F2 you will receive 15 points, and for solving subproblem F3 you will receive 10 points. Manao has developed a model to predict the stock price of a company over the next n days and wants to design a profit-maximizing trading algorithm to make use of these predictions. Unfortunately, Manao's trading account has the following restrictions: * It only allows owning either zero or one shares of stock at a time; * It only allows buying or selling a share of this stock once per day; * It allows a maximum of k buy orders over the next n days; For the purposes of this problem, we define a trade to a be the act of buying one share of stock on day i, then holding the stock until some day j > i at which point the share is sold. To restate the above constraints, Manao is permitted to make at most k non-overlapping trades during the course of an n-day trading period for which Manao's model has predictions about the stock price. Even though these restrictions limit the amount of profit Manao can make compared to what would be achievable with an unlimited number of trades or the ability to hold more than one share at a time, Manao still has the potential to make a lot of money because Manao's model perfectly predicts the daily price of the stock. For example, using this model, Manao could wait until the price is low, then buy one share and hold until the price reaches a high value, then sell for a profit, and repeat this process up to k times until n days have passed. Nevertheless, Manao is not satisfied by having a merely good trading algorithm, and wants to develop an optimal strategy for trading subject to these constraints. Help Manao achieve this goal by writing a program that will determine when to buy and sell stock to achieve the greatest possible profit during the n-day trading period subject to the above constraints. Input The first line contains two integers n and k, separated by a single space, with <image>. The i-th of the following n lines contains a single integer pi (0 ≤ pi ≤ 1012), where pi represents the price at which someone can either buy or sell one share of stock on day i. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem F1 (8 points), n will be between 1 and 3000, inclusive. * In subproblem F2 (15 points), n will be between 1 and 100000, inclusive. * In subproblem F3 (10 points), n will be between 1 and 4000000, inclusive. Output For this problem, the program will only report the amount of the optimal profit, rather than a list of trades that can achieve this profit. Therefore, the program should print one line containing a single integer, the maximum profit Manao can achieve over the next n days with the constraints of starting with no shares on the first day of trading, always owning either zero or one shares of stock, and buying at most k shares over the course of the n-day trading period. Examples Input 10 2 2 7 3 9 8 7 9 7 1 9 Output 15 Input 10 5 2 7 3 9 8 7 9 7 1 9 Output 21 Note In the first example, the best trade overall is to buy at a price of 1 on day 9 and sell at a price of 9 on day 10 and the second best trade overall is to buy at a price of 2 on day 1 and sell at a price of 9 on day 4. Since these two trades do not overlap, both can be made and the profit is the sum of the profits of the two trades. Thus the trade strategy looks like this: 2 | 7 | 3 | 9 | 8 | 7 | 9 | 7 | 1 | 9 buy | | | sell | | | | | buy | sell The total profit is then (9 - 2) + (9 - 1) = 15. In the second example, even though Manao is allowed up to 5 trades there are only 4 profitable trades available. Making a fifth trade would cost Manao money so he only makes the following 4: 2 | 7 | 3 | 9 | 8 | 7 | 9 | 7 | 1 | 9 buy | sell | buy | sell | | buy | sell | | buy | sell The total profit is then (7 - 2) + (9 - 3) + (9 - 7) + (9 - 1) = 21. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. For a finite set of integers X, let f(X)=\max X - \min X. Given are N integers A_1,...,A_N. We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over all those ways. Since the answer can be enormous, print it \bmod (10^9+7). -----Constraints----- - 1 \leq N \leq 10^5 - 1 \leq K \leq N - |A_i| \leq 10^9 -----Input----- Input is given from Standard Input in the following format: N K A_1 ... A_N -----Output----- Print the answer \bmod (10^9+7). -----Sample Input----- 4 2 1 1 3 4 -----Sample Output----- 11 There are six ways to choose S: \{1,1\},\{1,3\},\{1,4\},\{1,3\},\{1,4\}, \{3,4\} (we distinguish the two 1s). The value of f(S) for these choices are 0,2,3,2,3,1, respectively, for the total of 11. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function $g : \{1,2, \ldots, n \} \rightarrow \{1,2, \ldots, n \}$, that for any $x \in \{1,2, \ldots, n \}$ the formula g(g(x)) = g(x) holds. Let's denote as f^{(}k)(x) the function f applied k times to the value x. More formally, f^{(1)}(x) = f(x), f^{(}k)(x) = f(f^{(}k - 1)(x)) for each k > 1. You are given some function $f : \{1,2, \ldots, n \} \rightarrow \{1,2, \ldots, n \}$. Your task is to find minimum positive integer k such that function f^{(}k)(x) is idempotent. -----Input----- In the first line of the input there is a single integer n (1 ≤ n ≤ 200) — the size of function f domain. In the second line follow f(1), f(2), ..., f(n) (1 ≤ f(i) ≤ n for each 1 ≤ i ≤ n), the values of a function. -----Output----- Output minimum k such that function f^{(}k)(x) is idempotent. -----Examples----- Input 4 1 2 2 4 Output 1 Input 3 2 3 3 Output 2 Input 3 2 3 1 Output 3 -----Note----- In the first sample test function f(x) = f^{(1)}(x) is already idempotent since f(f(1)) = f(1) = 1, f(f(2)) = f(2) = 2, f(f(3)) = f(3) = 2, f(f(4)) = f(4) = 4. In the second sample test: function f(x) = f^{(1)}(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2; function f(x) = f^{(2)}(x) is idempotent since for any x it is true that f^{(2)}(x) = 3, so it is also true that f^{(2)}(f^{(2)}(x)) = 3. In the third sample test: function f(x) = f^{(1)}(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2; function f(f(x)) = f^{(2)}(x) isn't idempotent because f^{(2)}(f^{(2)}(1)) = 2 but f^{(2)}(1) = 3; function f(f(f(x))) = f^{(3)}(x) is idempotent since it is identity function: f^{(3)}(x) = x for any $x \in \{1,2,3 \}$ meaning that the formula f^{(3)}(f^{(3)}(x)) = f^{(3)}(x) also holds. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. How Many Divisors? Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b. Constraints * 1 ≤ a, b, c ≤ 10000 * a ≤ b Input Three integers a, b and c are given in a line separated by a single space. Output Print the number of divisors in a line. Example Input 5 14 80 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. A nested list (or *array* in JavaScript) is a list that apears as a value inside another list, ```python [item, item, [item, item], item] ``` in the above list, [item, item] is a nested list. Your goal is to write a function that determines the depth of the deepest nested list within a given list. return 1 if there are no nested lists. The list passed to your function can contain any data types. A few examples: ```python list_depth([True]) return 1 list_depth([]) return 1 list_depth([2, "yes", [True, False]]) return 2 list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]) return 6 list_depth([2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]]) return 2 ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Gilbert is the network admin of Ginkgo company. His boss is mad about the messy network cables on the floor. He finally walked up to Gilbert and asked the lazy network admin to illustrate how computers and switches are connected. Since he is a programmer, he is very reluctant to move throughout the office and examine cables and switches with his eyes. He instead opted to get this job done by measurement and a little bit of mathematical thinking, sitting down in front of his computer all the time. Your job is to help him by writing a program to reconstruct the network topology from measurements. There are a known number of computers and an unknown number of switches. Each computer is connected to one of the switches via a cable and to nothing else. Specifically, a computer is never connected to another computer directly, or never connected to two or more switches. Switches are connected via cables to form a tree (a connected undirected graph with no cycles). No switches are ‘useless.’ In other words, each switch is on the path between at least one pair of computers. All in all, computers and switches together form a tree whose leaves are computers and whose internal nodes switches (See Figure 9). Gilbert measures the distances between all pairs of computers. The distance between two com- puters is simply the number of switches on the path between the two, plus one. Or equivalently, it is the number of cables used to connect them. You may wonder how Gilbert can actually obtain these distances solely based on measurement. Well, he can do so by a very sophisticated statistical processing technique he invented. Please do not ask the details. You are therefore given a matrix describing distances between leaves of a tree. Your job is to construct the tree from it. Input The input is a series of distance matrices, followed by a line consisting of a single '0'. Each distance matrix is formatted as follows. N a11 a12 ... a1N a21 a22 ... a2N . . . . . . . . . . . . aN1 aN2 ... aNN <image> N is the size, i.e. the number of rows and the number of columns, of the matrix. aij gives the distance between the i-th leaf node (computer) and the j-th. You may assume 2 ≤ N ≤ 50 and the matrix is symmetric whose diagonal elements are all zeros. That is, aii = 0 and aij = aji for each i and j. Each non-diagonal element aij (i ≠ j) satisfies 2 ≤ aij ≤ 30. You may assume there is always a solution. That is, there is a tree having the given distances between leaf nodes. Output For each distance matrix, find a tree having the given distances between leaf nodes. Then output the degree of each internal node (i.e. the number of cables adjoining each switch), all in a single line and in ascending order. Numbers in a line should be separated by a single space. A line should not contain any other characters, including trailing spaces. Examples Input 4 0 2 2 2 2 0 2 2 2 2 0 2 2 2 2 0 4 0 2 4 4 2 0 4 4 4 4 0 2 4 4 2 0 2 0 12 12 0 0 Output 4 2 3 3 2 2 2 2 2 2 2 2 2 2 2 Input 4 0 2 2 2 2 0 2 2 2 2 0 2 2 2 2 0 4 0 2 4 4 2 0 4 4 4 4 0 2 4 4 2 0 2 0 12 12 0 0 Output 4 2 3 3 2 2 2 2 2 2 2 2 2 2 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a directed graph consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it. Can you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex). -----Input----- The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively. Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v). -----Output----- If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO. -----Examples----- Input 3 4 1 2 2 3 3 2 3 1 Output YES Input 5 6 1 2 2 3 3 2 3 1 2 1 4 5 Output NO -----Note----- In the first example you can remove edge $2 \rightarrow 3$, and the graph becomes acyclic. In the second example you have to remove at least two edges (for example, $2 \rightarrow 1$ and $2 \rightarrow 3$) in order to make the graph acyclic. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. According to a new ISO standard, a flag of every country should have, strangely enough, a chequered field n × m, each square should be wholly painted one of 26 colours. The following restrictions are set: * In each row at most two different colours can be used. * No two adjacent squares can be painted the same colour. Pay attention, please, that in one column more than two different colours can be used. Berland's government took a decision to introduce changes into their country's flag in accordance with the new standard, at the same time they want these changes to be minimal. By the given description of Berland's flag you should find out the minimum amount of squares that need to be painted different colour to make the flag meet the new ISO standard. You are as well to build one of the possible variants of the new Berland's flag. Input The first input line contains 2 integers n and m (1 ≤ n, m ≤ 500) — amount of rows and columns in Berland's flag respectively. Then there follows the flag's description: each of the following n lines contains m characters. Each character is a letter from a to z, and it stands for the colour of the corresponding square. Output In the first line output the minimum amount of squares that need to be repainted to make the flag meet the new ISO standard. The following n lines should contain one of the possible variants of the new flag. Don't forget that the variant of the flag, proposed by you, should be derived from the old flag with the minimum amount of repainted squares. If the answer isn't unique, output any. Examples Input 3 4 aaaa bbbb cccc Output 6 abab baba acac Input 3 3 aba aba zzz Output 4 aba bab zbz Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Can you imagine our life if we removed all zeros from it? For sure we will have many problems. In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a and b. Now let's remove all zeros from this equation. Will the equation remain correct after removing all zeros? For example if the equation is 101 + 102 = 203, if we removed all zeros it will be 11 + 12 = 23 which is still a correct equation. But if the equation is 105 + 106 = 211, if we removed all zeros it will be 15 + 16 = 211 which is not a correct equation. Input The input will consist of two lines, the first line will contain the integer a, and the second line will contain the integer b which are in the equation as described above (1 ≤ a, b ≤ 109). There won't be any leading zeros in both. The value of c should be calculated as c = a + b. Output The output will be just one line, you should print "YES" if the equation will remain correct after removing all zeros, and print "NO" otherwise. Examples Input 101 102 Output YES Input 105 106 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. You've had a baby. Well done. Nice isn't it? Life destroying... but in a good way. Part of your new routine is lying awake at night worrying that you've either lost the baby... or that you have more than 1! Given a string of words (x), you need to calculate how many babies are in it. To count as a baby you must have all of the letters in baby ('b', 'a', 'b', 'y'). That counts as 1. They do not need to be in order in the string. Upper and lower case letters count. Examples: If there are no babies in the string - you lost the baby!! Return a different value, as shown below: ```if-not:kotlin 'none here' = "Where's the baby?!" '' = "Where's the baby?!" ``` ```if:kotlin "none here" = null "" = null ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q_1q_2... q_{k}. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string. Sereja wants to test his algorithm. For that, he has string s = s_1s_2... s_{n}, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring s_{l}_{i}s_{l}_{i} + 1... s_{r}_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (l_{i}, r_{i}) determine if the algorithm works correctly on this test or not. -----Input----- The first line contains non-empty string s, its length (n) doesn't exceed 10^5. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 10^5) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). -----Output----- For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. -----Examples----- Input zyxxxxxxyyz 5 5 5 1 3 1 11 1 4 3 6 Output YES YES NO YES NO -----Note----- In the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. Read the inputs from stdin solve the problem and write the answer to stdout (do 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, who is a novice in competitive programming, wants to learn M algorithms. Initially, his understanding level of each of the M algorithms is 0. Takahashi is visiting a bookstore, where he finds N books on algorithms. The i-th book (1\leq i\leq N) is sold for C_i yen (the currency of Japan). If he buys and reads it, his understanding level of the j-th algorithm will increase by A_{i,j} for each j (1\leq j\leq M). There is no other way to increase the understanding levels of the algorithms. Takahashi's objective is to make his understanding levels of all the M algorithms X or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve it. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A renowned abstract artist Sasha, drawing inspiration from nowhere, decided to paint a picture entitled "Special Olympics". He justly thought that, if the regular Olympic games have five rings, then the Special ones will do with exactly two rings just fine. Let us remind you that a ring is a region located between two concentric circles with radii r and R (r < R). These radii are called internal and external, respectively. Concentric circles are circles with centers located at the same point. Soon a white canvas, which can be considered as an infinite Cartesian plane, had two perfect rings, painted with solid black paint. As Sasha is very impulsive, the rings could have different radii and sizes, they intersect and overlap with each other in any way. We know only one thing for sure: the centers of the pair of rings are not the same. When Sasha got tired and fell into a deep sleep, a girl called Ilona came into the room and wanted to cut a circle for the sake of good memories. To make the circle beautiful, she decided to cut along the contour. We'll consider a contour to be a continuous closed line through which there is transition from one color to another (see notes for clarification). If the contour takes the form of a circle, then the result will be cutting out a circle, which Iona wants. But the girl's inquisitive mathematical mind does not rest: how many ways are there to cut a circle out of the canvas? Input The input contains two lines. Each line has four space-separated integers xi, yi, ri, Ri, that describe the i-th ring; xi and yi are coordinates of the ring's center, ri and Ri are the internal and external radii of the ring correspondingly ( - 100 ≤ xi, yi ≤ 100; 1 ≤ ri < Ri ≤ 100). It is guaranteed that the centers of the rings do not coinside. Output A single integer — the number of ways to cut out a circle from the canvas. Examples Input 60 60 45 55 80 80 8 32 Output 1 Input 60 60 45 55 80 60 15 25 Output 4 Input 50 50 35 45 90 50 35 45 Output 0 Note Figures for test samples are given below. The possible cuts are marked with red dotted line. <image> <image> <image> Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Fennec and Snuke are playing a board game. On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the graph formed by the cells and the roads is a tree. Initially, Cell 1 is painted black, and Cell N is painted white. The other cells are not yet colored. Fennec (who goes first) and Snuke (who goes second) alternately paint an uncolored cell. More specifically, each player performs the following action in her/his turn: - Fennec: selects an uncolored cell that is adjacent to a black cell, and paints it black. - Snuke: selects an uncolored cell that is adjacent to a white cell, and paints it white. A player loses when she/he cannot paint a cell. Determine the winner of the game when Fennec and Snuke play optimally. -----Constraints----- - 2 \leq N \leq 10^5 - 1 \leq a_i, b_i \leq N - The given graph is a tree. -----Input----- Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} -----Output----- If Fennec wins, print Fennec; if Snuke wins, print Snuke. -----Sample Input----- 7 3 6 1 2 3 1 7 4 5 7 1 4 -----Sample Output----- Fennec For example, if Fennec first paints Cell 2 black, she will win regardless of Snuke's moves. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 There is a rational number sequence $ X_0, X_1, X_2, ..., X_N $. Each term is defined as follows. 1. $ X_0 = 0 $ 2. $ X_i = X_ {i-1} $ $ op_i $ $ Y_i $ ($ 1 \ leq i \ leq N $). However, $ op_i $ is $ + $, $ − $, $ × $, $ ÷ $ Either. Find $ X_N $. Constraint * $ 1 \ leq N \ leq 10 ^ 5 $ * $ 1 \ leq o_i \ leq 4 $ * $ -10 ^ 6 \ leq Y_i \ leq 10 ^ 6 $ * If $ o_i = 4 $, then $ Y_i \ neq 0 $ * $ X_N $ is an integer greater than or equal to $ -2 ^ {31} $ and less than $ 2 ^ {31} $. input Input follows the following format. All given numbers are integers. $ N $ $ o_1 $ $ Y_1 $ $ o_2 $ $ Y_2 $ $ ... $ $ o_N $ $ Y_N $ When $ o_i = 1 $, $ op_i $ is +, when $ o_i = 2 $, $ op_i $ is −, when $ o_i = 3 $, $ op_i $ is ×, and when $ o_i = 4 $, $ op_i $ is ÷. output Print the value of $ X_N $ on one line. Example Input 4 1 1 4 2 2 4 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. Marcin is a coach in his university. There are $n$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other. Let's focus on the students. They are indexed with integers from $1$ to $n$. Each of them can be described with two integers $a_i$ and $b_i$; $b_i$ is equal to the skill level of the $i$-th student (the higher, the better). Also, there are $60$ known algorithms, which are numbered with integers from $0$ to $59$. If the $i$-th student knows the $j$-th algorithm, then the $j$-th bit ($2^j$) is set in the binary representation of $a_i$. Otherwise, this bit is not set. Student $x$ thinks that he is better than student $y$ if and only if $x$ knows some algorithm which $y$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group. Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum? -----Input----- The first line contains one integer $n$ ($1 \leq n \leq 7000$) — the number of students interested in the camp. The second line contains $n$ integers. The $i$-th of them is $a_i$ ($0 \leq a_i < 2^{60}$). The third line contains $n$ integers. The $i$-th of them is $b_i$ ($1 \leq b_i \leq 10^9$). -----Output----- Output one integer which denotes the maximum sum of $b_i$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0. -----Examples----- Input 4 3 2 3 6 2 8 5 10 Output 15 Input 3 1 2 3 1 2 3 Output 0 Input 1 0 1 Output 0 -----Note----- In the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $b_i$. In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored A·B·C hay blocks and stored them in a barn as a rectangular parallelepiped A layers high. Each layer had B rows and each row had C blocks. At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (A - 1) × (B - 2) × (C - 2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1 × 1 × 1 blocks and scattered them around the barn. After the theft Sam counted n hay blocks in the barn but he forgot numbers A, B и C. Given number n, find the minimally possible and maximally possible number of stolen hay blocks. Input The only line contains integer n from the problem's statement (1 ≤ n ≤ 109). Output Print space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator. Examples Input 4 Output 28 41 Input 7 Output 47 65 Input 12 Output 48 105 Note Let's consider the first sample test. If initially Sam has a parallelepiped consisting of 32 = 2 × 4 × 4 hay blocks in his barn, then after the theft the barn has 4 = (2 - 1) × (4 - 2) × (4 - 2) hay blocks left. Thus, the thieves could have stolen 32 - 4 = 28 hay blocks. If Sam initially had a parallelepiped consisting of 45 = 5 × 3 × 3 hay blocks in his barn, then after the theft the barn has 4 = (5 - 1) × (3 - 2) × (3 - 2) hay blocks left. Thus, the thieves could have stolen 45 - 4 = 41 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $n$ elements. The $i$-th element is $a_i$ ($i$ = $1, 2, \ldots, n$). He gradually takes the first two leftmost elements from the deque (let's call them $A$ and $B$, respectively), and then does the following: if $A > B$, he writes $A$ to the beginning and writes $B$ to the end of the deque, otherwise, he writes to the beginning $B$, and $A$ writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was $[2, 3, 4, 5, 1]$, on the operation he will write $B=3$ to the beginning and $A=2$ to the end, so he will get $[3, 4, 5, 1, 2]$. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him $q$ queries. Each query consists of the singular number $m_j$ $(j = 1, 2, \ldots, q)$. It is required for each query to answer which two elements he will pull out on the $m_j$-th operation. Note that the queries are independent and for each query the numbers $A$ and $B$ should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. -----Input----- The first line contains two integers $n$ and $q$ ($2 \leq n \leq 10^5$, $0 \leq q \leq 3 \cdot 10^5$) — the number of elements in the deque and the number of queries. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$, where $a_i$ $(0 \leq a_i \leq 10^9)$ — the deque element in $i$-th position. The next $q$ lines contain one number each, meaning $m_j$ ($1 \leq m_j \leq 10^{18}$). -----Output----- For each teacher's query, output two numbers $A$ and $B$ — the numbers that Valeriy pulls out of the deque for the $m_j$-th operation. -----Examples----- Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output -----Note----- Consider all 10 steps for the first test in detail: $[1, 2, 3, 4, 5]$ — on the first operation, $A$ and $B$ are $1$ and $2$, respectively. So, $2$ we write to the beginning of the deque, and $1$ — to the end. We get the following status of the deque: $[2, 3, 4, 5, 1]$. $[2, 3, 4, 5, 1] \Rightarrow A = 2, B = 3$. $[3, 4, 5, 1, 2]$ $[4, 5, 1, 2, 3]$ $[5, 1, 2, 3, 4]$ $[5, 2, 3, 4, 1]$ $[5, 3, 4, 1, 2]$ $[5, 4, 1, 2, 3]$ $[5, 1, 2, 3, 4]$ $[5, 2, 3, 4, 1] \Rightarrow A = 5, B = 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. # Largest Rectangle in Background Imagine a photo taken to be used in an advertisement. The background on the left of the motive is whitish and you want to write some text on that background. So you scan the photo with a high resolution scanner and, for each line, count the number of pixels from the left that are sufficiently white and suitable for being written on. Your job is to find the area of the largest text box you can place on those pixels. Example: In the figure below, the whitish background pixels of the scanned photo are represented by asterisks. ``` ********************************* ********* ******* ****** ****** ****** ************** ************** ************** *************** ********************* ``` If you count the pixels on each line from the left you get the list (or array, depending on which language you are using) `[33, 9, 7, 6, 6, 6, 14, 14, 14, 15, 21]`. The largest reactangle that you can place on these pixels has an area of 70, and is represented by the dots in the figure below. ``` ********************************* ********* ******* ****** ****** ****** .............. .............. .............. ..............* ..............******* ``` Write a function that, given a list of the number whitish pixels on each line in the background, returns the area of the largest rectangle that fits on that background. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: - For any integer j (1 \leq j \leq i), P_i \leq P_j. -----Constraints----- - 1 \leq N \leq 2 \times 10^5 - P_1, \ldots, P_N is a permutation of 1, \ldots, N. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N P_1 ... P_N -----Output----- Print the number of integers i that satisfy the condition. -----Sample Input----- 5 4 2 5 1 3 -----Sample Output----- 3 i=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j holds for j = 1. Similarly, i=5 does not satisfy the condition, either. Thus, there are three integers that satisfy the condition. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a function which takes a number and returns the corresponding ASCII char for that value. Example: ~~~if-not:java,racket ``` get_char(65) # => 'A' ``` ~~~ ~~~if:java ~~~ ~~~if:racket ~~~ For ASCII table, you can refer to http://www.asciitable.com/ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something! You have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them to the order you chose: * The x\% of the price of each the a-th sold ticket (a-th, 2a-th, 3a-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources. * The y\% of the price of each the b-th sold ticket (b-th, 2b-th, 3b-th and so on) in the order you chose is aimed for pollution abatement. If the ticket is in both programs then the (x + y) \% are used for environmental activities. Also, it's known that all prices are multiples of 100, so there is no need in any rounding. For example, if you'd like to sell tickets with prices [400, 100, 300, 200] and the cinema pays 10\% of each 2-nd sold ticket and 20\% of each 3-rd sold ticket, then arranging them in order [100, 200, 300, 400] will lead to contribution equal to 100 ⋅ 0 + 200 ⋅ 0.1 + 300 ⋅ 0.2 + 400 ⋅ 0.1 = 120. But arranging them in order [100, 300, 400, 200] will lead to 100 ⋅ 0 + 300 ⋅ 0.1 + 400 ⋅ 0.2 + 200 ⋅ 0.1 = 130. Nature can't wait, so you decided to change the order of tickets in such a way, so that the total contribution to programs will reach at least k in minimum number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least k. Input The first line contains a single integer q (1 ≤ q ≤ 100) — the number of independent queries. Each query consists of 5 lines. The first line of each query contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of tickets. The second line contains n integers p_1, p_2, ..., p_n (100 ≤ p_i ≤ 10^9, p_i mod 100 = 0) — the corresponding prices of tickets. The third line contains two integers x and a (1 ≤ x ≤ 100, x + y ≤ 100, 1 ≤ a ≤ n) — the parameters of the first program. The fourth line contains two integers y and b (1 ≤ y ≤ 100, x + y ≤ 100, 1 ≤ b ≤ n) — the parameters of the second program. The fifth line contains single integer k (1 ≤ k ≤ 10^{14}) — the required total contribution. It's guaranteed that the total number of tickets per test doesn't exceed 2 ⋅ 10^5. Output Print q integers — one per query. For each query, print the minimum number of tickets you need to sell to make the total ecological contribution of at least k if you can sell tickets in any order. If the total contribution can not be achieved selling all the tickets, print -1. Example Input 4 1 100 50 1 49 1 100 8 100 200 100 200 100 200 100 100 10 2 15 3 107 3 1000000000 1000000000 1000000000 50 1 50 1 3000000000 5 200 100 100 100 100 69 5 31 2 90 Output -1 6 3 4 Note In the first query the total contribution is equal to 50 + 49 = 99 < 100, so it's impossible to gather enough money. In the second query you can rearrange tickets in a following way: [100, 100, 200, 200, 100, 200, 100, 100] and the total contribution from the first 6 tickets is equal to 100 ⋅ 0 + 100 ⋅ 0.1 + 200 ⋅ 0.15 + 200 ⋅ 0.1 + 100 ⋅ 0 + 200 ⋅ 0.25 = 10 + 30 + 20 + 50 = 110. In the third query the full price of each ticket goes to the environmental activities. In the fourth query you can rearrange tickets as [100, 200, 100, 100, 100] and the total contribution from the first 4 tickets is 100 ⋅ 0 + 200 ⋅ 0.31 + 100 ⋅ 0 + 100 ⋅ 0.31 = 62 + 31 = 93. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha. You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly $x$ days and that's the exact number of days you will spend visiting your friend. You will spend exactly $x$ consecutive (successive) days visiting Coronavirus-chan. They use a very unusual calendar in Naha: there are $n$ months in a year, $i$-th month lasts exactly $d_i$ days. Days in the $i$-th month are numbered from $1$ to $d_i$. There are no leap years in Naha. The mood of Coronavirus-chan (and, accordingly, her desire to hug you) depends on the number of the day in a month. In particular, you get $j$ hugs if you visit Coronavirus-chan on the $j$-th day of the month. You know about this feature of your friend and want to plan your trip to get as many hugs as possible (and then maybe you can win the heart of Coronavirus-chan). Please note that your trip should not necessarily begin and end in the same year. -----Input----- The first line of input contains two integers $n$ and $x$ ($1 \le n \le 2 \cdot 10^5$) — the number of months in the year and the number of days you can spend with your friend. The second line contains $n$ integers $d_1, d_2, \ldots, d_n$, $d_i$ is the number of days in the $i$-th month ($1 \le d_i \le 10^6$). It is guaranteed that $1 \le x \le d_1 + d_2 + \ldots + d_n$. -----Output----- Print one integer — the maximum number of hugs that you can get from Coronavirus-chan during the best vacation in your life. -----Examples----- Input 3 2 1 3 1 Output 5 Input 3 6 3 3 3 Output 12 Input 5 6 4 2 3 1 3 Output 15 -----Note----- In the first test case, the numbers of the days in a year are (indices of days in a corresponding month) $\{1,1,2,3,1\}$. Coronavirus-chan will hug you the most if you come on the third day of the year: $2+3=5$ hugs. In the second test case, the numbers of the days are $\{1,2,3,1,2,3,1,2,3\}$. You will get the most hugs if you arrive on the third day of the year: $3+1+2+3+1+2=12$ hugs. In the third test case, the numbers of the days are $\{1,2,3,4,1,2, 1,2,3, 1, 1,2,3\}$. You will get the most hugs if you come on the twelfth day of the year: your friend will hug you $2+3+1+2+3+4=15$ times. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem. -----Input----- The first line contains two integers n and m (1 ≤ n ≤ 100; 0 ≤ m ≤ 10^4). The next m lines contain the debts. The i-th line contains three integers a_{i}, b_{i}, c_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}; 1 ≤ c_{i} ≤ 100), which mean that person a_{i} owes person b_{i} c_{i} rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x). -----Output----- Print a single integer — the minimum sum of debts in the optimal rearrangement. -----Examples----- Input 5 3 1 2 10 2 3 1 2 4 1 Output 10 Input 3 0 Output 0 Input 4 3 1 2 1 2 3 1 3 1 1 Output 0 -----Note----- In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10. In the second sample, there are no debts. In the third sample, you can annul all the debts. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 world, a mysterious snake made of only letters lives. Two types of snakes are currently identified, type A and type B, but there may be other types as well. For class A, after ">'" is followed by one or more "=", "#" comes, and after the same number of "=" as before, "~" (half-width tilde) finish. Class B ends with "~~" after "> ^" followed by one or more "Q =". Example of type A:>'==== # ==== ~>'== # == ~ Example of B type:> ^ Q = Q = Q = Q = ~~> ^ Q = Q = ~~ Receives a snake as character string data, determines what kind it is, and outputs "A" for type A, "B" for type B, and "NA" for other types. Please create a program to do. Input The input is given in the following format: n S1 S2 :: Sn The number of snakes identified on the first line n (1 ≤ n ≤ 10000), and the following n lines contain the i-th snake string Si (200 characters or less, without spaces) on each line. Is given to. Output Print the i-th snake type A, B or NA on line i. Example Input 3 >'======#======~ >^Q=Q=Q=Q=Q=Q=Q=Q=Q=~~ >'===#====~ Output A B NA Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even. Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written. Recently, they learned the operation called xor (exclusive OR).What is xor? For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is defined as follows: - When x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even. For example, 3~\textrm{xor}~5 = 6. They wanted to use this operation quickly, so each of them calculated the xor of the integers written on their scarfs except his scarf. We know that the xor calculated by Snuke Cat i, that is, the xor of the integers written on the scarfs except the scarf of Snuke Cat i is a_i. Using this information, restore the integer written on the scarf of each Snuke Cat. -----Constraints----- - All values in input are integers. - 2 \leq N \leq 200000 - N is even. - 0 \leq a_i \leq 10^9 - There exists a combination of integers on the scarfs that is consistent with the given information. -----Input----- Input is given from Standard Input in the following format: N a_1 a_2 \ldots a_N -----Output----- Print a line containing N integers separated with space. The i-th of the integers from the left should represent the integer written on the scarf of Snuke Cat i. If there are multiple possible solutions, you may print any of them. -----Sample Input----- 4 20 11 9 24 -----Sample Output----- 26 5 7 22 - 5~\textrm{xor}~7~\textrm{xor}~22 = 20 - 26~\textrm{xor}~7~\textrm{xor}~22 = 11 - 26~\textrm{xor}~5~\textrm{xor}~22 = 9 - 26~\textrm{xor}~5~\textrm{xor}~7 = 24 Thus, this output is consistent with the given information. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task. You are given two matrices $A$ and $B$ of size $n \times m$, each of which consists of $0$ and $1$ only. You can apply the following operation to the matrix $A$ arbitrary number of times: take any submatrix of the matrix $A$ that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain $0$, will be replaced by $1$, and all corners of the submatrix that contain $1$, will be replaced by $0$). You have to answer whether you can obtain the matrix $B$ from the matrix $A$. [Image] An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow. Ramesses don't want to perform these operations by himself, so he asks you to answer this question. A submatrix of matrix $M$ is a matrix which consist of all elements which come from one of the rows with indices $x_1, x_1+1, \ldots, x_2$ of matrix $M$ and one of the columns with indices $y_1, y_1+1, \ldots, y_2$ of matrix $M$, where $x_1, x_2, y_1, y_2$ are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$, where the cell $(i,j)$ denotes the cell on the intersection of the $i$-th row and the $j$-th column. -----Input----- The first line contains two integers $n$ and $m$ ($1 \leq n, m \leq 500$) — the number of rows and the number of columns in matrices $A$ and $B$. Each of the next $n$ lines contain $m$ integers: the $j$-th integer in the $i$-th line is the $j$-th element of the $i$-th row of the matrix $A$ ($0 \leq A_{ij} \leq 1$). Each of the next $n$ lines contain $m$ integers: the $j$-th integer in the $i$-th line is the $j$-th element of the $i$-th row of the matrix $B$ ($0 \leq B_{ij} \leq 1$). -----Output----- Print "Yes" (without quotes) if it is possible to transform the matrix $A$ to the matrix $B$ using the operations described above, and "No" (without quotes), if it is not possible. You can print each letter in any case (upper or lower). -----Examples----- Input 3 3 0 1 0 0 1 0 1 0 0 1 0 0 1 0 0 1 0 0 Output Yes Input 6 7 0 0 1 1 0 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0 1 1 0 1 0 1 0 0 0 1 0 0 1 0 1 0 1 0 1 0 0 1 1 1 0 1 0 1 1 0 1 1 0 1 0 0 1 1 0 1 0 0 1 1 0 1 0 0 1 0 0 1 1 0 1 0 0 0 1 1 1 1 0 1 Output Yes Input 3 4 0 1 0 1 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 Output No -----Note----- The examples are explained below. [Image] Example 1. [Image] Example 2. [Image] Example 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. Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows. Monocarp went around the building and counted $n$ windows. Now he is wondering, how many apartments of each type the building may have. Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has $n$ windows. If there are multiple answers, you can print any of them. Here are some examples: if Monocarp has counted $30$ windows, there could have been $2$ three-room apartments, $2$ five-room apartments and $2$ seven-room apartments, since $2 \cdot 3 + 2 \cdot 5 + 2 \cdot 7 = 30$; if Monocarp has counted $67$ windows, there could have been $7$ three-room apartments, $5$ five-room apartments and $3$ seven-room apartments, since $7 \cdot 3 + 5 \cdot 5 + 3 \cdot 7 = 67$; if Monocarp has counted $4$ windows, he should have mistaken since no building with the aforementioned layout can have $4$ windows. -----Input----- Th first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. The only line of each test case contains one integer $n$ ($1 \le n \le 1000$) — the number of windows in the building. -----Output----- For each test case, if a building with the new layout and the given number of windows just can't exist, print $-1$. Otherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them. -----Example----- Input 4 30 67 4 14 Output 2 2 2 7 5 3 -1 0 0 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 railroad running from west to east in Atcoder Kingdom is now complete. There are N stations on the railroad, numbered 1 through N from west to east. Tomorrow, the opening ceremony of the railroad will take place. On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i to Station i+1 in C_i seconds. No other trains will be operated. The first train from Station i to Station i+1 will depart Station i S_i seconds after the ceremony begins. Thereafter, there will be a train that departs Station i every F_i seconds. Here, it is guaranteed that F_i divides S_i. That is, for each Time t satisfying S_i≤t and t%F_i=0, there will be a train that departs Station i t seconds after the ceremony begins and arrives at Station i+1 t+C_i seconds after the ceremony begins, where A%B denotes A modulo B, and there will be no other trains. For each i, find the earliest possible time we can reach Station N if we are at Station i when the ceremony begins, ignoring the time needed to change trains. -----Constraints----- - 1≤N≤500 - 1≤C_i≤100 - 1≤S_i≤10^5 - 1≤F_i≤10 - S_i%F_i=0 - All input values are integers. -----Input----- Input is given from Standard Input in the following format: N C_1 S_1 F_1 : C_{N-1} S_{N-1} F_{N-1} -----Output----- Print N lines. Assuming that we are at Station i (1≤i≤N) when the ceremony begins, if the earliest possible time we can reach Station N is x seconds after the ceremony begins, the i-th line should contain x. -----Sample Input----- 3 6 5 1 1 10 1 -----Sample Output----- 12 11 0 We will travel from Station 1 as follows: - 5 seconds after the beginning: take the train to Station 2. - 11 seconds: arrive at Station 2. - 11 seconds: take the train to Station 3. - 12 seconds: arrive at Station 3. We will travel from Station 2 as follows: - 10 seconds: take the train to Station 3. - 11 seconds: arrive at Station 3. Note that we should print 0 for Station 3. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text. Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters). Thus, it points to an index character. The user can move the cursor left or right one position. If the cursor is already at the first (leftmost) position, then it does not move left. Initially, the cursor is in the first (leftmost) character. Also, the user can write a letter or brackets (either (, or )) to the position that the cursor is currently pointing at. A new character always overwrites the old value at that position. Your editor must check, whether the current line is the correct text. Text is correct if the brackets in them form the correct bracket sequence. Formally, correct text (CT) must satisfy the following rules: any line without brackets is CT (the line can contain whitespaces); If the first character of the string — is (, the last — is ), and all the rest form a CT, then the whole line is a CT; two consecutively written CT is also CT. Examples of correct texts: hello(codeforces), round, ((i)(write))edi(tor)s, ( me). Examples of incorrect texts: hello)oops(, round), ((me). The user uses special commands to work with your editor. Each command has its symbol, which must be written to execute this command. The correspondence of commands and characters is as follows: L — move the cursor one character to the left (remains in place if it already points to the first character); R — move the cursor one character to the right; any lowercase Latin letter or bracket (( or )) — write the entered character to the position where the cursor is now. For a complete understanding, take a look at the first example and its illustrations in the note below. You are given a string containing the characters that the user entered. For the brackets coloring module's work, after each command you need to: check if the current text in the editor is a correct text; if it is, print the least number of colors that required, to color all brackets. If two pairs of brackets are nested (the first in the second or vice versa), then these pairs of brackets should be painted in different colors. If two pairs of brackets are not nested, then they can be painted in different or the same colors. For example, for the bracket sequence ()(())()() the least number of colors is $2$, and for the bracket sequence (()(()())())(()) — is $3$. Write a program that prints the minimal number of colors after processing each command. -----Input----- The first line contains an integer $n$ ($1 \le n \le 10^6$) — the number of commands. The second line contains $s$ — a sequence of commands. The string $s$ consists of $n$ characters. It is guaranteed that all characters in a string are valid commands. -----Output----- In a single line print $n$ integers, where the $i$-th number is: $-1$ if the line received after processing the first $i$ commands is not valid text, the minimal number of colors in the case of the correct text. -----Examples----- Input 11 (RaRbR)L)L( Output -1 -1 -1 -1 -1 -1 1 1 -1 -1 2 Input 11 (R)R(R)Ra)c Output -1 -1 1 1 -1 -1 1 1 1 -1 1 -----Note----- In the first example, the text in the editor will take the following form: ( ^ ( ^ (a ^ (a ^ (ab ^ (ab ^ (ab) ^ (ab) ^ (a)) ^ (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. What's in a name? ..Or rather, what's a name in? For us, a particular string is where we are looking for a name. Task Test whether or not the string contains all of the letters which spell a given name, in order. The format A function passing two strings, searching for one (the name) within the other. ``function nameInStr(str, name){ return true || false }`` Examples nameInStr("Across the rivers", "chris") --> true ^ ^ ^^ ^ c h ri s Contains all of the letters in "chris", in order. ---------------------------------------------------------- nameInStr("Next to a lake", "chris") --> false Contains none of the letters in "chris". -------------------------------------------------------------------- nameInStr("Under a sea", "chris") --> false ^ ^ r s Contains only some of the letters in "chris". -------------------------------------------------------------------- nameInStr("A crew that boards the ship", "chris") --> false cr h s i cr h s i c h r s i ... Contains all of the letters in "chris", but not in order. -------------------------------------------------------------------- nameInStr("A live son", "Allison") --> false ^ ^^ ^^^ A li son Contains all of the correct letters in "Allison", in order, but not enough of all of them (missing an 'l'). Note: testing will _not_ be case-sensitive. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. [Haikus](https://en.wikipedia.org/wiki/Haiku_in_English) are short poems in a three-line format, with 17 syllables arranged in a 5–7–5 pattern. Your task is to check if the supplied text is a haiku or not. ### About syllables [Syllables](https://en.wikipedia.org/wiki/Syllable) are the phonological building blocks of words. *In this kata*, a syllable is a part of a word including a vowel ("a-e-i-o-u-y") or a group of vowels (e.g. "ou", "ee", "ay"). A few examples: "tea", "can", "to·day", "week·end", "el·e·phant". **However**, silent "E"s **do not** create syllables. *In this kata*, an "E" is considered silent if it's alone at the end of the word, preceded by one (or more) consonant(s) and there is at least one other syllable in the word. Examples: "age", "ar·range", "con·crete"; but not in "she", "blue", "de·gree". Some more examples: * one syllable words: "cat", "cool", "sprout", "like", "eye", "squeeze" * two syllables words: "ac·count", "hon·est", "beau·ty", "a·live", "be·cause", "re·store" ## Examples ``` An old silent pond... A frog jumps into the pond, splash! Silence again. ``` ...should return `True`, as this is a valid 5–7–5 haiku: ``` An old si·lent pond... # 5 syllables A frog jumps in·to the pond, # 7 splash! Si·lence a·gain. # 5 ``` Another example: ``` Autumn moonlight - a worm digs silently into the chestnut. ``` ...should return `False`, because the number of syllables per line is not correct: ``` Au·tumn moon·light - # 4 syllables a worm digs si·lent·ly # 6 in·to the chest·nut. # 5 ``` --- ## My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-) Read the inputs from stdin solve the problem and write the answer to stdout (do 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 art exhibition will be held in JOI. At the art exhibition, various works of art from all over the country will be exhibited. N works of art were collected as candidates for the works of art to be exhibited. These works of art are numbered 1, 2, ..., N. Each work of art has a set value called size and value. The size of the work of art i (1 \ leq i \ leq N) is A_i, and the value is B_i. At the art exhibition, one or more of these works of art will be selected and exhibited. The venue for the art exhibition is large enough to display all N works of art. However, due to the aesthetic sense of the people of JOI, I would like to select works of art to be exhibited so that the size difference between the works of art does not become too large. On the other hand, I would like to exhibit as many works of art as possible. Therefore, I decided to select the works of art to be exhibited so as to meet the following conditions: * Let A_ {max} be the size of the largest piece of art and A_ {min} be the size of the smallest piece of art selected. Also, let S be the sum of the values ​​of the selected works of art. * At this time, maximize S-(A_ {max} --A_ {min}). Task Given the number of candidates for the works of art to be exhibited and the size and value of each work of art, find the maximum value of S-(A_ {max} --A_ {min}). input Read the following input from standard input. * The integer N is written on the first line. This represents the number of candidates for the works of art to be exhibited. * In the i-th line (1 \ leq i \ leq N) of the following N lines, two integers A_i and B_i are written separated by a blank. These indicate that the size of the work of art i is A_i and the value is B_i. output Output the maximum value of S-(A_ {max} --A_ {min}) to the standard output on one line. Limits All input data satisfy the following conditions. * 2 \ leq N \ leq 500 000. * 1 \ leq A_i \ leq 1 000 000 000 000 000 = 10 ^ {15} (1 \ leq i \ leq N). * 1 \ leq B_i \ leq 1 000 000 000 (1 \ leq i \ leq N). Input / output example Input example 1 3 twenty three 11 2 4 5 Output example 1 6 In this input example, there are three candidates for the works of art to be exhibited. The size and value of each work of art are as follows. * The size of art 1 is 2 and the value is 3. * Art 2 has a size of 11 and a value of 2. * Art 3 has a size of 4 and a value of 5. In this case, if you choose to display art 1 and art 3, then S-(A_ {max} --A_ {min}) = 6 as follows. * The largest work of art selected is work of art 3. Therefore, A_ {max} = 4. * The smallest work of art selected is work of art 1. Therefore, A_ {min} = 2. * Since the sum of the values ​​of the selected works of art is 3 + 5 = 8, S = 8. Since it is impossible to set S-(A_ {max} --A_ {min}) to 7 or more, 6 is output. Input example 2 6 4 1 1 5 10 3 9 1 4 2 5 3 Output example 2 7 Input example 3 15 1543361732 260774320 2089759661 257198921 1555665663 389548466 4133306295 296394520 2596448427 301103944 1701413087 274491541 2347488426 912791996 2133012079 444074242 2659886224 656957044 1345396764 259870638 2671164286 233246973 2791812672 585862344 2996614635 91065315 971304780 488995617 1523452673 988137562 Output example 3 4232545716 Creative Commons License Information Olympics Japan Committee work "17th Japan Information Olympics (JOI 2017/2018) Final Selection" Example Input 3 2 3 11 2 4 5 Output 6 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Santa puts all the presents into the huge sack. In order to let his reindeers rest a bit, he only takes as many reindeers with him as he is required to do. The others may take a nap. Two reindeers are always required for the sleigh and Santa himself. Additionally he needs 1 reindeer per 30 presents. As you know, Santa has 8 reindeers in total, so he can deliver up to 180 presents at once (2 reindeers for Santa and the sleigh + 6 reindeers with 30 presents each). Complete the function `reindeers()`, which takes a number of presents and returns the minimum numbers of required reindeers. If the number of presents is too high, throw an error. Examles: ```python reindeer(0) # must return 2 reindeer(1) # must return 3 reindeer(30) # must return 3 reindeer(200) # must throw an error ``` Read the inputs from stdin solve the problem and write the answer to stdout (do 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 points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i). Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there? We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}. Constraints * 1 \leq N \leq 2\times 10^5 * 0 \leq D \leq 2\times 10^5 * |X_i|,|Y_i| \leq 2\times 10^5 * All values in input are integers. Input Input is given from Standard Input in the following format: N D X_1 Y_1 \vdots X_N Y_N Output Print an integer representing the number of points such that the distance from the origin is at most D. Examples Input 4 5 0 5 -2 4 3 4 4 -4 Output 3 Input 12 3 1 1 1 1 1 1 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 Output 7 Input 20 100000 14309 -32939 -56855 100340 151364 25430 103789 -113141 147404 -136977 -37006 -30929 188810 -49557 13419 70401 -88280 165170 -196399 137941 -176527 -61904 46659 115261 -153551 114185 98784 -6820 94111 -86268 -30401 61477 -55056 7872 5901 -163796 138819 -185986 -69848 -96669 Output 6 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a set of n elements indexed from 1 to n. The weight of i-th element is w_{i}. The weight of some subset of a given set is denoted as $W(S) =|S|\cdot \sum_{i \in S} w_{i}$. The weight of some partition R of a given set into k subsets is $W(R) = \sum_{S \in R} W(S)$ (recall that a partition of a given set is a set of its subsets such that every element of the given set belongs to exactly one subset in partition). Calculate the sum of weights of all partitions of a given set into exactly k non-empty subsets, and print it modulo 10^9 + 7. Two partitions are considered different iff there exist two elements x and y such that they belong to the same set in one of the partitions, and to different sets in another partition. -----Input----- The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2·10^5) — the number of elements and the number of subsets in each partition, respectively. The second line contains n integers w_{i} (1 ≤ w_{i} ≤ 10^9)— weights of elements of the set. -----Output----- Print one integer — the sum of weights of all partitions of a given set into k non-empty subsets, taken modulo 10^9 + 7. -----Examples----- Input 4 2 2 3 2 3 Output 160 Input 5 2 1 2 3 4 5 Output 645 -----Note----- Possible partitions in the first sample: {{1, 2, 3}, {4}}, W(R) = 3·(w_1 + w_2 + w_3) + 1·w_4 = 24; {{1, 2, 4}, {3}}, W(R) = 26; {{1, 3, 4}, {2}}, W(R) = 24; {{1, 2}, {3, 4}}, W(R) = 2·(w_1 + w_2) + 2·(w_3 + w_4) = 20; {{1, 3}, {2, 4}}, W(R) = 20; {{1, 4}, {2, 3}}, W(R) = 20; {{1}, {2, 3, 4}}, W(R) = 26; Possible partitions in the second sample: {{1, 2, 3, 4}, {5}}, W(R) = 45; {{1, 2, 3, 5}, {4}}, W(R) = 48; {{1, 2, 4, 5}, {3}}, W(R) = 51; {{1, 3, 4, 5}, {2}}, W(R) = 54; {{2, 3, 4, 5}, {1}}, W(R) = 57; {{1, 2, 3}, {4, 5}}, W(R) = 36; {{1, 2, 4}, {3, 5}}, W(R) = 37; {{1, 2, 5}, {3, 4}}, W(R) = 38; {{1, 3, 4}, {2, 5}}, W(R) = 38; {{1, 3, 5}, {2, 4}}, W(R) = 39; {{1, 4, 5}, {2, 3}}, W(R) = 40; {{2, 3, 4}, {1, 5}}, W(R) = 39; {{2, 3, 5}, {1, 4}}, W(R) = 40; {{2, 4, 5}, {1, 3}}, W(R) = 41; {{3, 4, 5}, {1, 2}}, W(R) = 42. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 two bus stops denoted A and B, and there n buses that go from A to B every day. The shortest path from A to B takes t units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route. At each station one can find a sorted list of moments of time when a bus is at this station. We denote this list as a_1 < a_2 < … < a_n for stop A and as b_1 < b_2 < … < b_n for stop B. The buses always depart from A and arrive to B according to the timetable, but the order in which the buses arrive may differ. Let's call an order of arrivals valid if each bus arrives at least t units of time later than departs. It is known that for an order to be valid the latest possible arrival for the bus that departs at a_i is b_{x_i}, i.e. x_i-th in the timetable. In other words, for each i there exists such a valid order of arrivals that the bus departed i-th arrives x_i-th (and all other buses can arrive arbitrary), but there is no valid order of arrivals in which the i-th departed bus arrives (x_i + 1)-th. Formally, let's call a permutation p_1, p_2, …, p_n valid, if b_{p_i} ≥ a_i + t for all i. Then x_i is the maximum value of p_i among all valid permutations. You are given the sequences a_1, a_2, …, a_n and x_1, x_2, …, x_n, but not the arrival timetable. Find out any suitable timetable for stop B b_1, b_2, …, b_n or determine that there is no such timetable. Input The first line of the input contains two integers n and t (1 ≤ n ≤ 200 000, 1 ≤ t ≤ 10^{18}) — the number of buses in timetable for and the minimum possible travel time from stop A to stop B. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_1 < a_2 < … < a_n ≤ 10^{18}), defining the moments of time when the buses leave stop A. The third line contains n integers x_1, x_2, …, x_n (1 ≤ x_i ≤ n), the i-th of them stands for the maximum possible timetable position, at which the i-th bus leaving stop A can arrive at stop B. Output If a solution exists, print "Yes" (without quotes) in the first line of the output. In the second line print n integers b_1, b_2, …, b_n (1 ≤ b_1 < b_2 < … < b_n ≤ 3 ⋅ 10^{18}). We can show that if there exists any solution, there exists a solution that satisfies such constraints on b_i. If there are multiple valid answers you can print any of them. If there is no valid timetable, print "No" (without quotes) in the only line of the output. Examples Input 3 10 4 6 8 2 2 3 Output Yes 16 17 21 Input 2 1 1 2 2 1 Output No Note Consider the first example and the timetable b_1, b_2, …, b_n from the output. To get x_1 = 2 the buses can arrive in the order (2, 1, 3). To get x_2 = 2 and x_3 = 3 the buses can arrive in the order (1, 2, 3). x_1 is not 3, because the permutations (3, 1, 2) and (3, 2, 1) (all in which the 1-st bus arrives 3-rd) are not valid (sube buses arrive too early), x_2 is not 3 because of similar reasons. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Rng is preparing a problem set for a qualification round of CODEFESTIVAL. He has N candidates of problems. The difficulty of the i-th candidate is D_i. There must be M problems in the problem set, and the difficulty of the i-th problem must be T_i. Here, one candidate of a problem cannot be used as multiple problems. Determine whether Rng can complete the problem set without creating new candidates of problems. Constraints * 1 \leq N \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq M \leq 200,000 * 1 \leq T_i \leq 10^9 * All numbers in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 ... D_N M T_1 T_2 ... T_M Output Print `YES` if Rng can complete the problem set without creating new candidates of problems; print `NO` if he cannot. Examples Input 5 3 1 4 1 5 3 5 4 3 Output YES Input 7 100 200 500 700 1200 1600 2000 6 100 200 500 700 1600 1600 Output NO Input 1 800 5 100 100 100 100 100 Output NO Input 15 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 9 5 4 3 2 1 2 3 4 5 Output YES Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contest started and Vasya submitted the problem d minutes after the contest started. As you know, on Codeforces the cost of a problem reduces as a round continues. That is, if you submit a problem that costs p points t minutes after the contest started, you get $\operatorname{max}(\frac{3p}{10}, p - \frac{p}{250} \times t)$ points. Misha and Vasya are having an argument trying to find out who got more points. Help them to find out the truth. -----Input----- The first line contains four integers a, b, c, d (250 ≤ a, b ≤ 3500, 0 ≤ c, d ≤ 180). It is guaranteed that numbers a and b are divisible by 250 (just like on any real Codeforces round). -----Output----- Output on a single line: "Misha" (without the quotes), if Misha got more points than Vasya. "Vasya" (without the quotes), if Vasya got more points than Misha. "Tie" (without the quotes), if both of them got the same number of points. -----Examples----- Input 500 1000 20 30 Output Vasya Input 1000 1000 1 1 Output Tie Input 1500 1000 176 177 Output Misha Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the screen as possible and fits within it completely. Thus, he may have to zoom the movie in or out, but Manao will always change the frame proportionally in both dimensions. Calculate the ratio of empty screen (the part of the screen not occupied by the movie) to the total screen size. Print the answer as an irreducible fraction p / q. -----Input----- A single line contains four space-separated integers a, b, c, d (1 ≤ a, b, c, d ≤ 1000). -----Output----- Print the answer to the problem as "p/q", where p is a non-negative integer, q is a positive integer and numbers p and q don't have a common divisor larger than 1. -----Examples----- Input 1 1 3 2 Output 1/3 Input 4 3 2 2 Output 1/4 -----Note----- Sample 1. Manao's monitor has a square screen. The movie has 3:2 horizontal to vertical length ratio. Obviously, the movie occupies most of the screen if the width of the picture coincides with the width of the screen. In this case, only 2/3 of the monitor will project the movie in the horizontal dimension: [Image] Sample 2. This time the monitor's width is 4/3 times larger than its height and the movie's frame is square. In this case, the picture must take up the whole monitor in the vertical dimension and only 3/4 in the horizontal dimension: [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. The objective is to return all pairs of integers from a given array of integers that have a difference of 2. The result array should be sorted in ascending order of values. Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter. ## Examples ~~~if-not:python ``` [1, 2, 3, 4] should return [[1, 3], [2, 4]] [4, 1, 2, 3] should also return [[1, 3], [2, 4]] [1, 23, 3, 4, 7] should return [[1, 3]] [4, 3, 1, 5, 6] should return [[1, 3], [3, 5], [4, 6]] ``` ~~~ ~~~if:python ``` [1, 2, 3, 4] should return [(1, 3), (2, 4)] [4, 1, 2, 3] should also return [(1, 3), (2, 4)] [1, 23, 3, 4, 7] should return [(1, 3)] [4, 3, 1, 5, 6] should return [(1, 3), (3, 5), (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. The biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. $2^n$ teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from $1$ to $2^n$ and will play games one-on-one. All teams start in the upper bracket. All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket. Lower bracket starts with $2^{n-1}$ teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round $2^k$ teams play a game with each other (teams are split into games by team numbers). $2^{k-1}$ loosing teams are eliminated from the championship, $2^{k-1}$ winning teams are playing $2^{k-1}$ teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have $2^{k-1}$ teams remaining. See example notes for better understanding. Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner. You are a fan of teams with numbers $a_1, a_2, ..., a_k$. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of? -----Input----- First input line has two integers $n, k$ — $2^n$ teams are competing in the championship. You are a fan of $k$ teams ($2 \le n \le 17; 0 \le k \le 2^n$). Second input line has $k$ distinct integers $a_1, \ldots, a_k$ — numbers of teams you're a fan of ($1 \le a_i \le 2^n$). -----Output----- Output single integer — maximal possible number of championship games that include teams you're fan of. -----Examples----- Input 3 1 6 Output 6 Input 3 3 1 7 8 Output 11 Input 3 4 1 3 5 7 Output 14 -----Note----- On the image, each game of the championship is denoted with an English letter ($a$ to $n$). Winner of game $i$ is denoted as $Wi$, loser is denoted as $Li$. Teams you're a fan of are highlighted with red background. In the first example, team $6$ will play in 6 games if it looses the first upper bracket game (game $c$) and wins all lower bracket games (games $h, j, l, m$). [Image] In the second example, teams $7$ and $8$ have to play with each other in the first game of upper bracket (game $d$). Team $8$ can win all remaining games in upper bracket, when teams $1$ and $7$ will compete in the lower bracket. [Image] In the third example, your favourite teams can play in all games of the championship. [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. On March 14, the day of the number $\pi$ is celebrated all over the world. This is a very important mathematical constant equal to the ratio of the circumference of a circle to its diameter. Polycarp was told at school that the number $\pi$ is irrational, therefore it has an infinite number of digits in decimal notation. He wanted to prepare for the Day of the number $\pi$ by memorizing this number as accurately as possible. Polycarp wrote out all the digits that he managed to remember. For example, if Polycarp remembered $\pi$ as $3.1415$, he wrote out 31415. Polycarp was in a hurry and could have made a mistake, so you decided to check how many first digits of the number $\pi$ Polycarp actually remembers correctly. -----Input----- The first line of the input data contains the single integer $t$ ($1 \le t \le 10^3$) — the number of test cases in the test. Each test case is described by a single string of digits $n$, which was written out by Polycarp. The string $n$ contains up to $30$ digits. -----Output----- Output $t$ integers, each of which is the answer to the corresponding test case, that is how many first digits of the number $\pi$ Polycarp remembers correctly. -----Examples----- Input 9 000 3 4141592653 141592653589793238462643383279 31420 31415 314159265358 27182 314159265358979323846264338327 Output 0 1 0 0 3 5 12 0 30 -----Note----- None Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points. Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined, there were n contestants in the tournament, numbered from 1 to n. Each of them had already obtained some amount of tournament points, namely the i-th fighter had pi points. Manao is going to engage in a single fight against each contestant. Each of Manao's fights ends in either a win or a loss. A win grants Manao one point, and a loss grants Manao's opponent one point. For each i, Manao estimated the amount of effort ei he needs to invest to win against the i-th contestant. Losing a fight costs no effort. After Manao finishes all of his fights, the ranklist will be determined, with 1 being the best rank and n + 1 being the worst. The contestants will be ranked in descending order of their tournament points. The contestants with the same number of points as Manao will be ranked better than him if they won the match against him and worse otherwise. The exact mechanism of breaking ties for other fighters is not relevant here. Manao's objective is to have rank k or better. Determine the minimum total amount of effort he needs to invest in order to fulfill this goal, if it is possible. Input The first line contains a pair of integers n and k (1 ≤ k ≤ n + 1). The i-th of the following n lines contains two integers separated by a single space — pi and ei (0 ≤ pi, ei ≤ 200000). The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem C1 (4 points), the constraint 1 ≤ n ≤ 15 will hold. * In subproblem C2 (4 points), the constraint 1 ≤ n ≤ 100 will hold. * In subproblem C3 (8 points), the constraint 1 ≤ n ≤ 200000 will hold. Output Print a single number in a single line — the minimum amount of effort Manao needs to use to rank in the top k. If no amount of effort can earn Manao such a rank, output number -1. Examples Input 3 2 1 1 1 4 2 2 Output 3 Input 2 1 3 2 4 0 Output -1 Input 5 2 2 10 2 10 1 1 3 1 3 1 Output 12 Note Consider the first test case. At the time when Manao joins the tournament, there are three fighters. The first of them has 1 tournament point and the victory against him requires 1 unit of effort. The second contestant also has 1 tournament point, but Manao needs 4 units of effort to defeat him. The third contestant has 2 points and victory against him costs Manao 2 units of effort. Manao's goal is top be in top 2. The optimal decision is to win against fighters 1 and 3, after which Manao, fighter 2, and fighter 3 will all have 2 points. Manao will rank better than fighter 3 and worse than fighter 2, thus finishing in second place. Consider the second test case. Even if Manao wins against both opponents, he will still rank third. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k. Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them. Input The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9). Output If there are no such points, print "NO". Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower). Examples Input 4 3 3 Output YES 1 0 2 3 4 1 Input 4 4 7 Output NO Note In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below: <image> In the second example there is no triangle with area nm/k = 16/7. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Robbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches. First, as they know that kingdom police is bad at math, robbers use the positional numeral system with base 7. Second, they divide one day in n hours, and each hour in m minutes. Personal watches of each robber are divided in two parts: first of them has the smallest possible number of places that is necessary to display any integer from 0 to n - 1, while the second has the smallest possible number of places that is necessary to display any integer from 0 to m - 1. Finally, if some value of hours or minutes can be displayed using less number of places in base 7 than this watches have, the required number of zeroes is added at the beginning of notation. Note that to display number 0 section of the watches is required to have at least one place. Little robber wants to know the number of moments of time (particular values of hours and minutes), such that all digits displayed on the watches are distinct. Help her calculate this number. Input The first line of the input contains two integers, given in the decimal notation, n and m (1 ≤ n, m ≤ 109) — the number of hours in one day and the number of minutes in one hour, respectively. Output Print one integer in decimal notation — the number of different pairs of hour and minute, such that all digits displayed on the watches are distinct. Examples Input 2 3 Output 4 Input 8 2 Output 5 Note In the first sample, possible pairs are: (0: 1), (0: 2), (1: 0), (1: 2). In the second sample, possible pairs are: (02: 1), (03: 1), (04: 1), (05: 1), (06: 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. With the motto "Creating your own path," a shrine created a fortune-telling fortune with its own hands. Ask the person who draws the lottery to throw six stones first, then the line segment connecting the first and second of the thrown stones, the line segment connecting the third and fourth, the fifth and six The fortune is determined from the area of ​​the triangle whose apex is the intersection of the three line segments connecting the second line segment. The relationship between each fortune and the area of ​​the triangle is as follows. Area of ​​a triangle whose apex is the intersection of line segments | Fortune --- | --- Over 1,900,000 | Daikichi 1,000,000 or more and less than 1,900,000 | Nakayoshi (chu-kichi) 100,000 or more and less than 1,000,000 | Kichi Greater than 0 and less than 100,000 | Kokichi (syo-kichi) No triangle | Kyo However, the size of the area of ​​the triangle is determined by the priest by hand, so it cannot be said to be accurate and it takes time. So, as an excellent programmer living in the neighborhood, you decided to write a program as soon as possible to help the priest. Create a program that takes the information of three line segments as input and outputs the fortune from the area of ​​the triangle whose vertices are the intersections of the line segments. The line segment information is given the coordinates of the start point (x1, y1) and the coordinates of the end point (x2, y2), and the coordinates of the start point and the end point must be different. Also, if two or more line segments are on the same straight line, if there are two line segments that do not have intersections, or if three line segments intersect at one point, it is "no triangle". <image> Input A sequence of multiple datasets is given as input. The end of the input is indicated by four zero lines. Each dataset is given in the following format: line1 line2 line3 The i-th line is given the information of the i-th line segment. Information for each line is given in the following format. x1 y1 x2 y2 Integers (x1, y1), (x2, y2) (-1000 ≤ x1, y1, x2, y2 ≤ 1000) representing the coordinates of the endpoints of the line segment are given, separated by blanks. Output The result of the fortune telling is output to one line for each data set. Example Input -3 -2 9 6 3 -2 7 6 -1 0 5 0 2 2 -1 -1 0 1 2 1 -3 -1 3 1 0 0 0 0 Output syo-kichi kyo Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. It is important to use strong passwords to make the Internet more secure. At the same time, it is very important not to reuse the same password. No matter how strong your password is, if the plaintext is leaked in one place, it will be very easy to break. Of course, if all applications hash passwords and use SALT properly, such damage will not occur even if leaked, but there are still applications that store passwords in clear text. Well, the contest is about to begin. I have to register a team account ... problem A string representing the password is given. Check if the character string meets all of the following conditions, and if it meets all of the following conditions, output "VALID", and if there is an item that does not meet even one, output "INVALID". * String length is 6 or more * Contains one or more numbers * Contains one or more uppercase letters * Contains one or more lowercase letters input A string representing the password is given on one line. output Print "VALID" if the password string meets all the conditions in question, and "INVALID" if there are conditions that do not. Constraint * The password string must be between 1 and 20 characters. * Password string contains only uppercase letters, lowercase letters, and numbers Input / output example Input 1 password Output 1 INVALID It is a password that is widely used all over the world. Input 2 AizuCamp2013 Output 2 VALID Great password. Input 3 1234 Output 3 INVALID Widely used as a PIN. Input 4 NaBiO3 Output 4 VALID It is barely 6 characters or more. Example Input password Output INVALID Read the inputs from stdin solve the problem and write the answer to stdout (do 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 door of Snuke's laboratory is locked with a security code. The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same. You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good. -----Constraints----- - S is a 4-character string consisting of digits. -----Input----- Input is given from Standard Input in the following format: S -----Output----- If S is hard to enter, print Bad; otherwise, print Good. -----Sample Input----- 3776 -----Sample Output----- Bad The second and third digits are the same, so 3776 is hard to enter. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a 4-character string S consisting of uppercase English letters. Determine if S consists of exactly two kinds of characters which both appear twice in S. -----Constraints----- - The length of S is 4. - S consists of uppercase English letters. -----Input----- Input is given from Standard Input in the following format: S -----Output----- If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No. -----Sample Input----- ASSA -----Sample Output----- Yes S consists of A and S which both appear twice in S. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. This is a problem that involves adding numbers to items in a list. In a list you will have to add the item's remainder when divided by a given divisor to each item. For example if the item is 40 and the divisor is 3 you would have to add 1 since 40 minus the closest multiple of 3 which is 39 is 1. So the 40 in the list will become 41. You would have to return the modified list in this problem. For this problem you will receive a divisor called `div` as well as simple list of whole numbers called `nums`. Good luck and happy coding. # Examples ```python nums = [2, 7, 5, 9, 100, 34, 32, 0], div = 3 ==> [4, 8, 7, 9, 101, 35, 34, 0] nums = [1000, 999, 998, 997], div = 5 ==> [1000, 1003, 1001, 999] nums = [], div = 2 ==> [] ``` **Note:** random tests check lists containing up to 10000 elements. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ## Task Your challenge is to write a function named `getSlope`/`get_slope`/`GetSlope` that calculates the slope of the line through two points. ## Input ```if:javascript,python Each point that the function takes in is an array 2 elements long. The first number is the x coordinate and the second number is the y coordinate. If the line through the two points is vertical or if the same point is given twice, the function should return `null`/`None`. ``` ```if:csharp `GetSlope` will take in two Point objects. If the line through the two points is vertical, or the two points are the same, return `null`. The Point object: ~~~ public class Point : System.Object { public double X; public double Y; public Point(double x, double y) { this.X = x; this.Y = y; } public override string ToString() { return $"({this.X}, {this.Y})"; } public override bool Equals(object point) { // Typechecking if (point == null || point.GetType() != this.GetType()) { return false; } return this.ToString() == point.ToString(); } } ~~~ ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Robbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches. First, as they know that kingdom police is bad at math, robbers use the positional numeral system with base 7. Second, they divide one day in n hours, and each hour in m minutes. Personal watches of each robber are divided in two parts: first of them has the smallest possible number of places that is necessary to display any integer from 0 to n - 1, while the second has the smallest possible number of places that is necessary to display any integer from 0 to m - 1. Finally, if some value of hours or minutes can be displayed using less number of places in base 7 than this watches have, the required number of zeroes is added at the beginning of notation. Note that to display number 0 section of the watches is required to have at least one place. Little robber wants to know the number of moments of time (particular values of hours and minutes), such that all digits displayed on the watches are distinct. Help her calculate this number. -----Input----- The first line of the input contains two integers, given in the decimal notation, n and m (1 ≤ n, m ≤ 10^9) — the number of hours in one day and the number of minutes in one hour, respectively. -----Output----- Print one integer in decimal notation — the number of different pairs of hour and minute, such that all digits displayed on the watches are distinct. -----Examples----- Input 2 3 Output 4 Input 8 2 Output 5 -----Note----- In the first sample, possible pairs are: (0: 1), (0: 2), (1: 0), (1: 2). In the second sample, possible pairs are: (02: 1), (03: 1), (04: 1), (05: 1), (06: 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. Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $k$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins. Now each knight ponders: how many coins he can have if only he kills other knights? You should answer this question for each knight. -----Input----- The first line contains two integers $n$ and $k$ $(1 \le n \le 10^5, 0 \le k \le \min(n-1,10))$ — the number of knights and the number $k$ from the statement. The second line contains $n$ integers $p_1, p_2 ,\ldots,p_n$ $(1 \le p_i \le 10^9)$ — powers of the knights. All $p_i$ are distinct. The third line contains $n$ integers $c_1, c_2 ,\ldots,c_n$ $(0 \le c_i \le 10^9)$ — the number of coins each knight has. -----Output----- Print $n$ integers — the maximum number of coins each knight can have it only he kills other knights. -----Examples----- Input 4 2 4 5 9 7 1 2 11 33 Output 1 3 46 36 Input 5 1 1 2 3 4 5 1 2 3 4 5 Output 1 3 5 7 9 Input 1 0 2 3 Output 3 -----Note----- Consider the first example. The first knight is the weakest, so he can't kill anyone. That leaves him with the only coin he initially has. The second knight can kill the first knight and add his coin to his own two. The third knight is the strongest, but he can't kill more than $k = 2$ other knights. It is optimal to kill the second and the fourth knights: $2+11+33 = 46$. The fourth knight should kill the first and the second knights: $33+1+2 = 36$. In the second example the first knight can't kill anyone, while all the others should kill the one with the index less by one than their own. In the third example there is only one knight, so he can't kill anyone. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degree_{v} and s_{v}, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degree_{v} and s_{v} left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha. -----Input----- The first line contains integer n (1 ≤ n ≤ 2^16), the number of vertices in the graph. The i-th of the next lines contains numbers degree_{i} and s_{i} (0 ≤ degree_{i} ≤ n - 1, 0 ≤ s_{i} < 2^16), separated by a space. -----Output----- In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order. -----Examples----- Input 3 2 3 1 0 1 0 Output 2 1 0 2 0 Input 2 1 1 1 0 Output 1 0 1 -----Note----- The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is a tree T with N vertices, numbered 1 through N. For each 1 ≤ i ≤ N - 1, the i-th edge connects vertices a_i and b_i. Snuke is constructing a directed graph T' by arbitrarily assigning direction to each edge in T. (There are 2^{N - 1} different ways to construct T'.) For a fixed T', we will define d(s,\ t) for each 1 ≤ s,\ t ≤ N, as follows: * d(s,\ t) = (The number of edges that must be traversed against the assigned direction when traveling from vertex s to vertex t) In particular, d(s,\ s) = 0 for each 1 ≤ s ≤ N. Also note that, in general, d(s,\ t) ≠ d(t,\ s). We will further define D as the following: 3d2f3f88e8fa23f065c04cd175c14ebf.png Snuke is constructing T' so that D will be the minimum possible value. How many different ways are there to construct T' so that D will be the minimum possible value, modulo 10^9 + 7? Constraints * 2 ≤ N ≤ 1000 * 1 ≤ a_i,\ b_i ≤ N * The given graph is a tree. Input The input is given from Standard Input in the following format: N a_1 b_1 a_2 b_2 : a_{N - 1} b_{N - 1} Output Print the number of the different ways to construct T' so that D will be the minimum possible value, modulo 10^9 + 7. Examples Input 4 1 2 1 3 1 4 Output 2 Input 4 1 2 2 3 3 4 Output 6 Input 6 1 2 1 3 1 4 2 5 2 6 Output 14 Input 10 2 4 2 5 8 3 10 7 1 6 2 8 9 5 8 6 10 6 Output 102 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Rational numbers are numbers represented by ratios of two integers. For a prime number p, one of the elementary theorems in the number theory is that there is no rational number equal to √p. Such numbers are called irrational numbers. It is also known that there are rational numbers arbitrarily close to √p Now, given a positive integer n, we define a set Qn of all rational numbers whose elements are represented by ratios of two positive integers both of which are less than or equal to n. For example, Q4 is a set of 11 rational numbers {1/1, 1/2, 1/3, 1/4, 2/1, 2/3, 3/1, 3/2, 3/4, 4/1, 4/3}. 2/2, 2/4, 3/3, 4/2 and 4/4 are not included here because they are equal to 1/1, 1/2, 1/1, 2/1 and 1/1, respectively. Your job is to write a program that reads two integers p and n and reports two rational numbers x / y and u / v, where u / v < √p < x / y and there are no other elements of Qn between u/v and x/y. When n is greater than √p, such a pair of rational numbers always exists. Input The input consists of lines each of which contains two positive integers, a prime number p and an integer n in the following format. p n They are separated by a space character. You can assume that p and n are less than 10000, and that n is greater than √p. The end of the input is indicated by a line consisting of two zeros. Output For each input line, your program should output a line consisting of the two rational numbers x / y and u / v (x / y > u / v) separated by a space character in the following format. x/y u/v They should be irreducible. For example, 6/14 and 15/3 are not accepted. They should be reduced to 3/7 and 5/1, respectively. Example Input 2 5 3 10 5 100 0 0 Output 3/2 4/3 7/4 5/3 85/38 38/17 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Chef's new hobby is painting, but he learned the fact that it's not easy to paint 2D pictures in a hard way, after wasting a lot of canvas paper, paint and of course time. From now on, he decided to paint 1D pictures only. Chef's canvas is N millimeters long and is initially all white. For simplicity, colors will be represented by an integer between 0 and 105. 0 indicates white. The picture he is envisioning is also N millimeters long and the ith millimeter consists purely of the color Ci. Unfortunately, his brush isn't fine enough to paint every millimeter one by one. The brush is 3 millimeters wide and so it can only paint three millimeters at a time with the same color. Painting over the same place completely replaces the color by the new one. Also, Chef has lots of bottles of paints of each color, so he will never run out of paint of any color. Chef also doesn't want to ruin the edges of the canvas, so he doesn't want to paint any part beyond the painting. This means, for example, Chef cannot paint just the first millimeter of the canvas, or just the last two millimeters, etc. Help Chef by telling him whether he can finish the painting or not with these restrictions. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N. The second line contains N space-separated integers C1, C2, ..., CN denoting the colors of Chef's painting. -----Output----- For each test case, output a single line containing either “Yes” or “No” (without quotes), denoting whether Chef can finish the painting or not. -----Constraints----- - 1 ≤ T ≤ 105 - 3 ≤ N ≤ 105 - The sum of the Ns over all the test cases in a single test file is ≤ 5×105 - 1 ≤ Ci ≤ 105 -----Example----- Input:3 4 1 5 5 5 4 1 1 1 5 3 5 5 2 Output:Yes Yes No -----Explanation----- Example case 1. Chef's canvas initially contains the colors [0,0,0,0]. Chef can finish the painting by first painting the first three millimeters with color 1, so the colors become [1,1,1,0], and then the last three millimeters with color 5 so that it becomes [1,5,5,5]. Example case 2. Chef's canvas initially contains the colors [0,0,0,0]. Chef can finish the painting by first painting the last three millimeters by color 5 so the colors become [0,5,5,5], and then the first three millimeters by color 1 so it becomes [1,1,1,5]. Example case 3. In this test case, Chef can only paint the painting as a whole, so all parts must have the same color, and the task is impossible. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mr. Takahashi has a string s consisting of lowercase English letters. He repeats the following operation on s exactly K times. * Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of `z` is `a`. For example, if you perform an operation for the second letter on `aaz`, `aaz` becomes `abz`. If you then perform an operation for the third letter on `abz`, `abz` becomes `aba`. Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s. Find the such string. Constraints * 1≤|s|≤10^5 * All letters in s are lowercase English letters. * 1≤K≤10^9 Input The input is given from Standard Input in the following format: s K Output Print the lexicographically smallest string after performing exactly K operations on s. Examples Input xyz 4 Output aya Input a 25 Output z Input codefestival 100 Output aaaafeaaivap Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts. There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses. Find the minimum distance to be traveled when AtCoDeer can start and end his travel at any positions. -----Constraints----- - 1 ≤ N ≤ 100 - 0 ≤ a_i ≤ 1000 - a_i is an integer. -----Input----- Input is given from Standard Input in the following format: N a_1 a_2 ... a_N -----Output----- Print the minimum distance to be traveled. -----Sample Input----- 4 2 3 7 9 -----Sample Output----- 7 The travel distance of 7 can be achieved by starting at coordinate 9 and traveling straight to coordinate 2. It is not possible to do with a travel distance of less than 7, and thus 7 is the minimum distance to be traveled. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much. A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at volume v (1 ≤ v ≤ a_{i}; v is an integer) both on the piano and the guitar. They should retain harmony, so the total volume with which the i-th note was played on the guitar and the piano must equal b_{i}. If Dima and Inna cannot play a note by the described rules, they skip it and Sereja's joy drops by 1. But if Inna and Dima play the i-th note at volumes x_{i} and y_{i} (x_{i} + y_{i} = b_{i}) correspondingly, Sereja's joy rises by x_{i}·y_{i}. Sereja has just returned home from the university and his current joy is 0. Help Dima and Inna play the song so as to maximize Sereja's total joy after listening to the whole song! -----Input----- The first line of the input contains integer n (1 ≤ n ≤ 10^5) — the number of notes in the song. The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^6). The third line contains n integers b_{i} (1 ≤ b_{i} ≤ 10^6). -----Output----- In a single line print an integer — the maximum possible joy Sereja feels after he listens to a song. -----Examples----- Input 3 1 1 2 2 2 3 Output 4 Input 1 2 5 Output -1 -----Note----- In the first sample, Dima and Inna play the first two notes at volume 1 (1 + 1 = 2, the condition holds), they should play the last note at volumes 1 and 2. Sereja's total joy equals: 1·1 + 1·1 + 1·2 = 4. In the second sample, there is no such pair (x, y), that 1 ≤ x, y ≤ 2, x + y = 5, so Dima and Inna skip a note. Sereja's total joy equals -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. # Don't give me five! In this kata you get the start number and the end number of a region and should return the count of all numbers except numbers with a 5 in it. The start and the end number are both inclusive! Examples: ``` 1,9 -> 1,2,3,4,6,7,8,9 -> Result 8 4,17 -> 4,6,7,8,9,10,11,12,13,14,16,17 -> Result 12 ``` The result may contain fives. ;-) The start number will always be smaller than the end number. Both numbers can be also negative! I'm very curious for your solutions and the way you solve it. Maybe someone of you will find an easy pure mathematics solution. Have fun coding it and please don't forget to vote and rank this kata! :-) I have also created other katas. Take a look if you enjoyed this kata! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Many years have passed, and n friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo. Simply speaking, the process of photographing can be described as follows. Each friend occupies a rectangle of pixels on the photo: the i-th of them in a standing state occupies a w_{i} pixels wide and a h_{i} pixels high rectangle. But also, each person can lie down for the photo, and then he will occupy a h_{i} pixels wide and a w_{i} pixels high rectangle. The total photo will have size W × H, where W is the total width of all the people rectangles, and H is the maximum of the heights. The friends want to determine what minimum area the group photo can they obtain if no more than n / 2 of them can lie on the ground (it would be strange if more than n / 2 gentlemen lie on the ground together, isn't it?..) Help them to achieve this goal. -----Input----- The first line contains integer n (1 ≤ n ≤ 1000) — the number of friends. The next n lines have two integers w_{i}, h_{i} (1 ≤ w_{i}, h_{i} ≤ 1000) each, representing the size of the rectangle, corresponding to the i-th friend. -----Output----- Print a single integer equal to the minimum possible area of the photo containing all friends if no more than n / 2 of them can lie on the ground. -----Examples----- Input 3 10 1 20 2 30 3 Output 180 Input 3 3 1 2 2 4 3 Output 21 Input 1 5 10 Output 50 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Today is Chef's birthday. His mom has surprised him with truly fruity gifts: 2 fruit baskets. The first basket contains N apples, and the second one contains M oranges. Chef likes apples and oranges very much but he likes them equally, and therefore, wants to have the minimum possible difference between the number of apples and oranges he has. To do so, he can purchase 1 apple or 1 orange by paying exactly 1 gold coin (that's some expensive fruit, eh?). Chef can purchase fruits at most K times (as he has only K gold coins in his pocket) to make the difference the minimum possible. Our little Chef is busy in celebrating his birthday to the fullest, and therefore, he has handed this job to his best friend — you. Can you help him by finding the minimum possible difference he can achieve between the number of apples and orange he owns? -----Input----- The first line of input contains a single integer T denoting the number of test cases. The first and only line of each test case contains 3 space separated integers — N, M and K — denoting the number of apples, number of oranges, and number of gold coins our little Chef has. -----Output----- For each test case, output the minimum possible difference between the number of apples and oranges that Chef can achieve. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N, M, K ≤ 100 -----Example-----Input 3 3 4 1 5 2 1 3 4 3 Output 0 2 0 -----Explanation----- - Test 1: Chef will buy 1 apple by paying 1 gold coin and will have equal number of apples and oranges. - Test 2: Chef will buy 1 orange by paying 1 gold coin and will have 5 apples and 3 oranges. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it! Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour s_{i}, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland. For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3. But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer m_{i} and a lowercase letter c_{i}, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan. -----Input----- The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland. The second line contains n lowercase English letters s_1s_2... s_{n} as a string — the initial colours of paper pieces on the garland. The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has. The next q lines describe one plan each: the i-th among them contains an integer m_{i} (1 ≤ m_{i} ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter c_{i} — Koyomi's possible favourite colour. -----Output----- Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it. -----Examples----- Input 6 koyomi 3 1 o 4 o 4 m Output 3 6 5 Input 15 yamatonadeshiko 10 1 a 2 a 3 a 4 a 5 a 1 b 2 b 3 b 4 b 5 b Output 3 4 5 7 8 1 2 3 4 5 Input 10 aaaaaaaaaa 2 10 b 10 z Output 10 10 -----Note----- In the first sample, there are three plans: In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable; In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6; In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train? -----Input----- The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train. The second line contains n integers p_{i} (1 ≤ p_{i} ≤ n, p_{i} ≠ p_{j} if i ≠ j) — the sequence of the numbers of the cars in the train. -----Output----- Print a single integer — the minimum number of actions needed to sort the railway cars. -----Examples----- Input 5 4 1 2 5 3 Output 2 Input 4 4 1 3 2 Output 2 -----Note----- In the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter. [Image] Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time. Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game? You have to determine the winner of the game for all initial positions of the marbles. -----Input----- The first line of input contains two integers n and m (2 ≤ n ≤ 100, $1 \leq m \leq \frac{n(n - 1)}{2}$). The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≤ v, u ≤ n, v ≠ u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic. -----Output----- Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise. -----Examples----- Input 4 4 1 2 b 1 3 a 2 4 c 3 4 b Output BAAA ABAA BBBA BBBB Input 5 8 5 3 h 1 2 c 3 1 c 3 2 r 5 1 r 4 3 z 5 4 r 5 2 h Output BABBB BBBBB AABBB AAABA AAAAB -----Note----- Here's the graph in the first sample test case: [Image] Here's the graph in the second sample test case: [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows: [Image] The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times. Please output the maximum number of cake cells that the cakeminator can eat. -----Input----- The first line contains two integers r and c (2 ≤ r, c ≤ 10), denoting the number of rows and the number of columns of the cake. The next r lines each contains c characters — the j-th character of the i-th line denotes the content of the cell at row i and column j, and is either one of these: '.' character denotes a cake cell with no evil strawberry; 'S' character denotes a cake cell with an evil strawberry. -----Output----- Output the maximum number of cake cells that the cakeminator can eat. -----Examples----- Input 3 4 S... .... ..S. Output 8 -----Note----- For the first example, one possible way to eat the maximum number of cake cells is as follows (perform 3 eats). [Image] [Image] [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Take 2 strings `s1` and `s2` including only letters from `a`to `z`. Return a new **sorted** string, the longest possible, containing distinct letters, - each taken only once - coming from s1 or s2. # Examples: ``` a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy" a = "abcdefghijklmnopqrstuvwxyz" longest(a, a) -> "abcdefghijklmnopqrstuvwxyz" ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes. From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k ≥ 0) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2k - 1 into one box of side length 2k, or as in the following figure: <image> Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes. Input The first line of input contains an integer n (1 ≤ n ≤ 105), the number of different sizes of boxes Emuskald has. Each of following n lines contains two integers ki and ai (0 ≤ ki ≤ 109, 1 ≤ ai ≤ 109), which means that Emuskald has ai boxes with side length 2ki. It is guaranteed that all of ki are distinct. Output Output a single integer p, such that the smallest magical box that can contain all of Emuskald’s boxes has side length 2p. Examples Input 2 0 3 1 5 Output 3 Input 1 0 4 Output 1 Input 2 1 10 2 2 Output 3 Note Picture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture. In the second test case, we can put all four small boxes into a box with side 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. Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities. To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a_1, a_2, ..., a_{k}. Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another n - k cities, and, of course, flour delivery should be paid — for every kilometer of path between storage and bakery Masha should pay 1 ruble. Formally, Masha will pay x roubles, if she will open the bakery in some city b (a_{i} ≠ b for every 1 ≤ i ≤ k) and choose a storage in some city s (s = a_{j} for some 1 ≤ j ≤ k) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used). Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount. -----Input----- The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 0 ≤ k ≤ n) — the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then m lines follow. Each of them contains three integers u, v and l (1 ≤ u, v ≤ n, 1 ≤ l ≤ 10^9, u ≠ v) meaning that there is a road between cities u and v of length of l kilometers . If k > 0, then the last line of the input contains k distinct integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ n) — the number of cities having flour storage located in. If k = 0 then this line is not presented in the input. -----Output----- Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the n cities, print - 1 in the only line. -----Examples----- Input 5 4 2 1 2 5 1 2 3 2 3 4 1 4 10 1 5 Output 3 Input 3 1 1 1 2 3 3 Output -1 -----Note----- [Image] Image illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task You are given a function that should insert an asterisk (`*`) between every pair of **even digits** in the given input, and return it as a string. If the input is a sequence, concat the elements first as a string. ## Input The input can be an integer, a string of digits or a sequence containing integers only. ## Output Return a string. ## Examples ``` 5312708 --> "531270*8" "0000" --> "0*0*0*0" [1, 4, 64] --> "14*6*4" ``` Have fun! Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k = 2, the pair of integers x = 5 and y = 3 is k-interesting, because their binary representation x=101 and y=011 differs exactly in two bits. Vasya wants to know how many pairs of indexes (i, j) are in his sequence so that i < j and the pair of integers a_{i} and a_{j} is k-interesting. Your task is to help Vasya and determine this number. -----Input----- The first line contains two integers n and k (2 ≤ n ≤ 10^5, 0 ≤ k ≤ 14) — the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ. The second line contains the sequence a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^4), which Vasya has. -----Output----- Print the number of pairs (i, j) so that i < j and the pair of integers a_{i} and a_{j} is k-interesting. -----Examples----- Input 4 1 0 3 2 1 Output 4 Input 6 0 200 100 100 100 200 200 Output 6 -----Note----- In the first test there are 4 k-interesting pairs: (1, 3), (1, 4), (2, 3), (2, 4). In the second test k = 0. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs: (1, 5), (1, 6), (2, 3), (2, 4), (3, 4), (5, 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. Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city v_{i} to city u_{i} (and from u_{i} to v_{i}), and it costs w_{i} coins to use this route. Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is a_{i} coins. You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). Formally, for every $i \in [ 1, n ]$ you have to calculate $\operatorname{min}_{j = 1} 2 d(i, j) + a_{j}$, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large. -----Input----- The first line contains two integers n and m (2 ≤ n ≤ 2·10^5, 1 ≤ m ≤ 2·10^5). Then m lines follow, i-th contains three integers v_{i}, u_{i} and w_{i} (1 ≤ v_{i}, u_{i} ≤ n, v_{i} ≠ u_{i}, 1 ≤ w_{i} ≤ 10^12) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a_1, a_2, ... a_{k} (1 ≤ a_{i} ≤ 10^12) — price to attend the concert in i-th city. -----Output----- Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i). -----Examples----- Input 4 2 1 2 4 2 3 7 6 20 1 25 Output 6 14 1 25 Input 3 3 1 2 1 2 3 1 1 3 1 30 10 20 Output 12 10 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. Little C loves number «3» very much. He loves all things about it. Now he is playing a game on a chessboard of size n × m. The cell in the x-th row and in the y-th column is called (x,y). Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between which is exactly 3. The Manhattan distance between two cells (x_i,y_i) and (x_j,y_j) is defined as |x_i-x_j|+|y_i-y_j|. He want to place as many chessmen as possible on the chessboard. Please help him find the maximum number of chessmen he can place. Input A single line contains two integers n and m (1 ≤ n,m ≤ 10^9) — the number of rows and the number of columns of the chessboard. Output Print one integer — the maximum number of chessmen Little C can place. Examples Input 2 2 Output 0 Input 3 3 Output 8 Note In the first example, the Manhattan distance between any two cells is smaller than 3, so the answer is 0. In the second example, a possible solution is (1,1)(3,2), (1,2)(3,3), (2,1)(1,3), (3,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. After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has 6 strings and an infinite number of frets numbered from 1. Fretting the fret number j on the i-th string produces the note a_{i} + j. Tayuya wants to play a melody of n notes. Each note can be played on different string-fret combination. The easiness of performance depends on the difference between the maximal and the minimal indices of used frets. The less this difference is, the easier it is to perform the technique. Please determine the minimal possible difference. For example, if a = [1, 1, 2, 2, 3, 3], and the sequence of notes is 4, 11, 11, 12, 12, 13, 13 (corresponding to the second example), we can play the first note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7, as shown on the picture. <image> Input The first line contains 6 space-separated numbers a_{1}, a_{2}, ..., a_{6} (1 ≤ a_{i} ≤ 10^{9}) which describe the Tayuya's strings. The second line contains the only integer n (1 ≤ n ≤ 100 000) standing for the number of notes in the melody. The third line consists of n integers b_{1}, b_{2}, ..., b_{n} (1 ≤ b_{i} ≤ 10^{9}), separated by space. They describe the notes to be played. It's guaranteed that b_i > a_j for all 1≤ i≤ n and 1≤ j≤ 6, in other words, you can play each note on any string. Output Print the minimal possible difference of the maximal and the minimal indices of used frets. Examples Input 1 4 100 10 30 5 6 101 104 105 110 130 200 Output 0 Input 1 1 2 2 3 3 7 13 4 11 12 11 13 12 Output 7 Note In the first sample test it is optimal to play the first note on the first string, the second note on the second string, the third note on the sixth string, the fourth note on the fourth string, the fifth note on the fifth string, and the sixth note on the third string. In this case the 100-th fret is used each time, so the difference is 100 - 100 = 0. <image> In the second test it's optimal, for example, to play the second note on the first string, and all the other notes on the sixth string. Then the maximal fret will be 10, the minimal one will be 3, and the answer is 10 - 3 = 7. <image> Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Takahashi has a string S of length N consisting of digits from 0 through 9. He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten. Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers. Compute this count to help Takahashi. -----Constraints----- - 1 \leq N \leq 2 \times 10^5 - S consists of digits. - |S| = N - 2 \leq P \leq 10000 - P is a prime number. -----Input----- Input is given from Standard Input in the following format: N P S -----Output----- Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten. -----Sample Input----- 4 3 3543 -----Sample Output----- 6 Here S = 3543. There are ten non-empty (contiguous) substrings of S: - 3: divisible by 3. - 35: not divisible by 3. - 354: divisible by 3. - 3543: divisible by 3. - 5: not divisible by 3. - 54: divisible by 3. - 543: divisible by 3. - 4: not divisible by 3. - 43: not divisible by 3. - 3: divisible by 3. Six of these are divisible by 3, so print 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 are n employees working in company "X" (let's number them from 1 to n for convenience). Initially the employees didn't have any relationships among each other. On each of m next days one of the following events took place: either employee y became the boss of employee x (at that, employee x didn't have a boss before); or employee x gets a packet of documents and signs them; then he gives the packet to his boss. The boss signs the documents and gives them to his boss and so on (the last person to sign the documents sends them to the archive); or comes a request of type "determine whether employee x signs certain documents". Your task is to write a program that will, given the events, answer the queries of the described type. At that, it is guaranteed that throughout the whole working time the company didn't have cyclic dependencies. -----Input----- The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of employees and the number of events. Each of the next m lines contains the description of one event (the events are given in the chronological order). The first number of the line determines the type of event t (1 ≤ t ≤ 3). If t = 1, then next follow two integers x and y (1 ≤ x, y ≤ n) — numbers of the company employees. It is guaranteed that employee x doesn't have the boss currently. If t = 2, then next follow integer x (1 ≤ x ≤ n) — the number of the employee who got a document packet. If t = 3, then next follow two integers x and i (1 ≤ x ≤ n; 1 ≤ i ≤ [number of packets that have already been given]) — the employee and the number of the document packet for which you need to find out information. The document packets are numbered started from 1 in the chronological order. It is guaranteed that the input has at least one query of the third type. -----Output----- For each query of the third type print "YES" if the employee signed the document package and "NO" otherwise. Print all the words without the quotes. -----Examples----- Input 4 9 1 4 3 2 4 3 3 1 1 2 3 2 2 3 1 2 1 3 1 2 2 3 1 3 Output YES NO YES Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given four integers $n$, $B$, $x$ and $y$. You should build a sequence $a_0, a_1, a_2, \dots, a_n$ where $a_0 = 0$ and for each $i \ge 1$ you can choose: either $a_i = a_{i - 1} + x$ or $a_i = a_{i - 1} - y$. Your goal is to build such a sequence $a$ that $a_i \le B$ for all $i$ and $\sum\limits_{i=0}^{n}{a_i}$ is maximum possible. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Next $t$ cases follow. The first and only line of each test case contains four integers $n$, $B$, $x$ and $y$ ($1 \le n \le 2 \cdot 10^5$; $1 \le B, x, y \le 10^9$). It's guaranteed that the total sum of $n$ doesn't exceed $2 \cdot 10^5$. -----Output----- For each test case, print one integer — the maximum possible $\sum\limits_{i=0}^{n}{a_i}$. -----Examples----- Input 3 5 100 1 30 7 1000000000 1000000000 1000000000 4 1 7 3 Output 15 4000000000 -10 -----Note----- In the first test case, the optimal sequence $a$ is $[0, 1, 2, 3, 4, 5]$. In the second test case, the optimal sequence $a$ is $[0, 10^9, 0, 10^9, 0, 10^9, 0, 10^9]$. In the third test case, the optimal sequence $a$ is $[0, -3, -6, 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. Память компьютера состоит из n ячеек, которые выстроены в ряд. Пронумеруем ячейки от 1 до n слева направо. Про каждую ячейку известно, свободна она или принадлежит какому-либо процессу (в таком случае известен процесс, которому она принадлежит). Для каждого процесса известно, что принадлежащие ему ячейки занимают в памяти непрерывный участок. С помощью операций вида «переписать данные из занятой ячейки в свободную, а занятую теперь считать свободной» требуется расположить все принадлежащие процессам ячейки в начале памяти компьютера. Другими словами, любая свободная ячейка должна располагаться правее (иметь больший номер) любой занятой. Вам необходимо найти минимальное количество операций переписывания данных из одной ячейки в другую, с помощью которых можно достичь описанных условий. Допустимо, что относительный порядок ячеек в памяти для каждого из процессов изменится после дефрагментации, но относительный порядок самих процессов должен остаться без изменений. Это значит, что если все ячейки, принадлежащие процессу i, находились в памяти раньше всех ячеек процесса j, то и после перемещений это условие должно выполняться. Считайте, что номера всех процессов уникальны, хотя бы одна ячейка памяти занята каким-либо процессом. -----Входные данные----- В первой строке входных данных записано число n (1 ≤ n ≤ 200 000) — количество ячеек в памяти компьютера. Во второй строке входных данных следуют n целых чисел a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n), где a_{i} равно либо 0 (это означает, что i-я ячейка памяти свободна), либо номеру процесса, которому принадлежит i-я ячейка памяти. Гарантируется, что хотя бы одно значение a_{i} не равно 0. Процессы пронумерованы целыми числами от 1 до n в произвольном порядке. При этом процессы не обязательно пронумерованы последовательными числами. -----Выходные данные----- Выведите одно целое число — минимальное количество операций, которое нужно сделать для дефрагментации памяти. -----Примеры----- Входные данные 4 0 2 2 1 Выходные данные 2 Входные данные 8 0 8 8 8 0 4 4 2 Выходные данные 4 -----Примечание----- В первом тестовом примере достаточно двух операций: Переписать данные из третьей ячейки в первую. После этого память компьютера примет вид: 2 2 0 1. Переписать данные из четвертой ячейки в третью. После этого память компьютера примет вид: 2 2 1 0. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Create a function `close_compare` that accepts 3 parameters: `a`, `b`, and an optional `margin`. The function should return whether `a` is lower than, close to, or higher than `b`. `a` is "close to" `b` if `margin` is higher than or equal to the difference between `a` and `b`. When `a` is lower than `b`, return `-1`. When `a` is higher than `b`, return `1`. When `a` is close to `b`, return `0`. If `margin` is not given, treat it as zero. Example: if `a = 3`, `b = 5` and the `margin = 3`, since `a` and `b` are no more than 3 apart, `close_compare` should return `0`. Otherwise, if instead `margin = 0`, `a` is lower than `b` and `close_compare` should return `-1`. Assume: `margin >= 0` Tip: Some languages have a way to make arguments optional. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving. More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed. <image> It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located. You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size. Input The first line contains two integers n and m (2 ≤ n, m ≤ 106). Output Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator). Examples Input 3 4 Output 2 Input 3 3 Output 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.