question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code. The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code. How many different PIN codes can he set this way? Both the lucky number and the PIN code may begin with a 0. Constraints * 4 \leq N \leq 30000 * S is a string of length N consisting of digits. Input Input is given from Standard Input in the following format: N S Output Print the number of different PIN codes Takahashi can set. Examples Input 4 0224 Output 3 Input 6 123123 Output 17 Input 19 3141592653589793238 Output 329 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Bob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can transmit from 0 to x2 water units per second. If y1 water units per second flow through the first tap and y2 water units per second flow through the second tap, then the resulting bath water temperature will be: <image> Bob wants to open both taps so that the bath water temperature was not less than t0. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible. Determine how much each tap should be opened so that Bob was pleased with the result in the end. Input You are given five integers t1, t2, x1, x2 and t0 (1 ≤ t1 ≤ t0 ≤ t2 ≤ 106, 1 ≤ x1, x2 ≤ 106). Output Print two space-separated integers y1 and y2 (0 ≤ y1 ≤ x1, 0 ≤ y2 ≤ x2). Examples Input 10 70 100 100 25 Output 99 33 Input 300 500 1000 1000 300 Output 1000 0 Input 143 456 110 117 273 Output 76 54 Note In the second sample the hot water tap shouldn't be opened, but the cold water tap should be opened at full capacity in order to fill the bath in the quickest way possible. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Arkady and his friends love playing checkers on an $n \times n$ field. The rows and the columns of the field are enumerated from $1$ to $n$. The friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friends one set of candies per each cell of the field: the set of candies for cell $(i, j)$ will have exactly $(i^2 + j^2)$ candies of unique type. There are $m$ friends who deserve the present. How many of these $n \times n$ sets of candies can be split equally into $m$ parts without cutting a candy into pieces? Note that each set has to be split independently since the types of candies in different sets are different. -----Input----- The only line contains two integers $n$ and $m$ ($1 \le n \le 10^9$, $1 \le m \le 1000$) — the size of the field and the number of parts to split the sets into. -----Output----- Print a single integer — the number of sets that can be split equally. -----Examples----- Input 3 3 Output 1 Input 6 5 Output 13 Input 1000000000 1 Output 1000000000000000000 -----Note----- In the first example, only the set for cell $(3, 3)$ can be split equally ($3^2 + 3^2 = 18$, which is divisible by $m=3$). In the second example, the sets for the following cells can be divided equally: $(1, 2)$ and $(2, 1)$, since $1^2 + 2^2 = 5$, which is divisible by $5$; $(1, 3)$ and $(3, 1)$; $(2, 4)$ and $(4, 2)$; $(2, 6)$ and $(6, 2)$; $(3, 4)$ and $(4, 3)$; $(3, 6)$ and $(6, 3)$; $(5, 5)$. In the third example, sets in all cells can be divided equally, since $m = 1$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a rectangular matrix of size $n \times m$ consisting of integers from $1$ to $2 \cdot 10^5$. In one move, you can: choose any element of the matrix and change its value to any integer between $1$ and $n \cdot m$, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some $j$ ($1 \le j \le m$) and set $a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}$ simultaneously. [Image] Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: $\left. \begin{array}{|c c c c|} \hline 1 & {2} & {\ldots} & {m} \\{m + 1} & {m + 2} & {\ldots} & {2m} \\{\vdots} & {\vdots} & {\ddots} & {\vdots} \\{(n - 1) m + 1} & {(n - 1) m + 2} & {\ldots} & {nm} \\ \hline \end{array} \right.$ In other words, the goal is to obtain the matrix, where $a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$ (i.e. $a_{i, j} = (i - 1) \cdot m + j$) with the minimum number of moves performed. -----Input----- The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5$) — the size of the matrix. The next $n$ lines contain $m$ integers each. The number at the line $i$ and position $j$ is $a_{i, j}$ ($1 \le a_{i, j} \le 2 \cdot 10^5$). -----Output----- Print one integer — the minimum number of moves required to obtain the matrix, where $a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$ ($a_{i, j} = (i - 1)m + j$). -----Examples----- Input 3 3 3 2 1 1 2 3 4 5 6 Output 6 Input 4 3 1 2 3 4 5 6 7 8 9 10 11 12 Output 0 Input 3 4 1 6 3 4 5 10 7 8 9 2 11 12 Output 2 -----Note----- In the first example, you can set $a_{1, 1} := 7, a_{1, 2} := 8$ and $a_{1, 3} := 9$ then shift the first, the second and the third columns cyclically, so the answer is $6$. It can be shown that you cannot achieve a better answer. In the second example, the matrix is already good so the answer is $0$. In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is $2$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. Aditi recently discovered a new magic trick. First, she gives you an integer N and asks you to think an integer between 1 and N. Then she gives you a bundle of cards each having a sorted list (in ascending order) of some distinct integers written on it. The integers in all the lists are between 1 and N. Note that the same integer may appear in more than one card. Now, she shows you these cards one by one and asks whether the number you thought is written on the card or not. After that, she immediately tells you the integer you had thought of. Seeing you thoroughly puzzled, she explains that she can apply the trick so fast because she is just adding the first integer written on the cards that contain the integer you had thought of, and then gives the sum as the answer. She calls a bundle interesting if when the bundle is lexicographically sorted, no two consecutive cards have any number in common. Now she challenges you to find out the minimum number of cards she will need for making an interesting bundle such that the magic trick will work every time. ------ Input ------ The first line of the input contains an integer T denoting the number of test cases. Each test case contains a line with a single integer N. ------ Output ------ For each test case, output a line containing a single integer denoting the minimum number of cards required. ------ Constraints ------ 1 ≤ T ≤ 10^{5} 1 ≤ N ≤ 10^{18} ------ Sub tasks ------ Subtask #1: 1 ≤ T ≤ 10, 1 ≤ N ≤ 10 (5 points) Subtask #2: 1 ≤ T ≤ 100, 1 ≤ N ≤ 1000 (10 points) Subtask #3: Original Constraints (85 points) ----- Sample Input 1 ------ 2 1 4 ----- Sample Output 1 ------ 1 3 ----- explanation 1 ------ In example 1, only 1 card containing {1} will work. In example 2, make 3 cards containing {1,4}, {2} and {3,4}. Assume you thought of 1, then you will select the 1st card {1,4}, then she will correctly figure out the integer you thought being 1. Assume you thought of 2, then you will select the 2nd card {2}, then she will correctly figure out the integer you thought being 2. Assume you thought of 3, then you will select the 3rd card {3,4}, then she will correctly figure out the integer you thought being 3. Assume you thought of 4, then you will select 1st card {1,4} and 3rd card {3,4}, then she will calculate the sum of the first integers of the two card 1 + 3 = 4, and she will answer it. Thus her trick will work well in every case. And we can check it easily that the cards are sorted in lexicographical order and two consecutive cards have no common integers. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an undirected connected weighted graph consisting of $n$ vertices and $m$ edges. Let's denote the length of the shortest path from vertex $1$ to vertex $i$ as $d_i$. You have to erase some edges of the graph so that at most $k$ edges remain. Let's call a vertex $i$ good if there still exists a path from $1$ to $i$ with length $d_i$ after erasing the edges. Your goal is to erase the edges in such a way that the number of good vertices is maximized. -----Input----- The first line contains three integers $n$, $m$ and $k$ ($2 \le n \le 3 \cdot 10^5$, $1 \le m \le 3 \cdot 10^5$, $n - 1 \le m$, $0 \le k \le m$) — the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively. Then $m$ lines follow, each containing three integers $x$, $y$, $w$ ($1 \le x, y \le n$, $x \ne y$, $1 \le w \le 10^9$), denoting an edge connecting vertices $x$ and $y$ and having weight $w$. The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices). -----Output----- In the first line print $e$ — the number of edges that should remain in the graph ($0 \le e \le k$). In the second line print $e$ distinct integers from $1$ to $m$ — the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible. -----Examples----- Input 3 3 2 1 2 1 3 2 1 1 3 3 Output 2 1 2 Input 4 5 2 4 1 8 2 4 1 2 1 3 3 4 9 3 1 5 Output 2 3 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey. At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively. Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness. Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours. Input The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order. The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. Output Output one of the four words without inverted commas: * «forward» — if Peter could see such sequences only on the way from A to B; * «backward» — if Peter could see such sequences on the way from B to A; * «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A; * «fantasy» — if Peter could not see such sequences. Examples Input atob a b Output forward Input aaacaaa aca aa Output both Note It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_{i} < a_{j}. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3). You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2]. After each query you have to determine whether the number of inversions is odd or even. -----Input----- The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — the elements of the permutation. These integers are pairwise distinct. The third line contains one integer m (1 ≤ m ≤ 2·10^5) — the number of queries to process. Then m lines follow, i-th line containing two integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) denoting that i-th query is to reverse a segment [l_{i}, r_{i}] of the permutation. All queries are performed one after another. -----Output----- Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise. -----Examples----- Input 3 1 2 3 2 1 2 2 3 Output odd even Input 4 1 2 4 3 4 1 1 1 4 1 4 2 3 Output odd odd odd even -----Note----- The first example: after the first query a = [2, 1, 3], inversion: (2, 1); after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2). The second example: a = [1, 2, 4, 3], inversion: (4, 3); a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3); a = [1, 2, 4, 3], inversion: (4, 3); a = [1, 4, 2, 3], inversions: (3, 2), (4, 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. Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm. Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows: [Image] You have to write a program that allows you to determine what number will be in the cell with index x (1 ≤ x ≤ n) after Dima's algorithm finishes. -----Input----- The first line contains two integers n and q (1 ≤ n ≤ 10^18, 1 ≤ q ≤ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer. Next q lines contain integers x_{i} (1 ≤ x_{i} ≤ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes. -----Output----- For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes. -----Examples----- Input 4 3 2 3 4 Output 3 2 4 Input 13 4 10 5 4 8 Output 13 3 8 9 -----Note----- The first example is shown in the picture. In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 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. A and B are preparing themselves for programming contests. The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n. Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them. As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days. Input The first line contains integer n (1 ≤ n ≤ 105) — the number of rooms in the University. The next n - 1 lines describe the corridors. The i-th of these lines (1 ≤ i ≤ n - 1) contains two integers ai and bi (1 ≤ ai, bi ≤ n), showing that the i-th corridor connects rooms ai and bi. The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Next m lines describe the queries. The j-th of these lines (1 ≤ j ≤ m) contains two integers xj and yj (1 ≤ xj, yj ≤ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj. Output In the i-th (1 ≤ i ≤ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day. Examples Input 4 1 2 1 3 2 4 1 2 3 Output 1 Input 4 1 2 2 3 2 4 2 1 2 1 3 Output 0 2 Note in the first sample there is only one room at the same distance from rooms number 2 and 3 — room number 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. # How much is the fish! (- Scooter ) The ocean is full of colorful fishes. We as programmers want to know the hexadecimal value of these fishes. ## Task Take all hexadecimal valid characters (a,b,c,d,e,f) of the given name and XOR them. Return the result as an integer. ## Input The input is always a string, which can contain spaces, upper and lower case letters but no digits. ## Example `fisHex("redlionfish") -> e,d,f -> XOR -> 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. This is an easy version of the problem. The only difference between an easy and a hard version is in the number of queries. Polycarp grew a tree from $n$ vertices. We remind you that a tree of $n$ vertices is an undirected connected graph of $n$ vertices and $n-1$ edges that does not contain cycles. He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set). In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other). For example, for a tree below sets $\{3, 2, 5\}$, $\{1, 5, 4\}$, $\{1, 4\}$ are passable, and $\{1, 3, 5\}$, $\{1, 2, 3, 4, 5\}$ are not. Polycarp asks you to answer $q$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable. -----Input----- The first line of input contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — number of vertices. Following $n - 1$ lines a description of the tree.. Each line contains two integers $u$ and $v$ ($1 \le u, v \le n$, $u \ne v$) — indices of vertices connected by an edge. Following line contains single integer $q$ ($1 \le q \le 5$) — number of queries. The following $2 \cdot q$ lines contain descriptions of sets. The first line of the description contains an integer $k$ ($1 \le k \le n$) — the size of the set. The second line of the description contains $k$ of distinct integers $p_1, p_2, \dots, p_k$ ($1 \le p_i \le n$) — indices of the vertices of the set. It is guaranteed that the sum of $k$ values for all queries does not exceed $2 \cdot 10^5$. -----Output----- Output $q$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer). -----Examples----- Input 5 1 2 2 3 2 4 4 5 5 3 3 2 5 5 1 2 3 4 5 2 1 4 3 1 3 5 3 1 5 4 Output YES NO YES NO YES Input 5 1 2 3 2 2 4 5 2 4 2 3 1 3 3 4 5 3 2 3 5 1 1 Output YES NO YES YES -----Note----- None Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer t_{i}. The bigger this value is, the better the friendship is. No two friends have the same value t_{i}. Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time. The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them — those with biggest t_{i}. Your task is to handle queries of two types: "1 id" — Friend id becomes online. It's guaranteed that he wasn't online before. "2 id" — Check whether friend id is displayed by the system. Print "YES" or "NO" in a separate line. Are you able to help Limak and answer all queries of the second type? -----Input----- The first line contains three integers n, k and q (1 ≤ n, q ≤ 150 000, 1 ≤ k ≤ min(6, n)) — the number of friends, the maximum number of displayed online friends and the number of queries, respectively. The second line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 10^9) where t_{i} describes how good is Limak's relation with the i-th friend. The i-th of the following q lines contains two integers type_{i} and id_{i} (1 ≤ type_{i} ≤ 2, 1 ≤ id_{i} ≤ n) — the i-th query. If type_{i} = 1 then a friend id_{i} becomes online. If type_{i} = 2 then you should check whether a friend id_{i} is displayed. It's guaranteed that no two queries of the first type will have the same id_{i} becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (type_{i} = 2) so the output won't be empty. -----Output----- For each query of the second type print one line with the answer — "YES" (without quotes) if the given friend is displayed and "NO" (without quotes) otherwise. -----Examples----- Input 4 2 8 300 950 500 200 1 3 2 4 2 3 1 1 1 2 2 1 2 2 2 3 Output NO YES NO YES YES Input 6 3 9 50 20 51 17 99 24 1 3 1 4 1 5 1 2 2 4 2 2 1 1 2 4 2 3 Output NO YES NO YES -----Note----- In the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries: "1 3" — Friend 3 becomes online. "2 4" — We should check if friend 4 is displayed. He isn't even online and thus we print "NO". "2 3" — We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print "YES". "1 1" — Friend 1 becomes online. The system now displays both friend 1 and friend 3. "1 2" — Friend 2 becomes online. There are 3 friends online now but we were given k = 2 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (t_1 < t_2, t_3) so friend 1 won't be displayed "2 1" — Print "NO". "2 2" — Print "YES". "2 3" — Print "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. For a given sequence $A = \\{a_0, a_1, ... a_{n-1}\\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program: bubbleSort(A) cnt = 0 // the number of inversions for i = 0 to A.length-1 for j = A.length-1 downto i+1 if A[j] < A[j-1] swap(A[j], A[j-1]) cnt++ return cnt For the given sequence $A$, print the number of inversions of $A$. Note that you should not use the above program, which brings Time Limit Exceeded. Constraints * $ 1 \leq n \leq 200,000$ * $ 0 \leq a_i \leq 10^9$ * $a_i$ are all different Input In the first line, an integer $n$, the number of elements in $A$, is given. In the second line, the elements $a_i$ ($i = 0, 1, .. n-1$) are given separated by space characters. Examples Input 5 3 5 2 1 4 Output 6 Input 3 3 1 2 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are $n$ detachments on the surface, numbered from $1$ to $n$, the $i$-th detachment is placed in a point with coordinates $(x_i, y_i)$. All detachments are placed in different points. Brimstone should visit each detachment at least once. You can choose the detachment where Brimstone starts. To move from one detachment to another he should first choose one of four directions of movement (up, right, left or down) and then start moving with the constant speed of one unit interval in a second until he comes to a detachment. After he reaches an arbitrary detachment, he can repeat the same process. Each $t$ seconds an orbital strike covers the whole surface, so at that moment Brimstone should be in a point where some detachment is located. He can stay with any detachment as long as needed. Brimstone is a good commander, that's why he can create at most one detachment and place it in any empty point with integer coordinates he wants before his trip. Keep in mind that Brimstone will need to visit this detachment, too. Help Brimstone and find such minimal $t$ that it is possible to check each detachment. If there is no such $t$ report about it. -----Input----- The first line contains a single integer $n$ $(2 \le n \le 1000)$ — the number of detachments. In each of the next $n$ lines there is a pair of integers $x_i$, $y_i$ $(|x_i|, |y_i| \le 10^9)$ — the coordinates of $i$-th detachment. It is guaranteed that all points are different. -----Output----- Output such minimal integer $t$ that it is possible to check all the detachments adding at most one new detachment. If there is no such $t$, print $-1$. -----Examples----- Input 4 100 0 0 100 -100 0 0 -100 Output 100 Input 7 0 2 1 0 -3 0 0 -2 -1 -1 -1 -3 -2 -3 Output -1 Input 5 0 0 0 -1 3 0 -2 0 -2 1 Output 2 Input 5 0 0 2 0 0 -1 -2 0 -2 1 Output 2 -----Note----- In the first test it is possible to place a detachment in $(0, 0)$, so that it is possible to check all the detachments for $t = 100$. It can be proven that it is impossible to check all detachments for $t < 100$; thus the answer is $100$. In the second test, there is no such $t$ that it is possible to check all detachments, even with adding at most one new detachment, so the answer is $-1$. In the third test, it is possible to place a detachment in $(1, 0)$, so that Brimstone can check all the detachments for $t = 2$. It can be proven that it is the minimal such $t$. In the fourth test, there is no need to add any detachments, because the answer will not get better ($t = 2$). It can be proven that it is the minimal such $t$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an array $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. You want to split it into exactly $k$ non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the elements of a given array. Each of the $n$ elements of the array $a$ must belong to exactly one of the $k$ subsegments. Let's see some examples of dividing the array of length $5$ into $3$ subsegments (not necessarily with odd sums): $[1, 2, 3, 4, 5]$ is the initial array, then all possible ways to divide it into $3$ non-empty non-intersecting subsegments are described below: $[1], [2], [3, 4, 5]$; $[1], [2, 3], [4, 5]$; $[1], [2, 3, 4], [5]$; $[1, 2], [3], [4, 5]$; $[1, 2], [3, 4], [5]$; $[1, 2, 3], [4], [5]$. Of course, it can be impossible to divide the initial array into exactly $k$ subsegments in such a way that each of them will have odd sum of elements. In this case print "NO". Otherwise, print "YES" and any possible division of the array. See the output format for the detailed explanation. You have to answer $q$ independent queries. -----Input----- The first line contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries. Then $q$ queries follow. The first line of the query contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the number of elements in the array and the number of subsegments, respectively. The second line of the query contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the $i$-th element of $a$. It is guaranteed that the sum of $n$ over all queries does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$). -----Output----- For each query, print the answer to it. If it is impossible to divide the initial array into exactly $k$ subsegments in such a way that each of them will have odd sum of elements, print "NO" in the first line. Otherwise, print "YES" in the first line and any possible division of the array in the second line. The division can be represented as $k$ integers $r_1$, $r_2$, ..., $r_k$ such that $1 \le r_1 < r_2 < \dots < r_k = n$, where $r_j$ is the right border of the $j$-th segment (the index of the last element that belongs to the $j$-th segment), so the array is divided into subsegments $[1; r_1], [r_1 + 1; r_2], [r_2 + 1, r_3], \dots, [r_{k - 1} + 1, n]$. Note that $r_k$ is always $n$ but you should print it anyway. -----Example----- Input 3 5 3 7 18 3 14 1 5 4 1 2 3 4 5 6 2 1 2 8 4 10 2 Output YES 1 3 5 NO NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that: 1. First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals <image>. The operation x mod y means that we take the remainder of the division of number x by number y. 2. Then we write the contents of the array s to the array a. Element number i (1 ≤ i ≤ n) of the array s becomes the i-th element of the array a (ai = si). You task is to find array a after exactly k described operations are applied. Input The first line contains two space-separated integers n and k (1 ≤ n ≤ 2000, 0 ≤ k ≤ 109). The next line contains n space-separated integers a1, a2, ..., an — elements of the array a (0 ≤ ai ≤ 109). Output Print n integers — elements of the array a after the operations are applied to it. Print the elements in the order of increasing of their indexes in the array a. Separate the printed numbers by spaces. Examples Input 3 1 1 2 3 Output 1 3 6 Input 5 0 3 14 15 92 6 Output 3 14 15 92 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've just entered a programming contest and have a chance to win a million dollars. This is the last question you have to solve, so your victory (and your vacation) depend on it. Can you guess the function just by looking at the test cases? There are two numerical inputs and one numerical output. Goodluck! hint: go here Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You will be given an array of strings. The words in the array should mesh together where one or more letters at the end of one word will have the same letters (in the same order) as the next word in the array. But, there are times when all the words won't mesh. Examples of meshed words: "apply" and "plywood" "apple" and "each" "behemoth" and "mother" Examples of words that don't mesh: "apply" and "playground" "apple" and "peggy" "behemoth" and "mathematics" If all the words in the given array mesh together, then your code should return the meshed letters in a string. You won't know how many letters the meshed words have in common, but it will be at least one. If all the words don't mesh together, then your code should return `"failed to mesh"`. Input: An array of strings. There will always be at least two words in the input array. Output: Either a string of letters that mesh the words together or the string `"failed to mesh"`. ## Examples #1: ``` ["allow", "lowering", "ringmaster", "terror"] --> "lowringter" ``` because: * the letters `"low"` in the first two words mesh together * the letters `"ring"` in the second and third word mesh together * the letters `"ter"` in the third and fourth words mesh together. #2: ``` ["kingdom", "dominator", "notorious", "usual", "allegory"] --> "failed to mesh" ``` Although the words `"dominator"` and `"notorious"` share letters in the same order, the last letters of the first word don't mesh with the first letters of the second word. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 balance scale tips to the left if L>R, where L is the total weight of the masses on the left pan and R is the total weight of the masses on the right pan. Similarly, it balances if L=R, and tips to the right if L<R. Takahashi placed a mass of weight A and a mass of weight B on the left pan of a balance scale, and placed a mass of weight C and a mass of weight D on the right pan. Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right. -----Constraints----- - 1\leq A,B,C,D \leq 10 - All input values are integers. -----Input----- Input is given from Standard Input in the following format: A B C D -----Output----- Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right. -----Sample Input----- 3 8 7 1 -----Sample Output----- Left The total weight of the masses on the left pan is 11, and the total weight of the masses on the right pan is 8. Since 11>8, we should print Left. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser. Last evening Roma started to play poker. He decided to spend no more than k virtual bourles — he will stop immediately if the number of his loses exceeds the number of his wins by k. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by k. Next morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won k bourles or he lost. The sequence written by Roma is a string s consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met: * In the end the absolute difference between the number of wins and loses is equal to k; * There is no hand such that the absolute difference before this hand was equal to k. Help Roma to restore any such sequence. Input The first line contains two numbers n (the length of Roma's sequence) and k (1 ≤ n, k ≤ 1000). The second line contains the sequence s consisting of characters W, L, D and ?. There are exactly n characters in this sequence. Output If there is no valid sequence that can be obtained from s by replacing all ? characters by W, L or D, print NO. Otherwise print this sequence. If there are multiple answers, print any of them. Examples Input 3 2 L?? Output LDL Input 3 1 W?? Output NO Input 20 5 ?LLLLLWWWWW????????? Output WLLLLLWWWWWWWWLWLWDW Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon. The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous. Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: * climb one area up; * climb one area down; * jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon. The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on. The level is considered completed if the ninja manages to get out of the canyon. After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. Input The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. Output Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). Examples Input 7 3 ---X--X -X--XX- Output YES Input 6 2 --X-X- X--XX- Output NO Note In the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Gru has not been in the limelight for a long time and is, therefore, planning something particularly nefarious. Frustrated by his minions' incapability which has kept him away from the limelight, he has built a transmogrifier — a machine which mutates minions. Each minion has an intrinsic characteristic value (similar to our DNA), which is an integer. The transmogrifier adds an integer K to each of the minions' characteristic value. Gru knows that if the new characteristic value of a minion is divisible by 7, then it will have Wolverine-like mutations. Given the initial characteristic integers of N minions, all of which are then transmogrified, find out how many of them become Wolverine-like. -----Input Format:----- The first line contains one integer, T, which is the number of test cases. Each test case is then described in two lines. The first line contains two integers N and K, as described in the statement. The next line contains N integers, which denote the initial characteristic values for the minions. -----Output Format:----- For each testcase, output one integer in a new line, which is the number of Wolverine-like minions after the transmogrification. -----Constraints:----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 100 - 1 ≤ K ≤ 100 - All initial characteristic values lie between 1 and 105, both inclusive. -----Example----- Input: 1 5 10 2 4 1 35 1 Output: 1 -----Explanation:----- After transmogrification, the characteristic values become {12,14,11,45,11}, out of which only 14 is divisible by 7. So only the second minion becomes Wolverine-like. Read the inputs from stdin solve the problem and write the answer to stdout (do 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. A loves sweets, but recently his wife has told him to go on a diet. One day, when Mr. A went out from his home to the city hall, his wife recommended that he go by bicycle. There, Mr. A reluctantly went out on a bicycle, but Mr. A, who likes sweets, came up with the idea of ​​stopping by a cake shop on the way to eat cake. If you ride a bicycle, calories are consumed according to the mileage, but if you eat cake, you will consume that much calories. The net calories burned is the calories burned on the bike minus the calories burned by eating the cake. Therefore, the net calories burned may be less than zero. If you buy a cake at a cake shop, Mr. A will eat all the cake on the spot. Mr. A does not stop at all cake shops, but when he passes through the point where the cake shop exists, he always stops and buys and eats one cake. However, it's really tempting to pass in front of the same cake shop many times, so each cake shop should only be visited once. In addition, you may stop by the cake shop after passing the destination city hall, and then return to the city hall to finish your work, and you may visit as many times as you like except the cake shop. Enter the map information from Mr. A's home to the city hall, a list of calories of cakes that can be eaten at the cake shop on the way, and the calories burned by traveling a unit distance, from leaving home to entering the city hall. Create a program that outputs the minimum net calories burned. The map shows Mr. A's home and city hall, a cake shop and a landmark building. The input data representing the map contains a line consisting of a symbol representing the two points and the distance between them, when there is a road connecting Mr. A's home, city hall, cake shop and each point of the landmark. For example, if the distance between the 5th cake shop and the 3rd landmark is 10, the input data will contain a line similar to the following: C5 L3 10 In this way, cake shops are represented by C, and landmarks are represented by L in front of the number. Also, Mr. A's home is represented by H and the city hall is represented by D. If the input data is given two points and the distance between them, advance between the two points in either direction. For example, in the example above, you can go from a cake shop to a landmark and vice versa. In addition, you must be able to reach the city hall from your home. Other input data given are the number of cake shops m, the number of landmarks n, the calories burned per unit distance k, and the cakes that can be bought at each of the first cake shop to the mth cake shop. The total number of m data representing calories and distance data d. Input A sequence of multiple datasets is given as input. The end of the input is indicated by four 0 lines. Each dataset is given in the following format: m n k d c1 c2 ... cm s1 t1 e1 s2 t2 e2 :: sd td ed Number of cake shops m (1 ≤ m ≤ 6), number of landmarks n (1 ≤ n ≤ 100), calories burned per unit distance k (1 ≤ k ≤ 5), distance data on the first line The total number d (5 ≤ d ≤ 256) is given. The second line gives the calories ci (1 ≤ ci ≤ 100) of the cake you buy at each cake shop. The following d line is given the distance data si, ti, ei (1 ≤ ei ≤ 20) between the i-th two points. The number of datasets does not exceed 100. Output Outputs the minimum total calories burned on one line for each input dataset. Example Input 1 1 2 5 35 H L1 5 C1 D 6 C1 H 12 L1 D 10 C1 L1 20 2 1 4 6 100 70 H L1 5 C1 L1 12 C1 D 11 C2 L1 7 C2 D 15 L1 D 8 0 0 0 0 Output 1 -2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given an array $a$ of length $n$, find another array, $b$, of length $n$ such that: for each $i$ $(1 \le i \le n)$ $MEX(\{b_1$, $b_2$, $\ldots$, $b_i\})=a_i$. The $MEX$ of a set of integers is the smallest non-negative integer that doesn't belong to this set. If such array doesn't exist, determine this. -----Input----- The first line contains an integer $n$ ($1 \le n \le 10^5$) — the length of the array $a$. The second line contains $n$ integers $a_1$, $a_2$, $\ldots$, $a_n$ ($0 \le a_i \le i$) — the elements of the array $a$. It's guaranteed that $a_i \le a_{i+1}$ for $1\le i < n$. -----Output----- If there's no such array, print a single line containing $-1$. Otherwise, print a single line containing $n$ integers $b_1$, $b_2$, $\ldots$, $b_n$ ($0 \le b_i \le 10^6$) If there are multiple answers, print any. -----Examples----- Input 3 1 2 3 Output 0 1 2 Input 4 0 0 0 2 Output 1 3 4 0 Input 3 1 1 3 Output 0 2 1 -----Note----- In the second test case, other answers like $[1,1,1,0]$, for example, are valid. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vlad has $n$ friends, for each of whom he wants to buy one gift for the New Year. There are $m$ shops in the city, in each of which he can buy a gift for any of his friends. If the $j$-th friend ($1 \le j \le n$) receives a gift bought in the shop with the number $i$ ($1 \le i \le m$), then the friend receives $p_{ij}$ units of joy. The rectangular table $p_{ij}$ is given in the input. Vlad has time to visit at most $n-1$ shops (where $n$ is the number of friends). He chooses which shops he will visit and for which friends he will buy gifts in each of them. Let the $j$-th friend receive $a_j$ units of joy from Vlad's gift. Let's find the value $\alpha=\min\{a_1, a_2, \dots, a_n\}$. Vlad's goal is to buy gifts so that the value of $\alpha$ is as large as possible. In other words, Vlad wants to maximize the minimum of the joys of his friends. For example, let $m = 2$, $n = 2$. Let the joy from the gifts that we can buy in the first shop: $p_{11} = 1$, $p_{12}=2$, in the second shop: $p_{21} = 3$, $p_{22}=4$. Then it is enough for Vlad to go only to the second shop and buy a gift for the first friend, bringing joy $3$, and for the second — bringing joy $4$. In this case, the value $\alpha$ will be equal to $\min\{3, 4\} = 3$ Help Vlad choose gifts for his friends so that the value of $\alpha$ is as high as possible. Please note that each friend must receive one gift. Vlad can visit at most $n-1$ shops (where $n$ is the number of friends). In the shop, he can buy any number of gifts. -----Input----- The first line of the input contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. An empty line is written before each test case. Then there is a line containing integers $m$ and $n$ ($2 \le n$, $2 \le n \cdot m \le 10^5$) separated by a space — the number of shops and the number of friends, where $n \cdot m$ is the product of $n$ and $m$. Then $m$ lines follow, each containing $n$ numbers. The number in the $i$-th row of the $j$-th column $p_{ij}$ ($1 \le p_{ij} \le 10^9$) is the joy of the product intended for friend number $j$ in shop number $i$. It is guaranteed that the sum of the values $n \cdot m$ over all test cases in the test does not exceed $10^5$. -----Output----- Print $t$ lines, each line must contain the answer to the corresponding test case — the maximum possible value of $\alpha$, where $\alpha$ is the minimum of the joys from a gift for all of Vlad's friends. -----Examples----- Input 5 2 2 1 2 3 4 4 3 1 3 1 3 1 1 1 2 2 1 1 3 2 3 5 3 4 2 5 1 4 2 7 9 8 1 9 6 10 8 2 4 6 5 2 1 7 9 7 2 Output 3 2 4 8 2 -----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. An `non decreasing` number is one containing no two consecutive digits (left to right), whose the first is higer than the second. For example, 1235 is an non decreasing number, 1229 is too, but 123429 isn't. Write a function that finds the number of non decreasing numbers up to `10**N` (exclusive) where N is the input of your function. For example, if `N=3`, you have to count all non decreasing numbers from 0 to 999. You'll definitely need something smarter than brute force for large values of N! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission. Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k_1 knights with lightsabers of the first color, k_2 knights with lightsabers of the second color, ..., k_{m} knights with lightsabers of the m-th color. However, since the last time, she has learned that it is not always possible to select such an interval. Therefore, she decided to ask some Jedi Knights to go on an indefinite unpaid vacation leave near certain pits on Tatooine, if you know what I mean. Help Heidi decide what is the minimum number of Jedi Knights that need to be let go before she is able to select the desired interval from the subsequence of remaining knights. -----Input----- The first line of the input contains n (1 ≤ n ≤ 2·10^5) and m (1 ≤ m ≤ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains m integers k_1, k_2, ..., k_{m} (with $1 \leq \sum_{i = 1}^{m} k_{i} \leq n$) – the desired counts of Jedi Knights with lightsabers of each color from 1 to m. -----Output----- Output one number: the minimum number of Jedi Knights that need to be removed from the sequence so that, in what remains, there is an interval with the prescribed counts of lightsaber colors. If this is not possible, output - 1. -----Example----- Input 8 3 3 3 1 2 2 1 1 3 3 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. You are given sequence a_1, a_2, ..., a_{n} of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You should write a program which finds sum of the best subsequence. -----Input----- The first line contains integer number n (1 ≤ n ≤ 10^5). The second line contains n integer numbers a_1, a_2, ..., a_{n} ( - 10^4 ≤ a_{i} ≤ 10^4). The sequence contains at least one subsequence with odd sum. -----Output----- Print sum of resulting subseqeuence. -----Examples----- Input 4 -2 2 -3 1 Output 3 Input 3 2 -5 -3 Output -1 -----Note----- In the first example sum of the second and the fourth elements is 3. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Fox Ciel is playing a game with numbers now. Ciel has n positive integers: x_1, x_2, ..., x_{n}. She can do the following operation as many times as needed: select two different indexes i and j such that x_{i} > x_{j} hold, and then apply assignment x_{i} = x_{i} - x_{j}. The goal is to make the sum of all numbers as small as possible. Please help Ciel to find this minimal sum. -----Input----- The first line contains an integer n (2 ≤ n ≤ 100). Then the second line contains n integers: x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 100). -----Output----- Output a single integer — the required minimal sum. -----Examples----- Input 2 1 2 Output 2 Input 3 2 4 6 Output 6 Input 2 12 18 Output 12 Input 5 45 12 27 30 18 Output 15 -----Note----- In the first example the optimal way is to do the assignment: x_2 = x_2 - x_1. In the second example the optimal sequence of operations is: x_3 = x_3 - x_2, x_2 = x_2 - x_1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The magic sum of 3s is calculated on an array by summing up odd numbers which include the digit `3`. Write a function `magic_sum` which accepts an array of integers and returns the sum. *Example:* `[3, 12, 5, 8, 30, 13]` results in `16` (`3` + `13`) If the sum cannot be calculated, `0` should be returned. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of h_{i} identical blocks. For clarification see picture for the first sample. Limak will repeat the following operation till everything is destroyed. Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time. Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. -----Input----- The first line contains single integer n (1 ≤ n ≤ 10^5). The second line contains n space-separated integers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 10^9) — sizes of towers. -----Output----- Print the number of operations needed to destroy all towers. -----Examples----- Input 6 2 1 4 6 2 2 Output 3 Input 7 3 3 3 1 3 3 3 Output 2 -----Note----- The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. [Image] After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an integer sequence $1, 2, \dots, n$. You have to divide it into two sets $A$ and $B$ in such a way that each element belongs to exactly one set and $|sum(A) - sum(B)|$ is minimum possible. The value $|x|$ is the absolute value of $x$ and $sum(S)$ is the sum of elements of the set $S$. -----Input----- The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^9$). -----Output----- Print one integer — the minimum possible value of $|sum(A) - sum(B)|$ if you divide the initial sequence $1, 2, \dots, n$ into two sets $A$ and $B$. -----Examples----- Input 3 Output 0 Input 5 Output 1 Input 6 Output 1 -----Note----- Some (not all) possible answers to examples: In the first example you can divide the initial sequence into sets $A = \{1, 2\}$ and $B = \{3\}$ so the answer is $0$. In the second example you can divide the initial sequence into sets $A = \{1, 3, 4\}$ and $B = \{2, 5\}$ so the answer is $1$. In the third example you can divide the initial sequence into sets $A = \{1, 4, 5\}$ and $B = \{2, 3, 6\}$ so the answer is $1$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0. The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0. -----Input----- The first line of input contains two integers n and s (1 ≤ n ≤ 100, 1 ≤ s ≤ 1000) — the number of passengers and the number of the top floor respectively. The next n lines each contain two space-separated integers f_{i} and t_{i} (1 ≤ f_{i} ≤ s, 1 ≤ t_{i} ≤ 1000) — the floor and the time of arrival in seconds for the passenger number i. -----Output----- Print a single integer — the minimum amount of time in seconds needed to bring all the passengers to floor 0. -----Examples----- Input 3 7 2 1 3 8 5 2 Output 11 Input 5 10 2 77 3 33 8 21 9 12 10 64 Output 79 -----Note----- In the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done: 1. Move to floor 5: takes 2 seconds. 2. Pick up passenger 3. 3. Move to floor 3: takes 2 seconds. 4. Wait for passenger 2 to arrive: takes 4 seconds. 5. Pick up passenger 2. 6. Go to floor 2: takes 1 second. 7. Pick up passenger 1. 8. Go to floor 0: takes 2 seconds. This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In the wake of the npm's `left-pad` debacle, you decide to write a new super padding method that superceds the functionality of `left-pad`. Your version will provide the same functionality, but will additionally add right, and justified padding of string -- the `super_pad`. Your function `super_pad` should take three arguments: the string `string`, the width of the final string `width`, and a fill character `fill`. However, the fill character can be enriched with a format string resulting in different padding strategies. If `fill` begins with `'<'` the string is padded on the left with the remaining fill string and if `fill` begins with `'>'` the string is padded on the right. Finally, if `fill` begins with `'^'` the string is padded on the left and the right, where the left padding is always greater or equal to the right padding. The `fill` string can contain more than a single char, of course. Some examples to clarify the inner workings: - `super_pad("test", 10)` returns "      test" - `super_pad("test", 10, "x")` returns `"xxxxxxtest"` - `super_pad("test", 10, "xO")` returns `"xOxOxOtest"` - `super_pad("test", 10, "xO-")` returns `"xO-xO-test"` - `super_pad("some other test", 10, "nope")` returns `"other test"` - `super_pad("some other test", 10, "> ")` returns `"some other"` - `super_pad("test", 7, ">nope")` returns `"testnop"` - `super_pad("test", 7, "^more complex")` returns `"motestm"` - `super_pad("test", 7, "")` returns `"test"` The `super_pad` method always returns a string of length `width` if possible. We expect the `width` to be positive (including 0) and the fill could be also an empty string. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan. There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites <image>-th boy and <image>-th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever. Drazil wants to know whether he can use this plan to make all his friends become happy at some moment. Input The first line contains two integer n and m (1 ≤ n, m ≤ 100). The second line contains integer b (0 ≤ b ≤ n), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1, x2, ..., xb (0 ≤ xi < n), denoting the list of indices of happy boys. The third line conatins integer g (0 ≤ g ≤ m), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1, y2, ... , yg (0 ≤ yj < m), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends. Output If Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No". Examples Input 2 3 0 1 0 Output Yes Input 2 4 1 0 1 2 Output No Input 2 3 1 0 1 1 Output Yes Note By <image> we define the remainder of integer division of i by k. In first sample case: * On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day. * On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day. * On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day. * On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy. * On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner. For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner. -----Input----- The first line contains two integers: n and k (2 ≤ n ≤ 500, 2 ≤ k ≤ 10^12) — the number of people and the number of wins. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all a_{i} are distinct. -----Output----- Output a single integer — power of the winner. -----Examples----- Input 2 2 1 2 Output 2 Input 4 2 3 1 2 4 Output 3 Input 6 2 6 5 3 1 2 4 Output 6 Input 2 10000000000 2 1 Output 2 -----Note----- Games in the second sample: 3 plays with 1. 3 wins. 1 goes to the end of the line. 3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert a grams of sand into b grams of lead, the second one allows you to convert c grams of lead into d grams of gold and third one allows you to convert e grams of gold into f grams of sand. When Harry told his friends about these spells, Ron Weasley was amazed. After all, if they succeed in turning sand into lead, lead into gold, and then turning part of the gold into sand again and so on, then it will be possible to start with a small amount of sand and get huge amounts of gold! Even an infinite amount of gold! Hermione Granger, by contrast, was skeptical about that idea. She argues that according to the law of conservation of matter getting an infinite amount of matter, even using magic, is impossible. On the contrary, the amount of matter may even decrease during transformation, being converted to magical energy. Though Hermione's theory seems convincing, Ron won't believe her. As far as Ron is concerned, Hermione made up her law of conservation of matter to stop Harry and Ron wasting their time with this nonsense, and to make them go and do homework instead. That's why Ron has already collected a certain amount of sand for the experiments. A quarrel between the friends seems unavoidable... Help Harry to determine which one of his friends is right, and avoid the quarrel after all. To do this you have to figure out whether it is possible to get the amount of gold greater than any preassigned number from some finite amount of sand. Input The first line contains 6 integers a, b, c, d, e, f (0 ≤ a, b, c, d, e, f ≤ 1000). Output Print "Ron", if it is possible to get an infinitely large amount of gold having a certain finite amount of sand (and not having any gold and lead at all), i.e., Ron is right. Otherwise, print "Hermione". Examples Input 100 200 250 150 200 250 Output Ron Input 100 50 50 200 200 100 Output Hermione Input 100 10 200 20 300 30 Output Hermione Input 0 0 0 0 0 0 Output Hermione Input 1 1 0 1 1 1 Output Ron Input 1 0 1 2 1 2 Output Hermione Input 100 1 100 1 0 1 Output Ron Note Consider the first sample. Let's start with the 500 grams of sand. Apply the first spell 5 times and turn the sand into 1000 grams of lead. Then apply the second spell 4 times to get 600 grams of gold. Let’s take 400 grams from the resulting amount of gold turn them back into sand. We get 500 grams of sand and 200 grams of gold. If we apply the same operations to 500 grams of sand again, we can get extra 200 grams of gold every time. Thus, you can get 200, 400, 600 etc. grams of gold, i.e., starting with a finite amount of sand (500 grams), you can get the amount of gold which is greater than any preassigned number. In the forth sample it is impossible to get sand, or lead, or gold, applying the spells. In the fifth sample an infinitely large amount of gold can be obtained by using only the second spell, which allows you to receive 1 gram of gold out of nothing. Note that if such a second spell is available, then the first and the third one do not affect the answer at all. The seventh sample is more interesting. We can also start with a zero amount of sand there. With the aid of the third spell you can get sand out of nothing. We get 10000 grams of sand in this manner. Let's get 100 grams of lead using the first spell 100 times. Then make 1 gram of gold from them. We managed to receive 1 gram of gold, starting with a zero amount of sand! Clearly, in this manner you can get an infinitely large amount of gold. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sequences A and B consisting of non-negative integers. The lengths of both A and B are N, and the sums of the elements in A and B are equal. The i-th element in A is A_i, and the i-th element in B is B_i. Tozan and Gezan repeats the following sequence of operations: - If A and B are equal sequences, terminate the process. - Otherwise, first Tozan chooses a positive element in A and decrease it by 1. - Then, Gezan chooses a positive element in B and decrease it by 1. - Then, give one candy to Takahashi, their pet. Tozan wants the number of candies given to Takahashi until the process is terminated to be as large as possible, while Gezan wants it to be as small as possible. Find the number of candies given to Takahashi when both of them perform the operations optimally. -----Constraints----- - 1 \leq N \leq 2 × 10^5 - 0 \leq A_i,B_i \leq 10^9(1\leq i\leq N) - The sums of the elements in A and B are equal. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N A_1 B_1 : A_N B_N -----Output----- Print the number of candies given to Takahashi when both Tozan and Gezan perform the operations optimally. -----Sample Input----- 2 1 2 3 2 -----Sample Output----- 2 When both Tozan and Gezan perform the operations optimally, the process will proceed as follows: - Tozan decreases A_1 by 1. - Gezan decreases B_1 by 1. - One candy is given to Takahashi. - Tozan decreases A_2 by 1. - Gezan decreases B_1 by 1. - One candy is given to Takahashi. - As A and B are equal, the process is terminated. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Aoki is playing with a sequence of numbers a_{1}, a_{2}, ..., a_{N}. Every second, he performs the following operation : * Choose a positive integer k. For each element of the sequence v, Aoki may choose to replace v with its remainder when divided by k, or do nothing with v. The cost of this operation is 2^{k} (regardless of how many elements he changes). Aoki wants to turn the sequence into b_{1}, b_{2}, ..., b_{N} (the order of the elements is important). Determine if it is possible for Aoki to perform this task and if yes, find the minimum cost required. Constraints * 1 \leq N \leq 50 * 0 \leq a_{i}, b_{i} \leq 50 * All values in the input are integers. Input Input is given from Standard Input in the following format: N a_{1} a_{2} ... a_{N} b_{1} b_{2} ... b_{N} Output Print the minimum cost required to turn the original sequence into b_{1}, b_{2}, ..., b_{N}. If the task is impossible, output -1 instead. Examples Input 3 19 10 14 0 3 4 Output 160 Input 3 19 15 14 0 0 0 Output 2 Input 2 8 13 5 13 Output -1 Input 4 2 0 1 8 2 0 1 8 Output 0 Input 1 50 13 Output 137438953472 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Two players A and B have a list of $n$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty). Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $\{1, 2, 2, 3\}$ in a list and you decided to choose $2$ for the next turn, only a single instance of $2$ will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally. Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same. -----Input----- The first line of input contains an integer $n$ ($1 \le n \le 100\,000$) — the sizes of the list. The second line contains $n$ integers $a_i$ ($1 \le a_i \le 10^6$), describing the list of the player A, who starts the game. The third line contains $n$ integers $b_i$ ($1 \le b_i \le 10^6$), describing the list of the player B. -----Output----- Output the difference between A's score and B's score ($A-B$) if both of them are playing optimally. -----Examples----- Input 2 1 4 5 1 Output 0 Input 3 100 100 100 100 100 100 Output 0 Input 2 2 1 5 6 Output -3 -----Note----- In the first example, the game could have gone as follows: A removes $5$ from B's list. B removes $4$ from A's list. A takes his $1$. B takes his $1$. Hence, A's score is $1$, B's score is $1$ and difference is $0$. There is also another optimal way of playing: A removes $5$ from B's list. B removes $4$ from A's list. A removes $1$ from B's list. B removes $1$ from A's list. The difference in the scores is still $0$. In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be $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. There are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his office exactly ai times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home. Doctor plans to go home after receiving k animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out. Input The first line of input data contains two space-separated integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 1014). In the second line are given space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator). Output If the doctor will overall carry out less than k examinations, print a single number "-1" (without quotes). Otherwise, print the sequence of numbers — number of animals in the order in which they stand in the queue. Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted. Examples Input 3 3 1 2 1 Output 2 Input 4 10 3 3 2 1 Output -1 Input 7 10 1 3 3 1 2 3 1 Output 6 2 3 Note In the first sample test: * Before examination: {1, 2, 3} * After the first examination: {2, 3} * After the second examination: {3, 2} * After the third examination: {2} In the second sample test: * Before examination: {1, 2, 3, 4, 5, 6, 7} * After the first examination: {2, 3, 4, 5, 6, 7} * After the second examination: {3, 4, 5, 6, 7, 2} * After the third examination: {4, 5, 6, 7, 2, 3} * After the fourth examination: {5, 6, 7, 2, 3} * After the fifth examination: {6, 7, 2, 3, 5} * After the sixth examination: {7, 2, 3, 5, 6} * After the seventh examination: {2, 3, 5, 6} * After the eighth examination: {3, 5, 6, 2} * After the ninth examination: {5, 6, 2, 3} * After the tenth examination: {6, 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. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types: * replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4); * swap any pair of digits in string a. Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task. Input The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105. Output Print on the single line the single number — the minimum number of operations needed to convert string a into string b. Examples Input 47 74 Output 1 Input 774 744 Output 1 Input 777 444 Output 3 Note In the first sample it is enough simply to swap the first and the second digit. In the second sample we should replace the second digit with its opposite. In the third number we should replace all three digits with their opposites. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya has a string $s$ of length $n$. He decides to make the following modification to the string: Pick an integer $k$, ($1 \leq k \leq n$). For $i$ from $1$ to $n-k+1$, reverse the substring $s[i:i+k-1]$ of $s$. For example, if string $s$ is qwer and $k = 2$, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length $2$) weqr (after reversing the second substring of length $2$) werq (after reversing the last substring of length $2$) Hence, the resulting string after modifying $s$ with $k = 2$ is werq. Vasya wants to choose a $k$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $k$. Among all such $k$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help. A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds: $a$ is a prefix of $b$, but $a \ne b$; in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 5000$). The description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 5000$) — the length of the string $s$. The second line of each test case contains the string $s$ of $n$ lowercase latin letters. It is guaranteed that the sum of $n$ over all test cases does not exceed $5000$. -----Output----- For each testcase output two lines: In the first line output the lexicographically smallest string $s'$ achievable after the above-mentioned modification. In the second line output the appropriate value of $k$ ($1 \leq k \leq n$) that you chose for performing the modification. If there are multiple values of $k$ that give the lexicographically smallest string, output the smallest value of $k$ among them. -----Example----- Input 6 4 abab 6 qwerty 5 aaaaa 6 alaska 9 lfpbavjsm 1 p Output abab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 -----Note----- In the first testcase of the first sample, the string modification results for the sample abab are as follows : for $k = 1$ : abab for $k = 2$ : baba for $k = 3$ : abab for $k = 4$ : baba The lexicographically smallest string achievable through modification is abab for $k = 1$ and $3$. Smallest value of $k$ needed to achieve is hence $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. Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array. In case of multiple appearances to choose from, take the last occurence of the unpaired character. **Notes:** * A wide range of characters is used, and some of them may not render properly in your browser. * Your solution should be linear in terms of string length to pass the last test. ## Examples ``` "Hello World" --> ["H", "e", " ", "W", "r", "l", "d"] "Codewars" --> ["C", "o", "d", "e", "w", "a", "r", "s"] "woowee" --> [] "wwoooowweeee" --> [] "racecar" --> ["e"] "Mamma" --> ["M"] "Mama" --> ["M", "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. The concept of "[smooth number](https://en.wikipedia.org/wiki/Smooth_number)" is applied to all those numbers whose prime factors are lesser than or equal to `7`: `60` is a smooth number (`2 * 2 * 3 * 5`), `111` is not (`3 * 37`). More specifically, smooth numbers are classified by their highest prime factor and your are tasked with writing a `isSmooth`/`is_smooth` function that returns a string with this classification as it follows: * 2-smooth numbers should be all defined as a `"power of 2"`, as they are merely that; * 3-smooth numbers are to return a result of `"3-smooth"`; * 5-smooth numbers will be labelled as `"Hamming number"`s (incidentally, you might appreciate [this nice kata on them](https://www.codewars.com/kata/hamming-numbers)); * 7-smooth numbers are classified as `"humble numbers"`s; * for all the other numbers, just return `non-smooth`. Examples: ```python is_smooth(16) == "power of 2" is_smooth(36) == "3-smooth" is_smooth(60) == "Hamming number" is_smooth(98) == "humble number" is_smooth(111) == "non-smooth" ``` The provided input `n` is always going to be a positive number `> 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. We guessed a permutation $p$ consisting of $n$ integers. The permutation of length $n$ is the array of length $n$ where each element from $1$ to $n$ appears exactly once. This permutation is a secret for you. For each position $r$ from $2$ to $n$ we chose some other index $l$ ($l < r$) and gave you the segment $p_l, p_{l + 1}, \dots, p_r$ in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly $n-1$ segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is $p=[3, 1, 4, 6, 2, 5]$ then the possible given set of segments can be: $[2, 5, 6]$ $[4, 6]$ $[1, 3, 4]$ $[1, 3]$ $[1, 2, 4, 6]$ Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($2 \le n \le 200$) — the length of the permutation. The next $n-1$ lines describe given segments. The $i$-th line contains the description of the $i$-th segment. The line starts with the integer $k_i$ ($2 \le k_i \le n$) — the length of the $i$-th segment. Then $k_i$ integers follow. All integers in a line are distinct, sorted in ascending order, between $1$ and $n$, inclusive. It is guaranteed that the required $p$ exists for each test case. It is also guaranteed that the sum of $n$ over all test cases does not exceed $200$ ($\sum n \le 200$). -----Output----- For each test case, print the answer: $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). -----Example----- Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have to create a function named reverseIt. Write your function so that in the case a string or a number is passed in as the data , you will return the data in reverse order. If the data is any other type, return it as it is. Examples of inputs and subsequent outputs: ``` "Hello" -> "olleH" "314159" -> "951413" [1,2,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. You have a multiset containing several integers. Initially, it contains $a_1$ elements equal to $1$, $a_2$ elements equal to $2$, ..., $a_n$ elements equal to $n$. You may apply two types of operations: choose two integers $l$ and $r$ ($l \le r$), then remove one occurrence of $l$, one occurrence of $l + 1$, ..., one occurrence of $r$ from the multiset. This operation can be applied only if each number from $l$ to $r$ occurs at least once in the multiset; choose two integers $i$ and $x$ ($x \ge 1$), then remove $x$ occurrences of $i$ from the multiset. This operation can be applied only if the multiset contains at least $x$ occurrences of $i$. What is the minimum number of operations required to delete all elements from the multiset? -----Input----- The first line contains one integer $n$ ($1 \le n \le 5000$). The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$). -----Output----- Print one integer — the minimum number of operations required to delete all elements from the multiset. -----Examples----- Input 4 1 4 1 1 Output 2 Input 5 1 0 1 0 1 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. You're given two arrays $a[1 \dots n]$ and $b[1 \dots n]$, both of the same length $n$. In order to perform a push operation, you have to choose three integers $l, r, k$ satisfying $1 \le l \le r \le n$ and $k > 0$. Then, you will add $k$ to elements $a_l, a_{l+1}, \ldots, a_r$. For example, if $a = [3, 7, 1, 4, 1, 2]$ and you choose $(l = 3, r = 5, k = 2)$, the array $a$ will become $[3, 7, \underline{3, 6, 3}, 2]$. You can do this operation at most once. Can you make array $a$ equal to array $b$? (We consider that $a = b$ if and only if, for every $1 \le i \le n$, $a_i = b_i$) -----Input----- The first line contains a single integer $t$ ($1 \le t \le 20$) — the number of test cases in the input. The first line of each test case contains a single integer $n$ ($1 \le n \le 100\ 000$) — the number of elements in each array. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 1000$). The third line of each test case contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le 1000$). It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$. -----Output----- For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). -----Example----- Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO -----Note----- The first test case is described in the statement: we can perform a push operation with parameters $(l=3, r=5, k=2)$ to make $a$ equal to $b$. In the second test case, we would need at least two operations to make $a$ equal to $b$. In the third test case, arrays $a$ and $b$ are already equal. In the fourth test case, it's impossible to make $a$ equal to $b$, because the integer $k$ has to be positive. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence. Here, an sequence b is a good sequence when the following condition holds true: * For each element x in b, the value x occurs exactly x times in b. For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not. Find the minimum number of elements that needs to be removed so that a will be a good sequence. Constraints * 1 \leq N \leq 10^5 * a_i is an integer. * 1 \leq a_i \leq 10^9 Input Input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output Print the minimum number of elements that needs to be removed so that a will be a good sequence. Examples Input 4 3 3 3 3 Output 1 Input 5 2 4 1 4 2 Output 2 Input 6 1 2 2 3 3 3 Output 0 Input 1 1000000000 Output 1 Input 8 2 7 1 8 2 8 1 8 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. Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is h_{i}. Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence). You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary. As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (10^9 + 7). -----Input----- The first line contains integer n (1 ≤ n ≤ 1 000 000) — the number of boards in Vasily's fence. The second line contains n space-separated numbers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 10^9), where h_{i} equals the height of the i-th board to the left. -----Output----- Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good. -----Examples----- Input 2 1 1 Output 0 Input 3 3 4 2 Output 13 -----Note----- From the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good. All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part): [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. Philip's just turned four and he wants to know how old he will be in various years in the future such as 2090 or 3044. His parents can't keep up calculating this so they've begged you to help them out by writing a programme that can answer Philip's endless questions. Your task is to write a function that takes two parameters: the year of birth and the year to count years in relation to. As Philip is getting more curious every day he may soon want to know how many years it was until he would be born, so your function needs to work with both dates in the future and in the past. Provide output in this format: For dates in the future: "You are ... year(s) old." For dates in the past: "You will be born in ... year(s)." If the year of birth equals the year requested return: "You were born this very year!" "..." are to be replaced by the number, followed and proceeded by a single space. Mind that you need to account for both "year" and "years", depending on the result. Good Luck! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a string $s$, consisting of $n$ lowercase Latin letters. A substring of string $s$ is a continuous segment of letters from $s$. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it. Let's call some string of length $n$ diverse if and only if there is no letter to appear strictly more than $\frac n 2$ times. For example, strings "abc" and "iltlml" are diverse and strings "aab" and "zz" are not. Your task is to find any diverse substring of string $s$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 1000$) — the length of string $s$. The second line is the string $s$, consisting of exactly $n$ lowercase Latin letters. -----Output----- Print "NO" if there is no diverse substring in the string $s$. Otherwise the first line should contain "YES". The second line should contain any diverse substring of string $s$. -----Examples----- Input 10 codeforces Output YES code Input 5 aaaaa Output NO -----Note----- The first example has lots of correct answers. Please, restrain yourself from asking if some specific answer is correct for some specific test or not, these questions always lead to "No comments" answer. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Not so long ago as a result of combat operations the main Berland place of interest — the magic clock — was damaged. The cannon's balls made several holes in the clock, that's why the residents are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane, where the origin corresponds to the clock center. The clock was painted two colors as is shown in the picture: <image> The picture shows only the central part of the clock. This coloring naturally extends to infinity. The balls can be taken to be points on the plane. Your task is to find the color of the area, damaged by the given ball. All the points located on the border of one of the areas have to be considered painted black. Input The first and single line contains two integers x and y — the coordinates of the hole made in the clock by the ball. Each of the numbers x and y has an absolute value that does not exceed 1000. Output Find the required color. All the points between which and the origin of coordinates the distance is integral-value are painted black. Examples Input -2 1 Output white Input 2 1 Output black Input 4 3 Output black Read the inputs from stdin solve the problem and write the answer to stdout (do 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 slimes lining up in a row. Initially, the i-th slime from the left has a size of a_i. Taro is trying to combine all the slimes into a larger slime. He will perform the following operation repeatedly until there is only one slime: * Choose two adjacent slimes, and combine them into a new slime. The new slime has a size of x + y, where x and y are the sizes of the slimes before combining them. Here, a cost of x + y is incurred. The positional relationship of the slimes does not change while combining slimes. Find the minimum possible total cost incurred. Constraints * All values in input are integers. * 2 \leq N \leq 400 * 1 \leq a_i \leq 10^9 Input Input is given from Standard Input in the following format: N a_1 a_2 \ldots a_N Output Print the minimum possible total cost incurred. Examples Input 4 10 20 30 40 Output 190 Input 5 10 10 10 10 10 Output 120 Input 3 1000000000 1000000000 1000000000 Output 5000000000 Input 6 7 6 8 6 1 1 Output 68 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other. Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word_1<3word_2<3 ... word_{n}<3. Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message. Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 10^5. The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 10^5. A text message can contain only small English letters, digits and signs more and less. -----Output----- In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise. -----Examples----- Input 3 i love you <3i<3love<23you<3 Output yes Input 7 i am not main in the family <3i<>3am<3the<3<main<3in<3the<3><3family<3 Output no -----Note----- Please note that Dima got a good old kick in the pants for the second sample from the statement. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice! Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index b_{i} from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index b_{i}, then this person acted like that: he pointed at the person with index (b_{i} + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y); if j ≥ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player b_{i} on the current turn, then he had drunk a glass of juice; the turn went to person number (b_{i} + 1) mod n. The person who was pointed on the last turn did not make any actions. The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him. You can assume that in any scenario, there is enough juice for everybody. -----Input----- The first line contains a single integer n (4 ≤ n ≤ 2000) — the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns. -----Output----- Print a single integer — the number of glasses of juice Vasya could have drunk if he had played optimally well. -----Examples----- Input 4 abbba Output 1 Input 4 abbab Output 0 -----Note----- In both samples Vasya has got two turns — 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined $E = \sum_{i = 1}^{n}(a_{i} - b_{i})^{2}$. You have to perform exactly k_1 operations on array A and exactly k_2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1. Output the minimum possible value of error after k_1 operations on array A and k_2 operations on array B have been performed. -----Input----- The first line contains three space-separated integers n (1 ≤ n ≤ 10^3), k_1 and k_2 (0 ≤ k_1 + k_2 ≤ 10^3, k_1 and k_2 are non-negative) — size of arrays and number of operations to perform on A and B respectively. Second line contains n space separated integers a_1, a_2, ..., a_{n} ( - 10^6 ≤ a_{i} ≤ 10^6) — array A. Third line contains n space separated integers b_1, b_2, ..., b_{n} ( - 10^6 ≤ b_{i} ≤ 10^6)— array B. -----Output----- Output a single integer — the minimum possible value of $\sum_{i = 1}^{n}(a_{i} - b_{i})^{2}$ after doing exactly k_1 operations on array A and exactly k_2 operations on array B. -----Examples----- Input 2 0 0 1 2 2 3 Output 2 Input 2 1 0 1 2 2 2 Output 0 Input 2 5 7 3 4 14 4 Output 1 -----Note----- In the first sample case, we cannot perform any operations on A or B. Therefore the minimum possible error E = (1 - 2)^2 + (2 - 3)^2 = 2. In the second sample case, we are required to perform exactly one operation on A. In order to minimize error, we increment the first element of A by 1. Now, A = [2, 2]. The error is now E = (2 - 2)^2 + (2 - 2)^2 = 0. This is the minimum possible error obtainable. In the third sample case, we can increase the first element of A to 8, using the all of the 5 moves available to us. Also, the first element of B can be reduced to 8 using the 6 of the 7 available moves. Now A = [8, 4] and B = [8, 4]. The error is now E = (8 - 8)^2 + (4 - 4)^2 = 0, but we are still left with 1 move for array B. Increasing the second element of B to 5 using the left move, we get B = [8, 5] and E = (8 - 8)^2 + (4 - 5)^2 = 1. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Write a simple function that takes polar coordinates (an angle in degrees and a radius) and returns the equivalent cartesian coordinates (rouded to 10 places). ``` For example: coordinates(90,1) => (0.0, 1.0) coordinates(45, 1) => (0.7071067812, 0.7071067812) ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A binary tree of n nodes is given. Nodes of the tree are numbered from 1 to n and the root is the node 1. Each node can have no child, only one left child, only one right child, or both children. For convenience, let's denote l_u and r_u as the left and the right child of the node u respectively, l_u = 0 if u does not have the left child, and r_u = 0 if the node u does not have the right child. Each node has a string label, initially is a single character c_u. Let's define the string representation of the binary tree as the concatenation of the labels of the nodes in the in-order. Formally, let f(u) be the string representation of the tree rooted at the node u. f(u) is defined as follows: $$$ f(u) = \begin{cases} <empty string>, & if u = 0; \\\ f(l_u) + c_u + f(r_u) & otherwise, \end{cases} where +$$$ denotes the string concatenation operation. This way, the string representation of the tree is f(1). For each node, we can duplicate its label at most once, that is, assign c_u with c_u + c_u, but only if u is the root of the tree, or if its parent also has its label duplicated. You are given the tree and an integer k. What is the lexicographically smallest string representation of the tree, if we can duplicate labels of at most k nodes? A string a is lexicographically smaller than a string b if and only if one of the following holds: * a is a prefix of b, but a ≠ b; * in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains a string c of n lower-case English letters, where c_i is the initial label of the node i for 1 ≤ i ≤ n. Note that the given string c is not the initial string representation of the tree. The i-th of the next n lines contains two integers l_i and r_i (0 ≤ l_i, r_i ≤ n). If the node i does not have the left child, l_i = 0, and if the node i does not have the right child, r_i = 0. It is guaranteed that the given input forms a binary tree, rooted at 1. Output Print a single line, containing the lexicographically smallest string representation of the tree if at most k nodes have their labels duplicated. Examples Input 4 3 abab 2 3 0 0 0 4 0 0 Output baaaab Input 8 2 kadracyn 2 5 3 4 0 0 0 0 6 8 0 7 0 0 0 0 Output daarkkcyan Input 8 3 kdaracyn 2 5 0 3 0 4 0 0 6 8 0 7 0 0 0 0 Output darkcyan Note The images below present the tree for the examples. The number in each node is the node number, while the subscripted letter is its label. To the right is the string representation of the tree, with each letter having the same color as the corresponding node. Here is the tree for the first example. Here we duplicated the labels of nodes 1 and 3. We should not duplicate the label of node 2 because it would give us the string "bbaaab", which is lexicographically greater than "baaaab". <image> In the second example, we can duplicate the labels of nodes 1 and 2. Note that only duplicating the label of the root will produce a worse result than the initial string. <image> In the third example, we should not duplicate any character at all. Even though we would want to duplicate the label of the node 3, by duplicating it we must also duplicate the label of the node 2, which produces a worse result. <image> There is no way to produce string "darkkcyan" from a tree with the initial string representation "darkcyan" :(. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode). procedure bubbleSortGraph() build a graph G with n vertices and 0 edges repeat swapped = false for i = 1 to n - 1 inclusive do: if a[i] > a[i + 1] then add an undirected edge in G between a[i] and a[i + 1] swap( a[i], a[i + 1] ) swapped = true end if end for until not swapped /* repeat the algorithm as long as swapped value is true. */ end procedure For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph. Input The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). Output Output a single integer — the answer to the problem. Examples Input 3 3 1 2 Output 2 Note Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [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. There is an infinitely large pond, which we consider as a number line. In this pond, there are N lotuses floating at coordinates 0, 1, 2, ..., N-2 and N-1. On the lotus at coordinate i, an integer s_i is written. You are standing on the lotus at coordinate 0. You will play a game that proceeds as follows: - 1. Choose positive integers A and B. Your score is initially 0. - 2. Let x be your current coordinate, and y = x+A. The lotus at coordinate x disappears, and you move to coordinate y. - If y = N-1, the game ends. - If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y. - If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends. - 3. Let x be your current coordinate, and y = x-B. The lotus at coordinate x disappears, and you move to coordinate y. - If y = N-1, the game ends. - If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y. - If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends. - 4. Go back to step 2. You want to end the game with as high a score as possible. What is the score obtained by the optimal choice of A and B? -----Constraints----- - 3 \leq N \leq 10^5 - -10^9 \leq s_i \leq 10^9 - s_0=s_{N-1}=0 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N s_0 s_1 ...... s_{N-1} -----Output----- Print the score obtained by the optimal choice of A and B. -----Sample Input----- 5 0 2 5 1 0 -----Sample Output----- 3 If you choose A = 3 and B = 2, the game proceeds as follows: - Move to coordinate 0 + 3 = 3. Your score increases by s_3 = 1. - Move to coordinate 3 - 2 = 1. Your score increases by s_1 = 2. - Move to coordinate 1 + 3 = 4. The game ends with a score of 3. There is no way to end the game with a score of 4 or higher, so the answer is 3. Note that you cannot land the lotus at coordinate 2 without drowning later. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars. Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles. In other words, you should find two non-negative integers x and y such that Vasya can buy x bottles of Ber-Cola and y Bars bars and x·a + y·b = n or tell that it's impossible. -----Input----- First line contains single integer n (1 ≤ n ≤ 10 000 000) — amount of money, that Vasya has. Second line contains single integer a (1 ≤ a ≤ 10 000 000) — cost of one bottle of Ber-Cola. Third line contains single integer b (1 ≤ b ≤ 10 000 000) — cost of one Bars bar. -----Output----- If Vasya can't buy Bars and Ber-Cola in such a way to spend exactly n burles print «NO» (without quotes). Otherwise in first line print «YES» (without quotes). In second line print two non-negative integers x and y — number of bottles of Ber-Cola and number of Bars bars Vasya should buy in order to spend exactly n burles, i.e. x·a + y·b = n. If there are multiple answers print any of them. Any of numbers x and y can be equal 0. -----Examples----- Input 7 2 3 Output YES 2 1 Input 100 25 10 Output YES 0 10 Input 15 4 8 Output NO Input 9960594 2551 2557 Output YES 1951 1949 -----Note----- In first example Vasya can buy two bottles of Ber-Cola and one Bars bar. He will spend exactly 2·2 + 1·3 = 7 burles. In second example Vasya can spend exactly n burles multiple ways: buy two bottles of Ber-Cola and five Bars bars; buy four bottles of Ber-Cola and don't buy Bars bars; don't buy Ber-Cola and buy 10 Bars bars. In third example it's impossible to but Ber-Cola and Bars bars in order to spend exactly n burles. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. I decided to do bowling as a recreation of the class. Create a program that inputs the pitching information for each participant and outputs the grade information in descending order of score. If there is a tie, output in ascending order of student ID number. However, it is assumed that the number of participants is 3 or more and 40 or less, and one game is thrown per person. Bowling is a sport in which the player rolls the ball toward 10 pins arranged in an equilateral triangle with the vertices facing the player and knocks down the pins. The case where all the players fall in the first pitch is called a strike, and only that pitch advances to the next frame. If it is not a strike, leave the remaining pins and make a second pitch. A spare is when all the pitches have fallen on the second pitch. After the second pitch, proceed to the next frame. One game consists of 10 frames, and each of the 1st to 9th frames can be pitched twice. At the beginning of each frame, all 10 pins are upright. In the 10th frame, if there is a strike or a spare, a total of 3 pitches will be thrown, otherwise 2 pitches will be made and the game will end. Score example 1 <image> Score example 2 (when the maximum score is 300 points) <image> How to calculate the score * If there are no spares or strikes in each frame, the number of pins defeated in two pitches will be the score for that frame. (4th and 8th frames of score example 1) * If you give a spare, in addition to the number of defeated 10 points, the number of defeated pins in the next pitch will be added to the score of this frame. (Relationship between the 1st frame and the 2nd frame of the score example 1) In the 1st frame of the score example 1, 20 points including 10 points (points) defeated by 1 throw of the 2nd frame will be scored. The calculation method is the same for the third frame. * If you strike, the number of pins you defeated in the next two pitches will be added to the number of defeated 10 points. (Relationship between the 2nd frame and the 3rd frame of score example 1) Of course, there may be a strike during the following 2 throws. (Relationship between the 5th frame and the 6th and 7th frames of score example 1) * If you give a spare or strike only in the 10th frame, the total number of pins you have thrown and defeated will be added as the score in the 10th frame. * The total score of each frame is the score of one game, and the maximum score is 300 points. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: m score1 score2 :: scorem The number of participants m (3 ≤ m ≤ 40) is given in the first line, and the i-th participant information scorei is given in the following m lines. Each participant information is given in the following format, one line at a time. id s1 s2 ... sn The student ID number id (0 ≤ id ≤ 9999) is given first, followed by the number of fall pins of the jth throw sj (0 ≤ sj ≤ 10). It is assumed that the total number of pitches n is 12 or more and 21 or less, and the number of pins required for score calculation is given in just proportion. Output For each input dataset, the student ID number and score are output in descending order of score (if there is a tie, the student ID number is in ascending order). Please separate your student ID number and score with one space and output them on one line. Example Input 3 1010 6 3 10 7 1 0 7 9 1 10 6 2 4 3 9 1 9 0 1200 5 3 9 1 7 1 0 0 8 1 10 10 4 3 9 1 8 2 9 1101 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 3321 8 2 10 9 1 7 0 10 10 10 0 8 10 10 10 10 3332 5 0 10 9 1 4 1 9 0 10 10 7 1 5 2 8 1 3335 10 10 10 10 10 10 10 10 10 10 10 10 3340 8 2 7 3 6 4 8 2 8 2 9 1 7 3 6 4 8 2 9 1 7 0 Output 1200 127 1010 123 1101 60 3335 300 3321 200 3340 175 3332 122 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 positive integers N and M. How many sequences a of length N consisting of positive integers satisfy a_1 \times a_2 \times ... \times a_N = M? Find the count modulo 10^9+7. Here, two sequences a' and a'' are considered different when there exists some i such that a_i' \neq a_i''. -----Constraints----- - All values in input are integers. - 1 \leq N \leq 10^5 - 1 \leq M \leq 10^9 -----Input----- Input is given from Standard Input in the following format: N M -----Output----- Print the number of the sequences consisting of positive integers that satisfy the condition, modulo 10^9 + 7. -----Sample Input----- 2 6 -----Sample Output----- 4 Four sequences satisfy the condition: \{a_1, a_2\} = \{1, 6\}, \{2, 3\}, \{3, 2\} and \{6, 1\}. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a huge integer $a$ consisting of $n$ digits ($n$ is between $1$ and $3 \cdot 10^5$, inclusive). It may contain leading zeros. You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by $2$). For example, if $a = 032867235$ you can get the following integers in a single operation: $302867235$ if you swap the first and the second digits; $023867235$ if you swap the second and the third digits; $032876235$ if you swap the fifth and the sixth digits; $032862735$ if you swap the sixth and the seventh digits; $032867325$ if you swap the seventh and the eighth digits. Note, that you can't swap digits on positions $2$ and $4$ because the positions are not adjacent. Also, you can't swap digits on positions $3$ and $4$ because the digits have the same parity. You can perform any number (possibly, zero) of such operations. Find the minimum integer you can obtain. Note that the resulting integer also may contain leading zeros. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. The only line of each test case contains the integer $a$, its length $n$ is between $1$ and $3 \cdot 10^5$, inclusive. It is guaranteed that the sum of all values $n$ does not exceed $3 \cdot 10^5$. -----Output----- For each test case print line — the minimum integer you can obtain. -----Example----- Input 3 0709 1337 246432 Output 0079 1337 234642 -----Note----- In the first test case, you can perform the following sequence of operations (the pair of swapped digits is highlighted): $0 \underline{\textbf{70}} 9 \rightarrow 0079$. In the second test case, the initial integer is optimal. In the third test case you can perform the following sequence of operations: $246 \underline{\textbf{43}} 2 \rightarrow 24 \underline{\textbf{63}}42 \rightarrow 2 \underline{\textbf{43}} 642 \rightarrow 234642$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. В Берляндском государственном университете локальная сеть между серверами не всегда работает без ошибок. При передаче двух одинаковых сообщений подряд возможна ошибка, в результате которой эти два сообщения сливаются в одно. При таком слиянии конец первого сообщения совмещается с началом второго. Конечно, совмещение может происходить только по одинаковым символам. Длина совмещения должна быть положительным числом, меньшим длины текста сообщения. Например, при передаче двух сообщений «abrakadabra» подряд возможно, что оно будет передано с ошибкой описанного вида, и тогда будет получено сообщение вида «abrakadabrabrakadabra» или «abrakadabrakadabra» (в первом случае совмещение произошло по одному символу, а во втором — по четырем). По полученному сообщению t определите, возможно ли, что это результат ошибки описанного вида работы локальной сети, и если возможно, определите возможное значение s. Не следует считать ошибкой ситуацию полного наложения друга на друга двух сообщений. К примеру, если получено сообщение «abcd», следует считать, что в нём ошибки нет. Аналогично, простое дописывание одного сообщения вслед за другим не является признаком ошибки. Например, если получено сообщение «abcabc», следует считать, что в нём ошибки нет. -----Входные данные----- В единственной строке выходных данных следует непустая строка t, состоящая из строчных букв латинского алфавита. Длина строки t не превосходит 100 символов. -----Выходные данные----- Если сообщение t не может содержать ошибки, выведите «NO» (без кавычек) в единственную строку выходных данных. В противном случае в первой строке выведите «YES» (без кавычек), а в следующей строке выведите строку s — возможное сообщение, которое могло привести к ошибке. Если возможных ответов несколько, разрешается вывести любой из них. -----Примеры----- Входные данные abrakadabrabrakadabra Выходные данные YES abrakadabra Входные данные acacacaca Выходные данные YES acaca Входные данные abcabc Выходные данные NO Входные данные abababab Выходные данные YES ababab Входные данные tatbt Выходные данные NO -----Примечание----- Во втором примере подходящим ответом также является строка acacaca. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. T is playing a game with his friend, HL. There are $n$ piles of stones, the $i$-th pile initially has $a_i$ stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in the previous turn (the pile that was chosen by the other player, or if the current turn is the first turn then the player can choose any non-empty pile). The player who cannot choose a pile in his turn loses, and the game ends. Assuming both players play optimally, given the starting configuration of $t$ games, determine the winner of each game. -----Input----- The first line of the input contains a single integer $t$ $(1 \le t \le 100)$ — the number of games. The description of the games follows. Each description contains two lines: The first line contains a single integer $n$ $(1 \le n \le 100)$ — the number of piles. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 100)$. -----Output----- For each game, print on a single line the name of the winner, "T" or "HL" (without quotes) -----Example----- Input 2 1 2 2 1 1 Output T HL -----Note----- In the first game, T removes a single stone from the only pile in his first turn. After that, although the pile still contains $1$ stone, HL cannot choose from this pile because it has been chosen by T in the previous turn. Therefore, T is the winner. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have written N problems to hold programming contests. The i-th problem will have a score of P_i points if used in a contest. With these problems, you would like to hold as many contests as possible under the following condition: * A contest has three problems. The first problem has a score not greater than A points, the second has a score between A + 1 and B points (inclusive), and the third has a score not less than B + 1 points. The same problem should not be used in multiple contests. At most how many contests can be held? Constraints * 3 \leq N \leq 100 * 1 \leq P_i \leq 20 (1 \leq i \leq N) * 1 \leq A < B < 20 * All values in input are integers. Input Input is given from Standard Input in the following format: N A B P_1 P_2 ... P_N Output Print the answer. Examples Input 7 5 15 1 10 16 2 7 20 12 Output 2 Input 8 3 8 5 5 5 10 10 10 15 20 Output 0 Input 3 5 6 5 6 10 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. # RoboScript #2 - Implement the RS1 Specification ## Disclaimer The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental. ## About this Kata Series This Kata Series is based on a fictional story about a computer scientist and engineer who owns a firm that sells a toy robot called MyRobot which can interpret its own (esoteric) programming language called RoboScript. Naturally, this Kata Series deals with the software side of things (I'm afraid Codewars cannot test your ability to build a physical robot!). ## Story Now that you've built your own code editor for RoboScript with appropriate syntax highlighting to make it look like serious code, it's time to properly implement RoboScript so that our MyRobots can execute any RoboScript provided and move according to the will of our customers. Since this is the first version of RoboScript, let's call our specification RS1 (like how the newest specification for JavaScript is called ES6 :p) ## Task Write an interpreter for RS1 called `execute()` which accepts 1 required argument `code`, the RS1 program to be executed. The interpreter should return a string representation of the smallest 2D grid containing the full path that the MyRobot has walked on (explained in more detail later). Initially, the robot starts at the middle of a 1x1 grid. Everywhere the robot walks it will leave a path `"*"`. If the robot has not been at a particular point on the grid then that point will be represented by a whitespace character `" "`. So if the RS1 program passed in to `execute()` is empty, then: ``` "" --> "*" ``` The robot understands 3 major commands: - `F` - Move forward by 1 step in the direction that it is currently pointing. Initially, the robot faces to the right. - `L` - Turn "left" (i.e. **rotate** 90 degrees **anticlockwise**) - `R` - Turn "right" (i.e. **rotate** 90 degrees **clockwise**) As the robot moves forward, if there is not enough space in the grid, the grid should expand accordingly. So: ``` "FFFFF" --> "******" ``` As you will notice, 5 `F` commands in a row should cause your interpreter to return a string containing 6 `"*"`s in a row. This is because initially, your robot is standing at the middle of the 1x1 grid facing right. It leaves a mark on the spot it is standing on, hence the first `"*"`. Upon the first command, the robot moves 1 unit to the right. Since the 1x1 grid is not large enough, your interpreter should expand the grid 1 unit to the right. The robot then leaves a mark on its newly arrived destination hence the second `"*"`. As this process is repeated 4 more times, the grid expands 4 more units to the right and the robot keeps leaving a mark on its newly arrived destination so by the time the entire program is executed, 6 "squares" have been marked `"*"` from left to right. Each row in your grid must be separated from the next by a CRLF (`\r\n`). Let's look at another example: ``` "FFFFFLFFFFFLFFFFFLFFFFFL" --> "******\r\n* *\r\n* *\r\n* *\r\n* *\r\n******" ``` So the grid will look like this: ``` ****** * * * * * * * * ****** ``` The robot moves 5 units to the right, then turns left, then moves 5 units upwards, then turns left again, then moves 5 units to the left, then turns left again and moves 5 units downwards, returning to the starting point before turning left one final time. Note that the marks do **not** disappear no matter how many times the robot steps on them, e.g. the starting point is still marked `"*"` despite the robot having stepped on it twice (initially and on the last step). Another example: ``` "LFFFFFRFFFRFFFRFFFFFFF" --> " ****\r\n * *\r\n * *\r\n********\r\n * \r\n * " ``` So the grid will look like this: ``` **** * * * * ******** * * ``` Initially the robot turns left to face upwards, then moves upwards 5 squares, then turns right and moves 3 squares, then turns right again (to face downwards) and move 3 squares, then finally turns right again and moves 7 squares. Since you've realised that it is probably quite inefficient to repeat certain commands over and over again by repeating the characters (especially the `F` command - what if you want to move forwards 20 steps?), you decide to allow a shorthand notation in the RS1 specification which allows your customers to postfix a non-negative integer onto a command to specify how many times an instruction is to be executed: - `Fn` - Execute the `F` command `n` times (NOTE: `n` *may* be more than 1 digit long!) - `Ln` - Execute `L` n times - `Rn` - Execute `R` n times So the example directly above can also be written as: ``` "LF5RF3RF3RF7" ``` These 5 example test cases have been included for you :) ## Kata in this Series 1. [RoboScript #1 - Implement Syntax Highlighting](https://www.codewars.com/kata/roboscript-number-1-implement-syntax-highlighting) 2. **RoboScript #2 - Implement the RS1 Specification** 3. [RoboScript #3 - Implement the RS2 Specification](https://www.codewars.com/kata/58738d518ec3b4bf95000192) 4. [RoboScript #4 - RS3 Patterns to the Rescue](https://www.codewars.com/kata/594b898169c1d644f900002e) 5. [RoboScript #5 - The Final Obstacle (Implement RSU)](https://www.codewars.com/kata/5a12755832b8b956a9000133) Read the inputs from stdin solve the problem and write the answer to stdout (do 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 famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests. A result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately. In each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct). In the first contest, the participant on the 100-th place scored $a$ points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least $b$ points in the second contest. Similarly, for the second contest, the participant on the 100-th place has $c$ points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least $d$ points in the first contest. After two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The cutoff score to qualify to the final stage is the total score of the participant on the 100-th place. Given integers $a$, $b$, $c$, $d$, please help the jury determine the smallest possible value of the cutoff score. -----Input----- You need to process $t$ test cases. The first line contains an integer $t$ ($1 \leq t \leq 3025$) — the number of test cases. Then descriptions of $t$ test cases follow. The first line of each test case contains four integers $a$, $b$, $c$, $d$ ($0 \le a,\,b,\,c,\,d \le 9$; $d \leq a$; $b \leq c$). One can show that for any test case satisfying the constraints above, there is at least one olympiad scenario possible. -----Output----- For each test case print a single integer — the smallest possible cutoff score in some olympiad scenario satisfying the given information. -----Example----- Input 2 1 2 2 1 4 8 9 2 Output 3 12 -----Note----- For the first test case, consider the following olympiad scenario: there are $101$ participants in the elimination stage, each having $1$ point for the first contest and $2$ points for the second contest. Hence the total score of the participant on the 100-th place is $3$. For the second test case, consider the following olympiad scenario: there are $50$ participants with points $5$ and $9$ for the first and second contest respectively; $50$ participants with points $4$ and $8$ for the first and second contest respectively; and $50$ participants with points $2$ and $9$ for the first and second contest respectively. Hence the total point score of the participant on the 100-th place is $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. You are given a string s consisting of |s| small english letters. In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter. Your target is to make some number of moves (not necessary minimal) to get string abcdefghijklmnopqrstuvwxyz (english alphabet) as a subsequence. Subsequence of the string is the string that is obtained by deleting characters at some positions. You need to print the string that will be obtained from the given string and will be contain english alphabet as a subsequence or say that it is impossible. -----Input----- The only one line of the input consisting of the string s consisting of |s| (1 ≤ |s| ≤ 10^5) small english letters. -----Output----- If you can get a string that can be obtained from the given string and will contain english alphabet as a subsequence, print it. Otherwise print «-1» (without quotes). -----Examples----- Input aacceeggiikkmmooqqssuuwwyy Output abcdefghijklmnopqrstuvwxyz Input thereisnoanswer 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. Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area. To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of $n$ rows and $m$ columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side. Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo $10^9 + 7$. -----Input----- The only line contains two integers $n$ and $m$ ($1 \le n, m \le 100\,000$), the number of rows and the number of columns of the field. -----Output----- Print one integer, the number of random pictures modulo $10^9 + 7$. -----Example----- Input 2 3 Output 8 -----Note----- The picture below shows all possible random pictures of size $2$ by $3$. [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. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Everybody know that you passed to much time awake during night time... Your task here is to define how much coffee you need to stay awake after your night. You will have to complete a function that take an array of events in arguments, according to this list you will return the number of coffee you need to stay awake during day time. **Note**: If the count exceed 3 please return 'You need extra sleep'. The list of events can contain the following: - You come here, to solve some kata ('cw'). - You have a dog or a cat that just decide to wake up too early ('dog' | 'cat'). - You just watch a movie ('movie'). - Other events can be present and it will be represent by arbitrary string, just ignore this one. Each event can be downcase/lowercase, or uppercase. If it is downcase/lowercase you need 1 coffee by events and if it is uppercase you need 2 coffees. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a_1, a_2, ..., a_{m} of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f_1, f_2, ..., f_{n} of length n and for each number a_{i} got number b_{i} = f_{a}_{i}. To finish the prank he erased the initial sequence a_{i}. It's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible. -----Input----- The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the lengths of sequences f_{i} and b_{i} respectively. The second line contains n integers, determining sequence f_1, f_2, ..., f_{n} (1 ≤ f_{i} ≤ n). The last line contains m integers, determining sequence b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ n). -----Output----- Print "Possible" if there is exactly one sequence a_{i}, such that b_{i} = f_{a}_{i} for all i from 1 to m. Then print m integers a_1, a_2, ..., a_{m}. If there are multiple suitable sequences a_{i}, print "Ambiguity". If Spongebob has made a mistake in his calculations and no suitable sequence a_{i} exists, print "Impossible". -----Examples----- Input 3 3 3 2 1 1 2 3 Output Possible 3 2 1 Input 3 3 1 1 1 1 1 1 Output Ambiguity Input 3 3 1 2 1 3 3 3 Output Impossible -----Note----- In the first sample 3 is replaced by 1 and vice versa, while 2 never changes. The answer exists and is unique. In the second sample all numbers are replaced by 1, so it is impossible to unambiguously restore the original sequence. In the third sample f_{i} ≠ 3 for all i, so no sequence a_{i} transforms into such b_{i} and we can say for sure that Spongebob has made a mistake. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 chess tournament will be held soon, where $n$ chess players will take part. Every participant will play one game against every other participant. Each game ends in either a win for one player and a loss for another player, or a draw for both players. Each of the players has their own expectations about the tournament, they can be one of two types: a player wants not to lose any game (i. e. finish the tournament with zero losses); a player wants to win at least one game. You have to determine if there exists an outcome for all the matches such that all the players meet their expectations. If there are several possible outcomes, print any of them. If there are none, report that it's impossible. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 200$) — the number of test cases. The first line of each test case contains one integer $n$ ($2 \le n \le 50$) — the number of chess players. The second line contains the string $s$ ($|s| = n$; $s_i \in \{1, 2\}$). If $s_i = 1$, then the $i$-th player has expectations of the first type, otherwise of the second type. -----Output----- For each test case, print the answer in the following format: In the first line, print NO if it is impossible to meet the expectations of all players. Otherwise, print YES, and the matrix of size $n \times n$ in the next $n$ lines. The matrix element in the $i$-th row and $j$-th column should be equal to: +, if the $i$-th player won in a game against the $j$-th player; -, if the $i$-th player lost in a game against the $j$-th player; =, if the $i$-th and $j$-th players' game resulted in a draw; X, if $i = j$. -----Examples----- Input 3 3 111 2 21 4 2122 Output YES X== =X= ==X NO YES X--+ +X++ +-X- --+X -----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. — Hey folks, how do you like this problem? — That'll do it. BThero is a powerful magician. He has got $n$ piles of candies, the $i$-th pile initially contains $a_i$ candies. BThero can cast a copy-paste spell as follows: He chooses two piles $(i, j)$ such that $1 \le i, j \le n$ and $i \ne j$. All candies from pile $i$ are copied into pile $j$. Formally, the operation $a_j := a_j + a_i$ is performed. BThero can cast this spell any number of times he wants to — but unfortunately, if some pile contains strictly more than $k$ candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power? -----Input----- The first line contains one integer $T$ ($1 \le T \le 500$) — the number of test cases. Each test case consists of two lines: the first line contains two integers $n$ and $k$ ($2 \le n \le 1000$, $2 \le k \le 10^4$); the second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le k$). It is guaranteed that the sum of $n$ over all test cases does not exceed $1000$, and the sum of $k$ over all test cases does not exceed $10^4$. -----Output----- For each test case, print one integer — the maximum number of times BThero can cast the spell without losing his magic power. -----Example----- Input 3 2 2 1 1 3 5 1 2 3 3 7 3 2 2 Output 1 5 4 -----Note----- In the first test case we get either $a = [1, 2]$ or $a = [2, 1]$ after casting the spell for the first time, and it is impossible to cast it again. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. [Image] In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer. -----Input----- The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≤ yyyy ≤ 2038 and yyyy:mm:dd is a legal date). -----Output----- Print a single integer — the answer to the problem. -----Examples----- Input 1900:01:01 2038:12:31 Output 50768 Input 1996:03:09 1991:11:12 Output 1579 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 many of you know, we have two major calendar systems used in Japan today. One of them is Gregorian calendar which is widely used across the world. It is also known as “Western calendar” in Japan. The other calendar system is era-based calendar, or so-called “Japanese calendar.” This system comes from ancient Chinese systems. Recently in Japan it has been a common way to associate dates with the Emperors. In the era-based system, we represent a year with an era name given at the time a new Emperor assumes the throne. If the era name is “A”, the first regnal year will be “A 1”, the second year will be “A 2”, and so forth. Since we have two different calendar systems, it is often needed to convert the date in one calendar system to the other. In this problem, you are asked to write a program that converts western year to era-based year, given a database that contains association between several western years and era-based years. For the simplicity, you can assume the following: 1. A new era always begins on January 1st of the corresponding Gregorian year. 2. The first year of an era is described as 1. 3. There is no year in which more than one era switch takes place. Please note that, however, the database you will see may be incomplete. In other words, some era that existed in the history may be missing from your data. So you will also have to detect the cases where you cannot determine exactly which era the given year belongs to. Input The input contains multiple test cases. Each test case has the following format: N Q EraName1 EraBasedYear1 WesternYear1 . . . EraNameN EraBasedYearN WesternYearN Query1 . . . QueryQ The first line of the input contains two positive integers N and Q (1 ≤ N ≤ 1000, 1 ≤ Q ≤ 1000). N is the number of database entries, and Q is the number of queries. Each of the following N lines has three components: era name, era-based year number and the corresponding western year (1 ≤ EraBasedYeari ≤ WesternYeari ≤ 109 ). Each of era names consist of at most 16 Roman alphabet characters. Then the last Q lines of the input specifies queries (1 ≤ Queryi ≤ 109 ), each of which is a western year to compute era-based representation. The end of input is indicated by a line containing two zeros. This line is not part of any dataset and hence should not be processed. You can assume that all the western year in the input is positive integers, and that there is no two entries that share the same era name. Output For each query, output in a line the era name and the era-based year number corresponding to the western year given, separated with a single whitespace. In case you cannot determine the era, output “Unknown” without quotes. Example Input 4 3 meiji 10 1877 taisho 6 1917 showa 62 1987 heisei 22 2010 1868 1917 1988 1 1 universalcentury 123 2168 2010 0 0 Output meiji 1 taisho 6 Unknown Unknown Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the manager of the famous rescue team: The Knights. Your task is to assign your knights to a rescue missions on an infinite 2D-plane. Your knights can move only by `n-knight` jumps. For example, if a knight has n = 2, they can only move exactly as a knight on a chess board. If n = 3, they can move from (0, 0) to one of the following 8 points: `(3, 1) (3, -1), ( -3, 1), (-3, -1), (1, 3), (1, -3), (-1, 3) or (-1, -3).` You are given an array containing the `n`s of all of your knights `n-knight` jumps, and the coordinates (`x`, `y`) of a civilian who need your squad's help. Your head quarter is located at (0, 0). Your must determine if `at least one` of your knight can reach that point `(x, y)`. # Input/Output - `[input]` integer array `N` The ways your knights move. `1 <= N.length <=20` - `[input]` integer `x` The x-coordinate of the civilian - `[input]` integer `y` The y-coordinate of the civilian - `[output]` a boolean value `true` if one of your knights can reach point (x, y), `false` otherwise. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates $(0, 0)$, and coordinate axes are left and bottom sides of the table, then the bottom left corner of the white sheet has coordinates $(x_1, y_1)$, and the top right — $(x_2, y_2)$. After that two black sheets of paper are placed on the table. Sides of both black sheets are also parallel to the sides of the table. Coordinates of the bottom left corner of the first black sheet are $(x_3, y_3)$, and the top right — $(x_4, y_4)$. Coordinates of the bottom left corner of the second black sheet are $(x_5, y_5)$, and the top right — $(x_6, y_6)$. [Image] Example of three rectangles. Determine if some part of the white sheet can be seen from the above after the two black sheets are placed. The part of the white sheet can be seen if there is at least one point lying not strictly inside the white sheet and strictly outside of both black sheets. -----Input----- The first line of the input contains four integers $x_1, y_1, x_2, y_2$ $(0 \le x_1 < x_2 \le 10^{6}, 0 \le y_1 < y_2 \le 10^{6})$ — coordinates of the bottom left and the top right corners of the white sheet. The second line of the input contains four integers $x_3, y_3, x_4, y_4$ $(0 \le x_3 < x_4 \le 10^{6}, 0 \le y_3 < y_4 \le 10^{6})$ — coordinates of the bottom left and the top right corners of the first black sheet. The third line of the input contains four integers $x_5, y_5, x_6, y_6$ $(0 \le x_5 < x_6 \le 10^{6}, 0 \le y_5 < y_6 \le 10^{6})$ — coordinates of the bottom left and the top right corners of the second black sheet. The sides of each sheet of paper are parallel (perpendicular) to the coordinate axes. -----Output----- If some part of the white sheet can be seen from the above after the two black sheets are placed, print "YES" (without quotes). Otherwise print "NO". -----Examples----- Input 2 2 4 4 1 1 3 5 3 1 5 5 Output NO Input 3 3 7 5 0 0 4 6 0 0 7 4 Output YES Input 5 2 10 5 3 1 7 6 8 1 11 7 Output YES Input 0 0 1000000 1000000 0 0 499999 1000000 500000 0 1000000 1000000 Output YES -----Note----- In the first example the white sheet is fully covered by black sheets. In the second example the part of the white sheet can be seen after two black sheets are placed. For example, the point $(6.5, 4.5)$ lies not strictly inside the white sheet and lies strictly outside of both black sheets. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $s$ of length $n$ and $t$ of length $m$. A sequence $p_1, p_2, \ldots, p_m$, where $1 \leq p_1 < p_2 < \ldots < p_m \leq n$, is called beautiful, if $s_{p_i} = t_i$ for all $i$ from $1$ to $m$. The width of a sequence is defined as $\max\limits_{1 \le i < m} \left(p_{i + 1} - p_i\right)$. Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $s$ and $t$ there is at least one beautiful sequence. -----Input----- The first input line contains two integers $n$ and $m$ ($2 \leq m \leq n \leq 2 \cdot 10^5$) — the lengths of the strings $s$ and $t$. The following line contains a single string $s$ of length $n$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $t$ of length $m$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings. -----Output----- Output one integer — the maximum width of a beautiful sequence. -----Examples----- Input 5 3 abbbc abc Output 3 Input 5 2 aaaaa aa Output 4 Input 5 5 abcdf abcdf Output 1 Input 2 2 ab ab Output 1 -----Note----- In the first example there are two beautiful sequences of width $3$: they are $\{1, 2, 5\}$ and $\{1, 4, 5\}$. In the second example the beautiful sequence with the maximum width is $\{1, 5\}$. In the third example there is exactly one beautiful sequence — it is $\{1, 2, 3, 4, 5\}$. In the fourth example there is exactly one beautiful sequence — it is $\{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. You have three piles of candies: red, green and blue candies: the first pile contains only red candies and there are $r$ candies in it, the second pile contains only green candies and there are $g$ candies in it, the third pile contains only blue candies and there are $b$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day. Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies. -----Input----- The first line contains integer $t$ ($1 \le t \le 1000$) — the number of test cases in the input. Then $t$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $r$, $g$ and $b$ ($1 \le r, g, b \le 10^8$) — the number of red, green and blue candies, respectively. -----Output----- Print $t$ integers: the $i$-th printed integer is the answer on the $i$-th test case in the input. -----Example----- Input 6 1 1 1 1 2 1 4 1 1 7 4 10 8 1 4 8 2 8 Output 1 2 2 10 5 9 -----Note----- In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors. In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day. In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Given a natural number N less than or equal to 12, find the smallest natural number such that the number of divisors is exactly N. Constraints * 1 ≤ N ≤ 12 Input One natural number N is given in one line. Output Output the smallest natural number on a line so that the number of divisors is exactly N. Examples Input 1 Output 1 Input 2 Output 2 Input 3 Output 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. Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance. -----Input----- First line contains an integer n (1 ≤ n ≤ 100) — number of visits. Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses. Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses. Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses. -----Output----- Output one number — minimum distance in meters Winnie must go through to have a meal n times. -----Examples----- Input 3 2 3 1 Output 3 Input 1 2 3 5 Output 0 -----Note----- In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A rabbit is playing a role-playing game. Just before entering the castle, he was ambushed by an enemy! It was a battle between one hero operated by a rabbit and n enemies. Each character has four stats, health hi, attack power ai, defense power di, and agility si. I = 0 is the information of the main character, 1 ≤ i ≤ n is the information of each enemy. The battle is turn-based. Each turn, the surviving characters attack in descending order of agility. The enemy always attacks the hero. The hero attacks one enemy, but which enemy to attack Can be selected by the main character every turn. When a character with attack power a attacks a character with defense power d, max {a − d, 0} damage is dealt. The total damage received is greater than or equal to the value of physical strength. The character becomes incapacitated immediately. The battle ends when the main character becomes incapacitated, or when all the enemies become incapacitated. Input 1 ≤ n ≤ 40 000 1 ≤ hi, ai, di, si ≤ 1 000 000 000 (integer) si are all different. Output When the hero is sure to be incapacitated, output -1. Otherwise, output the minimum total damage to the hero in one line. Examples Input 2 10 3 1 2 2 4 1 3 2 2 1 1 Output 4 Input 1 1 1 1 1 10000 10000 10000 10000 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. Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust? -----Input----- The first line of input contains two integers n, m (2 ≤ n ≤ 10^5, $0 \leq m \leq \operatorname{min}(\frac{n(n - 1)}{2}, 10^{5})$), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≤ x, y ≤ n, $z \in \{0,1 \}$) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not. -----Output----- In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≤ x, y ≤ n, $z \in \{0,1 \}$), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any. -----Examples----- Input 2 1 1 2 0 Output 1 1 2 1 Input 4 4 1 2 1 1 3 0 2 3 1 3 4 1 Output 3 1 2 0 1 3 1 2 3 0 Input 8 9 1 2 0 8 3 0 2 3 1 1 4 1 8 7 0 1 5 1 4 6 1 5 7 0 6 8 0 Output 3 2 3 0 1 5 0 6 8 1 -----Note----- In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A young boy John is playing with eight triangular panels. These panels are all regular triangles of the same size, each painted in a single color; John is forming various octahedra with them. While he enjoys his playing, his father is wondering how many octahedra can be made of these panels since he is a pseudo-mathematician. Your task is to help his father: write a program that reports the number of possible octahedra for given panels. Here, a pair of octahedra should be considered identical when they have the same combination of the colors allowing rotation. Input The input consists of multiple datasets. Each dataset has the following format: Color1 Color2 ... Color8 Each Colori (1 ≤ i ≤ 8) is a string of up to 20 lowercase alphabets and represents the color of the i-th triangular panel. The input ends with EOF. Output For each dataset, output the number of different octahedra that can be made of given panels. Example Input blue blue blue blue blue blue blue blue red blue blue blue blue blue blue blue red red blue blue blue blue blue blue Output 1 1 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. Takahashi has come to a party as a special guest. There are N ordinary guests at the party. The i-th ordinary guest has a power of A_i. Takahashi has decided to perform M handshakes to increase the happiness of the party (let the current happiness be 0). A handshake will be performed as follows: - Takahashi chooses one (ordinary) guest x for his left hand and another guest y for his right hand (x and y can be the same). - Then, he shakes the left hand of Guest x and the right hand of Guest y simultaneously to increase the happiness by A_x+A_y. However, Takahashi should not perform the same handshake more than once. Formally, the following condition must hold: - Assume that, in the k-th handshake, Takahashi shakes the left hand of Guest x_k and the right hand of Guest y_k. Then, there is no pair p, q (1 \leq p < q \leq M) such that (x_p,y_p)=(x_q,y_q). What is the maximum possible happiness after M handshakes? -----Constraints----- - 1 \leq N \leq 10^5 - 1 \leq M \leq N^2 - 1 \leq A_i \leq 10^5 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N M A_1 A_2 ... A_N -----Output----- Print the maximum possible happiness after M handshakes. -----Sample Input----- 5 3 10 14 19 34 33 -----Sample Output----- 202 Let us say that Takahashi performs the following handshakes: - In the first handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 4. - In the second handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 5. - In the third handshake, Takahashi shakes the left hand of Guest 5 and the right hand of Guest 4. Then, we will have the happiness of (34+34)+(34+33)+(33+34)=202. We cannot achieve the happiness of 203 or greater, so the answer is 202. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 persons called Person 1 through Person N. You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times. If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts. Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group. At least how many groups does he need to make? -----Constraints----- - 2 \leq N \leq 2\times 10^5 - 0 \leq M \leq 2\times 10^5 - 1\leq A_i,B_i\leq N - A_i \neq B_i -----Input----- Input is given from Standard Input in the following format: N M A_1 B_1 \vdots A_M B_M -----Output----- Print the answer. -----Sample Input----- 5 3 1 2 3 4 5 1 -----Sample Output----- 3 Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming. Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a_1, a_2, ..., a_{n}, and Banban's have brightness b_1, b_2, ..., b_{m} respectively. Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns. Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible. You are asked to find the brightness of the chosen pair if both of them choose optimally. -----Input----- The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 50). The second line contains n space-separated integers a_1, a_2, ..., a_{n}. The third line contains m space-separated integers b_1, b_2, ..., b_{m}. All the integers range from - 10^9 to 10^9. -----Output----- Print a single integer — the brightness of the chosen pair. -----Examples----- Input 2 2 20 18 2 14 Output 252 Input 5 3 -1 0 1 2 3 -1 0 1 Output 2 -----Note----- In the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself. In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Soma is a fashionable girl. She absolutely loves shiny stones that she can put on as jewellery accessories. She has been collecting stones since her childhood - now she has become really good with identifying which ones are fake and which ones are not. Her King requested for her help in mining precious stones, so she has told him which all stones are jewels and which are not. Given her description, your task is to count the number of jewel stones. More formally, you're given a string J composed of latin characters where each character is a jewel. You're also given a string S composed of latin characters where each character is a mined stone. You have to find out how many characters of S are in J as well. ------ Input ------ First line contains an integer T denoting the number of test cases. Then follow T test cases. Each test case consists of two lines, each of which contains a string composed of English lower case and upper characters. First of these is the jewel string J and the second one is stone string S. You can assume that 1 ≤ T ≤ 100, 1 ≤ |J|, |S| ≤ 100 ------ Output ------ Output for each test case, a single integer, the number of jewels mined. ----- Sample Input 1 ------ 4 abc abcdef aA abAZ aaa a what none ----- Sample Output 1 ------ 3 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. Профиль горного хребта схематично задан в виде прямоугольной таблицы из символов «.» (пустое пространство) и «*» (часть горы). Каждый столбец таблицы содержит хотя бы одну «звёздочку». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*». ........... .........*. .*.......*. **.......*. **..*...**. *********** Пример изображения горного хребта. Маршрут туриста проходит через весь горный хребет слева направо. Каждый день турист перемещается вправо — в соседний столбец в схематичном изображении. Конечно, каждый раз он поднимается (или опускается) в самую верхнюю точку горы, которая находится в соответствующем столбце. Считая, что изначально турист находится в самой верхней точке в первом столбце, а закончит свой маршрут в самой верхней точке в последнем столбце, найдите две величины: наибольший подъём за день (равен 0, если в профиле горного хребта нет ни одного подъёма), наибольший спуск за день (равен 0, если в профиле горного хребта нет ни одного спуска). -----Входные данные----- В первой строке входных данных записаны два целых числа n и m (1 ≤ n, m ≤ 100) — количество строк и столбцов в схематичном изображении соответственно. Далее следуют n строк по m символов в каждой — схематичное изображение горного хребта. Каждый символ схематичного изображения — это либо «.», либо «*». Каждый столбец матрицы содержит хотя бы один символ «*». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*». -----Выходные данные----- Выведите через пробел два целых числа: величину наибольшего подъёма за день (или 0, если в профиле горного хребта нет ни одного подъёма), величину наибольшего спуска за день (или 0, если в профиле горного хребта нет ни одного спуска). -----Примеры----- Входные данные 6 11 ........... .........*. .*.......*. **.......*. **..*...**. *********** Выходные данные 3 4 Входные данные 5 5 ....* ...** ..*** .**** ***** Выходные данные 1 0 Входные данные 8 7 ....... .*..... .*..... .**.... .**.*.. .****.* .****** ******* Выходные данные 6 2 -----Примечание----- В первом тестовом примере высоты гор равны: 3, 4, 1, 1, 2, 1, 1, 1, 2, 5, 1. Наибольший подъем равен 3 и находится между горой номер 9 (её высота равна 2) и горой номер 10 (её высота равна 5). Наибольший спуск равен 4 и находится между горой номер 10 (её высота равна 5) и горой номер 11 (её высота равна 1). Во втором тестовом примере высоты гор равны: 1, 2, 3, 4, 5. Наибольший подъём равен 1 и находится, например, между горой номер 2 (ее высота равна 2) и горой номер 3 (её высота равна 3). Так как в данном горном хребте нет спусков, то величина наибольшего спуска равна 0. В третьем тестовом примере высоты гор равны: 1, 7, 5, 3, 4, 2, 3. Наибольший подъём равен 6 и находится между горой номер 1 (её высота равна 1) и горой номер 2 (её высота равна 7). Наибольший спуск равен 2 и находится между горой номер 2 (её высота равна 7) и горой номер 3 (её высота равна 5). Такой же спуск находится между горой номер 5 (её высота равна 4) и горой номер 6 (её высота равна 2). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task `EvilCode` is a game similar to `Codewars`. You have to solve programming tasks as quickly as possible. However, unlike `Codewars`, `EvilCode` awards you with a medal, depending on the time you took to solve the task. To get a medal, your time must be (strictly) inferior to the time corresponding to the medal. You can be awarded `"Gold", "Silver" or "Bronze"` medal, or `"None"` medal at all. Only one medal (the best achieved) is awarded. You are given the time achieved for the task and the time corresponding to each medal. Your task is to return the awarded medal. Each time is given in the format `HH:MM:SS`. # Input/Output `[input]` string `userTime` The time the user achieved. `[input]` string `gold` The time corresponding to the gold medal. `[input]` string `silver` The time corresponding to the silver medal. `[input]` string `bronze` The time corresponding to the bronze medal. It is guaranteed that `gold < silver < bronze`. `[output]` a string The medal awarded, one of for options: `"Gold", "Silver", "Bronze" or "None"`. # Example For ``` userTime = "00:30:00", gold = "00:15:00", silver = "00:45:00" and bronze = "01:15:00"``` the output should be `"Silver"` For ``` userTime = "01:15:00", gold = "00:15:00", silver = "00:45:00" and bronze = "01:15:00"``` the output should be `"None"` # For Haskell version ``` In Haskell, the result is a Maybe, returning Just String indicating the medal if they won or Nothing if they don't. ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height h_{i}. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k + 1). When the player have made such a move, its energy increases by h_{k} - h_{k} + 1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game? -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5). The next line contains n integers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 10^5) representing the heights of the pylons. -----Output----- Print a single number representing the minimum number of dollars paid by Caisa. -----Examples----- Input 5 3 4 3 2 4 Output 4 Input 3 4 4 4 Output 4 -----Note----- In the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the following recurrence: $$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$ Here $minDigit(x)$ and $maxDigit(x)$ are the minimal and maximal digits in the decimal representation of $x$ without leading zeroes. For examples refer to notes. Your task is calculate $a_{K}$ for given $a_{1}$ and $K$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of independent test cases. Each test case consists of a single line containing two integers $a_{1}$ and $K$ ($1 \le a_{1} \le 10^{18}$, $1 \le K \le 10^{16}$) separated by a space. -----Output----- For each test case print one integer $a_{K}$ on a separate line. -----Example----- Input 8 1 4 487 1 487 2 487 3 487 4 487 5 487 6 487 7 Output 42 487 519 528 544 564 588 628 -----Note----- $a_{1} = 487$ $a_{2} = a_{1} + minDigit(a_{1}) \cdot maxDigit(a_{1}) = 487 + \min (4, 8, 7) \cdot \max (4, 8, 7) = 487 + 4 \cdot 8 = 519$ $a_{3} = a_{2} + minDigit(a_{2}) \cdot maxDigit(a_{2}) = 519 + \min (5, 1, 9) \cdot \max (5, 1, 9) = 519 + 1 \cdot 9 = 528$ $a_{4} = a_{3} + minDigit(a_{3}) \cdot maxDigit(a_{3}) = 528 + \min (5, 2, 8) \cdot \max (5, 2, 8) = 528 + 2 \cdot 8 = 544$ $a_{5} = a_{4} + minDigit(a_{4}) \cdot maxDigit(a_{4}) = 544 + \min (5, 4, 4) \cdot \max (5, 4, 4) = 544 + 4 \cdot 5 = 564$ $a_{6} = a_{5} + minDigit(a_{5}) \cdot maxDigit(a_{5}) = 564 + \min (5, 6, 4) \cdot \max (5, 6, 4) = 564 + 4 \cdot 6 = 588$ $a_{7} = a_{6} + minDigit(a_{6}) \cdot maxDigit(a_{6}) = 588 + \min (5, 8, 8) \cdot \max (5, 8, 8) = 588 + 5 \cdot 8 = 628$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > a_{u}, where a_{u} is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u. Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root. Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? -----Input----- In the first line of the input integer n (1 ≤ n ≤ 10^5) is given — the number of vertices in the tree. In the second line the sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) is given, where a_{i} is the number written on vertex i. The next n - 1 lines describe tree edges: i^{th} of them consists of two integers p_{i} and c_{i} (1 ≤ p_{i} ≤ n, - 10^9 ≤ c_{i} ≤ 10^9), meaning that there is an edge connecting vertices i + 1 and p_{i} with number c_{i} written on it. -----Output----- Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. -----Example----- Input 9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8 Output 5 -----Note----- The following image represents possible process of removing leaves from the tree: [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 boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: Operation AND ('&', ASCII code 38) Operation OR ('|', ASCII code 124) Operation NOT ('!', ASCII code 33) Variables x, y and z (ASCII codes 120-122) Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one. Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar: E ::= E '|' T | T T ::= T '&' F | F F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z' -----Input----- The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of $x = \lfloor \frac{j}{4} \rfloor$, $y = \lfloor \frac{j}{2} \rfloor \operatorname{mod} 2$ and $z = j \operatorname{mod} 2$. -----Output----- You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces. -----Example----- Input 4 00110011 00000111 11110000 00011111 Output y (y|z)&x !x x|y&z -----Note----- The truth table for the second function: [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.