question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: «[date:time]: message», where for each «[date:time]» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one programmer — Alex — managed to decode them. The code was so complicated that Alex needed four weeks to decode it. Right after the decoding process was finished, all the files were deleted. But after the files deletion, Alex noticed that he saved the recordings in format «[time]: message». So, information about the dates was lost. However, as the lines were added into the log in chronological order, it's not difficult to say if the recordings could appear during one day or not. It is possible also to find the minimum amount of days during which the log was written. So, to make up for his mistake Alex has to find the minimum amount of days covered by the log. Note that Alex doesn't have to find the minimum amount of days between the beginning and the end of the logging, he has to find the minimum amount of dates in which records could be done. (See Sample test 2 for further clarifications). We should remind you that the process made not more than 10 recordings in a minute. Consider that a midnight belongs to coming day. Input The first input line contains number n (1 ≤ n ≤ 100). The following n lines contain recordings in format «[time]: message», where time is given in format «hh:mm x.m.». For hh two-digit numbers from 01 to 12 are used, for mm two-digit numbers from 00 to 59 are used, and x is either character «a» or character «p». A message is a non-empty sequence of Latin letters and/or spaces, it doesn't start or end with a space. The length of each message doesn't exceed 20. Output Output one number — the minimum amount of days covered by the log. Examples Input 5 [05:00 a.m.]: Server is started [05:00 a.m.]: Rescan initialized [01:13 p.m.]: Request processed [01:10 p.m.]: Request processed [11:40 p.m.]: Rescan completed Output 2 Input 3 [09:00 a.m.]: User logged in [08:00 a.m.]: User logged in [07:00 a.m.]: User logged in Output 3 Note Formally the 12-hour time format is described at: * http://en.wikipedia.org/wiki/12-hour_clock. The problem authors recommend you to look through these descriptions before you start with the problem. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Magic The Gathering is a collectible card game that features wizards battling against each other with spells and creature summons. The game itself can be quite complicated to learn. In this series of katas, we'll be solving some of the situations that arise during gameplay. You won't need any prior knowledge of the game to solve these contrived problems, as I will provide you with enough information. ## Creatures Each creature has a power and toughness. We will represent this in an array. [2, 3] means this creature has a power of 2 and a toughness of 3. When two creatures square off, they each deal damage equal to their power to each other at the same time. If a creature takes on damage greater than or equal to their toughness, they die. Examples: - Creature 1 - [2, 3] - Creature 2 - [3, 3] - Creature 3 - [1, 4] - Creature 4 - [4, 1] If creature 1 battles creature 2, creature 1 dies, while 2 survives. If creature 3 battles creature 4, they both die, as 3 deals 1 damage to 4, but creature 4 only has a toughness of 1. Write a function `battle(player1, player2)` that takes in 2 arrays of creatures. Each players' creatures battle each other in order (player1[0] battles the creature in player2[0]) and so on. If one list of creatures is longer than the other, those creatures are considered unblocked, and do not battle. Your function should return an object (a hash in Ruby) with the keys player1 and player2 that contain the power and toughness of the surviving creatures. Example: ``` Good luck with your battles! Check out my other Magic The Gathering katas: Magic The Gathering #1: Creatures Magic The Gathering #2: Mana Read the inputs from stdin solve the problem and write the answer to stdout (do 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 median in an array with the length of n is an element which occupies position number <image> after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17. We define an expression <image> as the integer part of dividing number a by number b. One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x. Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need. Input The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different. Output Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x. Examples Input 3 10 10 20 30 Output 1 Input 3 4 1 2 3 Output 4 Note In the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position <image>, that is, 10. In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The kingdom of Lazyland is the home to $n$ idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today $k$ important jobs for the kingdom ($k \le n$) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the $i$-th idler has chosen the job $a_i$. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes $b_i$ minutes to persuade the $i$-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? -----Input----- The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 10^5$) — the number of idlers and the number of jobs. The second line of the input contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le k$) — the jobs chosen by each idler. The third line of the input contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le 10^9$) — the time the King needs to spend to persuade the $i$-th idler. -----Output----- The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. -----Examples----- Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 -----Note----- In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Many years ago, Roman numbers were defined by only `4` digits: `I, V, X, L`, which represented `1, 5, 10, 50`. These were the only digits used. The value of a sequence was simply the sum of digits in it. For instance: ``` IV = VI = 6 IX = XI = 11 XXL = LXX = XLX = 70 ``` It is easy to see that this system is ambiguous, and some numbers could be written in many different ways. Your goal is to determine how many distinct integers could be represented by exactly `n` Roman digits grouped together. For instance: ```Perl solve(1) = 4, because groups of 1 are [I, V, X, L]. solve(2) = 10, because the groups of 2 are [II, VI, VV, XI, XV, XX, IL, VL, XL, LL] corresponding to [2,6,10,11,15,20,51,55,60,100]. solve(3) = 20, because groups of 3 start with [III, IIV, IVV, ...etc] ``` `n <= 10E7` More examples in test cases. 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. Snuke signed up for a new website which holds programming competitions. He worried that he might forget his password, and he took notes of it. Since directly recording his password would cause him trouble if stolen, he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions. You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order. Restore the original password. -----Constraints----- - O and E consists of lowercase English letters (a - z). - 1 \leq |O|,|E| \leq 50 - |O| - |E| is either 0 or 1. -----Input----- Input is given from Standard Input in the following format: O E -----Output----- Print the original password. -----Sample Input----- xyz abc -----Sample Output----- xaybzc The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given is a tree with N vertices numbered 1 to N, and N-1 edges numbered 1 to N-1. Edge i connects Vertex a_i and b_i bidirectionally and has a length of 1. Snuke will paint each vertex white or black. The niceness of a way of painting the graph is \max(X, Y), where X is the maximum among the distances between white vertices, and Y is the maximum among the distances between black vertices. Here, if there is no vertex of one color, we consider the maximum among the distances between vertices of that color to be 0. There are 2^N ways of painting the graph. Compute the sum of the nicenesses of all those ways, modulo (10^{9}+7). -----Constraints----- - 2 \leq N \leq 2 \times 10^{5} - 1 \leq a_i, b_i \leq N - The given graph is a tree. -----Input----- Input is given from Standard Input in the following format: N a_1 b_1 \vdots a_{N-1} b_{N-1} -----Output----- Print the sum of the nicenesses of the ways of painting the graph, modulo (10^{9}+7). -----Sample Input----- 2 1 2 -----Sample Output----- 2 - If we paint Vertex 1 and 2 the same color, the niceness will be 1; if we paint them different colors, the niceness will be 0. - The sum of those nicenesses is 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The __Hamming weight__ of a string is the number of symbols that are different from the zero-symbol of the alphabet used. There are several algorithms for efficient computing of the Hamming weight for numbers. In this Kata, speaking technically, you have to find out the number of '1' bits in a binary representation of a number. Thus, The interesting part of this task is that you have to do it *without* string operation (hey, it's not really interesting 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. # Task Let's define a `parameter` of number `n` as the least common multiple (LCM) of the sum of its digits and their product. Calculate the parameter of the given number `n`. # Input/Output `[input]` integer `n` A positive integer. It is guaranteed that no zero appears in `n`. `[output]` an integer The parameter of the given number. # Example For `n = 22`, the output should be `4`. Both the sum and the product of digits equal 4, and LCM(4, 4) = 4. For `n = 1234`, the output should be `120`. `1+2+3+4=10` and `1*2*3*4=24`, LCM(10,24)=120 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Naming multiple files can be a pain sometimes. #### Task: Your job here is to create a function that will take three parameters, `fmt`, `nbr` and `start`, and create an array of `nbr` elements formatted according to `frm` with the starting index `start`. `fmt` will have `` inserted at various locations; this is where the file index number goes in each file. #### Description of edge cases: 1. If `nbr` is less than or equal to 0, or not whole, return an empty array. 2. If `fmt` does not contain `''`, just return an array with `nbr` elements that are all equal to `fmt`. 3. If `start` is not an integer, return an empty array. #### What each parameter looks like: ```python type(frm) #=> str : "text_to_stay_constant_from_file_to_file " type(nbr) #=> int : number_of_files type(start) #=> int : index_no_of_first_file type(name_file(frm, nbr, start)) #=> list ``` #### Some examples: ```python name_file("IMG ", 4, 1) #=> ["IMG 1", "IMG 2", "IMG 3", "IMG 4"]) name_file("image #.jpg", 3, 7) #=> ["image #7.jpg", "image #8.jpg", "image #9.jpg"] name_file("# #", 3, -2) #=> ["#-2 #-2", "#-1 #-1", "#0 #0"] ``` Also check out my other creations — [Elections: Weighted Average](https://www.codewars.com/kata/elections-weighted-average), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions), [Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2). If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to gain dexterity that never mistypes by carefully stacking blocks. Since there are many building blocks, let's build a tall tower. There are N blocks, and the i-th (1 ≤ i ≤ N) building blocks are in the shape of a rectangular parallelepiped of 1 x Ai x Bi. The side of length 1 is used in the depth direction, and the sides of lengths Ai and Bi are assigned one by one in the horizontal direction and one in the height direction. When building blocks, the upper building blocks must be exactly shorter in width than the lower building blocks. The blocks can be used in any order, and some blocks may not be used. Under these restrictions, I want to make the tallest tower that can be built. Input N A1 B1 ... AN BN Satisfy 1 ≤ N ≤ 1,000, 1 ≤ Ai, Bi ≤ 1,000,000. All input values ​​are integers. Output Output the maximum height of the tower on one line. Examples Input 3 10 40 10 40 20 30 Output 80 Input 4 1 2 2 3 3 4 4 1 Output 11 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from $(0,0)$ to $(x,0)$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $n$ favorite numbers: $a_1, a_2, \ldots, a_n$. What is the minimum number of hops Rabbit needs to get from $(0,0)$ to $(x,0)$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination. Recall that the Euclidean distance between points $(x_i, y_i)$ and $(x_j, y_j)$ is $\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$. For example, if Rabbit has favorite numbers $1$ and $3$ he could hop from $(0,0)$ to $(4,0)$ in two hops as shown below. Note that there also exists other valid ways to hop to $(4,0)$ in $2$ hops (e.g. $(0,0)$ $\rightarrow$ $(2,-\sqrt{5})$ $\rightarrow$ $(4,0)$). $1$ Here is a graphic for the first example. Both hops have distance $3$, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number $a_i$ and hops with distance equal to $a_i$ in any direction he wants. The same number can be used multiple times. -----Input----- The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 1000$)  — the number of test cases. Next $2t$ lines contain test cases — two lines per test case. The first line of each test case contains two integers $n$ and $x$ ($1 \le n \le 10^5$, $1 \le x \le 10^9$)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct. It is guaranteed that the sum of $n$ over all the test cases will not exceed $10^5$. -----Output----- For each test case, print a single integer — the minimum number of hops needed. -----Example----- Input 4 2 4 1 3 3 12 3 4 5 1 5 5 2 10 15 4 Output 2 3 1 2 -----Note----- The first test case of the sample is shown in the picture above. Rabbit can hop to $(2,\sqrt{5})$, then to $(4,0)$ for a total of two hops. Each hop has a distance of $3$, which is one of his favorite numbers. In the second test case of the sample, one way for Rabbit to hop $3$ times is: $(0,0)$ $\rightarrow$ $(4,0)$ $\rightarrow$ $(8,0)$ $\rightarrow$ $(12,0)$. In the third test case of the sample, Rabbit can hop from $(0,0)$ to $(5,0)$. In the fourth test case of the sample, Rabbit can hop: $(0,0)$ $\rightarrow$ $(5,10\sqrt{2})$ $\rightarrow$ $(10,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. "What are your shoe sizes?" Suddenly, the doctor asked me when I met him for the first time. "It's 23.5" "Oh, that's a really nice number. It's 2 to the 4th power plus 2 to the 2nd power, 2 to the 1st power, 2 to the 0th power, and 2 to the 1st power." Then the doctor asked. "You, how tall are you?" "Yes, it's 158.1." He folded his arms and closed his eyes. After a while of silence, I opened my mouth. "Nah ~" After that, during the time I spent together, I gradually became able to understand the behavior of the doctor. First, I say the real number at the request of the doctor. If the real number is represented by a binary number with no more than 8 digits for the integer part and no more than 4 digits for the decimal part, he is happy to say the result of the conversion to binary. If not, it will sadly yell "Nah ~". This repeats until I say a negative real number. By the way, as he got older, it became more and more difficult to make long calculations. Therefore, please make a program for you to input real numbers and convert / output them to binary numbers on your behalf. However, if the binary representation does not fit within the limit number of digits (integer part within 8 digits + decimal part within 4 digits), output NA (half-width alphabetic characters). The input real number shall fit within 8 digits of the integer part and within 4 digits of the decimal part, and the binary representation to be output should be output with 8 digits of the integer part and 4 digits of the decimal part. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single negative real line. One real number n is given to one row for each dataset. The number of datasets does not exceed 1200. Output Outputs the conversion result to binary number for each input data set. Example Input 23.5 158.1 -1.0 Output 00010111.1000 NA Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task Consider the following algorithm for constructing 26 strings S(1) .. S(26): ``` S(1) = "a"; For i in [2, 3, ..., 26]: S(i) = S(i - 1) + character(i) + S(i - 1).``` For example: ``` S(1) = "a" S(2) = S(1) + "b" + S(1) = "a" + "b" + "a" = "aba" S(3) = S(2) + "c" + S(2) = "aba" + "c" +"aba" = "abacaba" ... S(26) = S(25) + "z" + S(25)``` Finally, we got a long string S(26). Your task is to find the `k`th symbol (indexing from 1) in the string S(26). All strings consist of lowercase letters only. # Input / Output - `[input]` integer `k` 1 ≤ k < 2^(26) - `[output]` a string(char in C#) the `k`th symbol of S(26) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Slime and his $n$ friends are at a party. Slime has designed a game for his friends to play. At the beginning of the game, the $i$-th player has $a_i$ biscuits. At each second, Slime will choose a biscuit randomly uniformly among all $a_1 + a_2 + \ldots + a_n$ biscuits, and the owner of this biscuit will give it to a random uniform player among $n-1$ players except himself. The game stops when one person will have all the biscuits. As the host of the party, Slime wants to know the expected value of the time that the game will last, to hold the next activity on time. For convenience, as the answer can be represented as a rational number $\frac{p}{q}$ for coprime $p$ and $q$, you need to find the value of $(p \cdot q^{-1})\mod 998\,244\,353$. You can prove that $q\mod 998\,244\,353 \neq 0$. -----Input----- The first line contains one integer $n\ (2\le n\le 100\,000)$: the number of people playing the game. The second line contains $n$ non-negative integers $a_1,a_2,\dots,a_n\ (1\le a_1+a_2+\dots+a_n\le 300\,000)$, where $a_i$ represents the number of biscuits the $i$-th person own at the beginning. -----Output----- Print one integer: the expected value of the time that the game will last, modulo $998\,244\,353$. -----Examples----- Input 2 1 1 Output 1 Input 2 1 2 Output 3 Input 5 0 0 0 0 35 Output 0 Input 5 8 4 2 0 1 Output 801604029 -----Note----- For the first example, in the first second, the probability that player $1$ will give the player $2$ a biscuit is $\frac{1}{2}$, and the probability that player $2$ will give the player $1$ a biscuit is $\frac{1}{2}$. But anyway, the game will stop after exactly $1$ second because only one player will occupy all biscuits after $1$ second, 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. Given are an integer K and integers a_1,\dots, a_K. Determine whether a sequence P satisfying below exists. If it exists, find the lexicographically smallest such sequence. * Every term in P is an integer between 1 and K (inclusive). * For each i=1,\dots, K, P contains a_i occurrences of i. * For each term in P, there is a contiguous subsequence of length K that contains that term and is a permutation of 1,\dots, K. Constraints * 1 \leq K \leq 100 * 1 \leq a_i \leq 1000 \quad (1\leq i\leq K) * a_1 + \dots + a_K\leq 1000 * All values in input are integers. Input Input is given from Standard Input in the following format: K a_1 a_2 \dots a_K Output If there is no sequence satisfying the conditions, print `-1`. Otherwise, print the lexicographically smallest sequence satisfying the conditions. Examples Input 3 2 4 3 Output 2 1 3 2 2 3 1 2 3 Input 4 3 2 3 2 Output 1 2 3 4 1 3 1 2 4 3 Input 5 3 1 4 1 5 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. Поликарп мечтает стать программистом и фанатеет от степеней двойки. Среди двух чисел ему больше нравится то, которое делится на большую степень числа 2. По заданной последовательности целых положительных чисел a_1, a_2, ..., a_{n} требуется найти r — максимальную степень числа 2, на которую делится хотя бы одно из чисел последовательности. Кроме того, требуется вывести количество чисел a_{i}, которые делятся на r. -----Входные данные----- В первой строке записано целое число n (1 ≤ n ≤ 100) — длина последовательности a. Во второй строке записана последовательность целых чисел a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). -----Выходные данные----- Выведите два числа: r — максимальную степень двойки, на которую делится хотя бы одно из чисел заданной последовательности, количество элементов последовательности, которые делятся на r. -----Примеры----- Входные данные 5 80 7 16 4 48 Выходные данные 16 3 Входные данные 4 21 5 3 33 Выходные данные 1 4 -----Примечание----- В первом тестовом примере максимальная степень двойки, на которую делится хотя бы одно число, равна 16 = 2^4, на неё делятся числа 80, 16 и 48. Во втором тестовом примере все четыре числа нечётные, поэтому делятся только на 1 = 2^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. You certainly can tell which is the larger number between 2^(10) and 2^(15). But what about, say, 2^(10) and 3^(10)? You know this one too. Things tend to get a bit more complicated with **both** different bases and exponents: which is larger between 3^(9) and 5^(6)? Well, by now you have surely guessed that you have to build a function to compare powers, returning -1 if the first member is larger, 0 if they are equal, 1 otherwise; powers to compare will be provided in the `[base, exponent]` format: ```python compare_powers([2,10],[2,15])==1 compare_powers([2,10],[3,10])==1 compare_powers([2,10],[2,10])==0 compare_powers([3,9],[5,6])==-1 compare_powers([7,7],[5,8])==-1 ``` ```if:nasm int compare_powers(const int n1[2], const int n2[2]) ``` Only positive integers will be tested, incluing bigger numbers - you are warned now, so be diligent try to implement an efficient solution not to drain too much on CW resources ;)! Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '<image>' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1. When ZS the Coder is at level k, he can : 1. Press the ' + ' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes x + k. 2. Press the '<image>' button. Let the number on the screen be x. After pressing this button, the number becomes <image>. After that, ZS the Coder levels up, so his current level becomes k + 1. This button can only be pressed when x is a perfect square, i.e. x = m2 for some positive integer m. Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '<image>' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5. ZS the Coder needs your help in beating the game — he wants to reach level n + 1. In other words, he needs to press the '<image>' button n times. Help him determine the number of times he should press the ' + ' button before pressing the '<image>' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level n + 1, but not necessarily a sequence minimizing the number of presses. Input The first and only line of the input contains a single integer n (1 ≤ n ≤ 100 000), denoting that ZS the Coder wants to reach level n + 1. Output Print n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the ' + ' button before pressing the '<image>' button at level i. Each number in the output should not exceed 1018. However, the number on the screen can be greater than 1018. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them. Examples Input 3 Output 14 16 46 Input 2 Output 999999999999999998 44500000000 Input 4 Output 2 17 46 97 Note In the first sample case: On the first level, ZS the Coder pressed the ' + ' button 14 times (and the number on screen is initially 2), so the number became 2 + 14·1 = 16. Then, ZS the Coder pressed the '<image>' button, and the number became <image>. After that, on the second level, ZS pressed the ' + ' button 16 times, so the number becomes 4 + 16·2 = 36. Then, ZS pressed the '<image>' button, levelling up and changing the number into <image>. After that, on the third level, ZS pressed the ' + ' button 46 times, so the number becomes 6 + 46·3 = 144. Then, ZS pressed the '<image>' button, levelling up and changing the number into <image>. Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4. Also, note that pressing the ' + ' button 10 times on the third level before levelling up does not work, because the number becomes 6 + 10·3 = 36, and when the '<image>' button is pressed, the number becomes <image> and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution. In the second sample case: On the first level, ZS the Coder pressed the ' + ' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2 + 999999999999999998·1 = 1018. Then, ZS the Coder pressed the '<image>' button, and the number became <image>. After that, on the second level, ZS pressed the ' + ' button 44500000000 times, so the number becomes 109 + 44500000000·2 = 9·1010. Then, ZS pressed the '<image>' button, levelling up and changing the number into <image>. Note that 300000 is a multiple of 3, so ZS the Coder can reach level 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. <image> For given three points p0, p1, p2, print COUNTER_CLOCKWISE if p0, p1, p2 make a counterclockwise turn (1), CLOCKWISE if p0, p1, p2 make a clockwise turn (2), ONLINE_BACK if p2 is on a line p2, p0, p1 in this order (3), ONLINE_FRONT if p2 is on a line p0, p1, p2 in this order (4), ON_SEGMENT if p2 is on a segment p0p1 (5). Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xi, yi ≤ 10000 * p0 and p1 are not identical. Input xp0 yp0 xp1 yp1 q xp20 yp20 xp21 yp21 ... xp2q-1 yp2q-1 In the first line, integer coordinates of p0 and p1 are given. Then, q queries are given for integer coordinates of p2. Output For each query, print the above mentioned status. Examples Input 0 0 2 0 2 -1 1 -1 -1 Output COUNTER_CLOCKWISE CLOCKWISE Input 0 0 2 0 3 -1 0 0 0 3 0 Output ONLINE_BACK ON_SEGMENT ONLINE_FRONT Read the inputs from stdin solve the problem and write the answer to stdout (do 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. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task. Input The single line contains an integer n (1 ≤ n ≤ 106) — the sum of digits of the required lucky number. Output Print on the single line the result — the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1. Examples Input 11 Output 47 Input 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. There are N children, numbered 1, 2, \ldots, N. They have decided to share K candies among themselves. Here, for each i (1 \leq i \leq N), Child i must receive between 0 and a_i candies (inclusive). Also, no candies should be left over. Find the number of ways for them to share candies, modulo 10^9 + 7. Here, two ways are said to be different when there exists a child who receives a different number of candies. Constraints * All values in input are integers. * 1 \leq N \leq 100 * 0 \leq K \leq 10^5 * 0 \leq a_i \leq K Input Input is given from Standard Input in the following format: N K a_1 a_2 \ldots a_N Output Print the number of ways for the children to share candies, modulo 10^9 + 7. Examples Input 3 4 1 2 3 Output 5 Input 1 10 9 Output 0 Input 2 0 0 0 Output 1 Input 4 100000 100000 100000 100000 100000 Output 665683269 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Dr. A of the Aizu Institute of Biological Research discovered a mysterious insect on a certain southern island. The shape is elongated like a hornworm, but since one segment is shaped like a ball, it looks like a beaded ball connected by a thread. What was strange was that there were many variations in body color, and some insects changed their body color over time. It seems that the color of the somites of all insects is limited to either red, green or blue, but the color of the somites changes every second, and finally all the somites become the same color and settle down. In some cases, the color seemed to keep changing no matter how long I waited. <image> As I investigated, I found that all the body segments usually have the same color, but after being surprised or excited by something, the color of the body segments changes without permission. It turns out that once the color of the segment changes, it will continue to change until all the segment are the same color again. Dr. A was curiously observing how the color changed when he caught and excited many of these insects, but the way the color changed during the color change is as follows. I noticed that there is regularity. * The color changes only in one pair of two adjacent somites of different colors, and the colors of the other somites do not change. However, when there are multiple such pairs, it is not possible to predict in advance which pair will change color. * Such a pair will change to a color that is neither of the colors of the two segmentes at the same time (for example, if the green and red segment are adjacent, they will change to blue at the same time). <image> The figure above shows all the changes in the color of the insects up to 2 seconds later. Suppose you have an insect that has the color shown in the upper part of the figure. At this time, there are 3 pairs of adjacent somites of different colors, so after 1 second, it will change to one of the 3 colors drawn side by side in the middle row. After 1 second, all the segments can turn green after 2 seconds (second from the left in the lower row of the figure) when they change to the two on the left side of the middle row. On the other hand, when it changes like the one on the far right in the middle row after 1 second, all the segments do not change to the same color after 2 seconds. He decided to predict if all the insect segments in front of him could be the same color, and if so, at the earliest, how many seconds later. Create a program that takes the color sequence of the insect body segments in front of you as input and outputs the shortest time required for all the insect body segments to have the same color in seconds. However, if there is no possibility that the colors will be the same, output "NA (half-width uppercase letters)". In addition, the color sequence of the insect body segment is represented by a character string consisting of r (red), g (green), and b (blue) of 2 or more and 10 or less. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. For each dataset, one string is given on one line that represents information about the insect's somites. The number of datasets does not exceed 100. Output For each dataset, the minimum time (integer in seconds) or NA required for all segment colors to be the same is output on one line. Example Input rbgrg rbbgbbr bgr bgrbrgbr bggrgbgrr gbrggrbggr rrrrr bgbr 0 Output 5 7 1 6 NA 8 0 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. There are N camels numbered 1 through N. The weight of Camel i is w_i. You will arrange the camels in a line and make them cross a bridge consisting of M parts. Before they cross the bridge, you can choose their order in the line - it does not have to be Camel 1, 2, \ldots, N from front to back - and specify the distance between each adjacent pair of camels to be any non-negative real number. The camels will keep the specified distances between them while crossing the bridge. The i-th part of the bridge has length l_i and weight capacity v_i. If the sum of the weights of camels inside a part (excluding the endpoints) exceeds v_i, the bridge will collapse. Determine whether it is possible to make the camels cross the bridge without it collapsing. If it is possible, find the minimum possible distance between the first and last camels in the line in such a case. It can be proved that the answer is always an integer, so print an integer. -----Constraints----- - All values in input are integers. - 2 \leq N \leq 8 - 1 \leq M \leq 10^5 - 1 \leq w_i,l_i,v_i \leq 10^8 -----Input----- Input is given from Standard Input in the following format: N M w_1 w_2 \cdots w_N l_1 v_1 \vdots l_M v_M -----Output----- If the bridge will unavoidably collapse when the camels cross the bridge, print -1. Otherwise, print the minimum possible distance between the first and last camels in the line when the camels cross the bridge without it collapsing. -----Sample Input----- 3 2 1 4 2 10 4 2 6 -----Sample Output----- 10 - It is possible to make the camels cross the bridge without it collapsing by, for example, arranging them in the order 1, 3, 2 from front to back, and setting the distances between them to be 0, 10. - For Part 1 of the bridge, there are moments when only Camel 1 and 3 are inside the part and moments when only Camel 2 is inside the part. In both cases, the sum of the weights of camels does not exceed 4 - the weight capacity of Part 1 - so there is no collapse. - For Part 2 of the bridge, there are moments when only Camel 1 and 3 are inside the part and moments when only Camel 2 is inside the part. In both cases, the sum of the weights of camels does not exceed 6 - the weight capacity of Part 2 - so there is no collapse. - Note that the distance between two camels may be 0 and that camels on endpoints of a part are not considered to be inside the part. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 as well. After IOI Ilya decided to make a business. He found a social network called "TheScorpyBook.com". It currently has N registered users. As in any social network two users can be friends. Ilya wants the world to be as connected as possible, so he wants to suggest friendship to some pairs of users. He will suggest user u to have a friendship with user v if they are not friends yet and there is a user w who is friends of both of them. Note that u, v and w are different users. Ilya is too busy with IPO these days, so he asks you to count how many friendship suggestions he has to send over his social network.   ------ Input ------ The first line contains an integer number N — the number of users in the network. Next N lines contain N characters each denoting friendship relations. j^{th} character if the i^{th} lines equals one, if users i and j are friends and equals to zero otherwise. This relation is symmetric, i.e. if user a is friend of b then b is also a friend of a.   ------ Output ------ Output a single integer — number of friendship suggestions Ilya has to send.   ------ Constraints ------ $1 ≤ N ≤ 2000$ ------ Example ------ Input: 4 0111 1000 1000 1000 Output: 6 ------ Explanation ------ Each of users [2, 3, 4] should receive two friendship suggestions, while user 1 does not need any, since he already has all other users in his friend-list. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy. Input The only line contains three integers n, a and b (0 ≤ a, b < n ≤ 100). Output Print the single number — the number of the sought positions. Examples Input 3 1 1 Output 2 Input 5 2 3 Output 3 Note The possible positions in the first sample are: 2 and 3 (if we number the positions starting with 1). In the second sample they are 3, 4 and 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. We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds. Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation: * If s does not contain X_i: add X_i to the end of s. * If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s. Find the elements of s after Snuke finished the operations. Constraints * 1 \leq N \leq 2 \times 10^5 * 1 \leq K \leq 10^{12} * 1 \leq A_i \leq 2 \times 10^5 * All values in input are integers. Input Input is given from Standard Input in the following format: N K A_0 A_1 \cdots A_{N-1} Output Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between. Examples Input 3 2 1 2 3 Output 2 3 Input 5 10 1 2 3 2 3 Output 3 Input 6 1000000000000 1 1 2 2 3 3 Output Input 11 97 3 1 4 1 5 9 2 6 5 3 5 Output 9 2 6 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i. In the contest, N foods numbered 1 through N will be presented, and the difficulty of Food i is F_i. The details of the contest are as follows: - A team should assign one member to each food, and should not assign the same member to multiple foods. - It will take x \times y seconds for a member to finish the food, where x is the consumption coefficient of the member and y is the difficulty of the dish. - The score of a team is the longest time it takes for an individual member to finish the food. Before the contest, Takahashi's team decided to do some training. In one set of training, a member can reduce his/her consumption coefficient by 1, as long as it does not go below 0. However, for financial reasons, the N members can do at most K sets of training in total. What is the minimum possible score of the team, achieved by choosing the amounts of members' training and allocating the dishes optimally? -----Constraints----- - All values in input are integers. - 1 \leq N \leq 2 \times 10^5 - 0 \leq K \leq 10^{18} - 1 \leq A_i \leq 10^6\ (1 \leq i \leq N) - 1 \leq F_i \leq 10^6\ (1 \leq i \leq N) -----Input----- Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N F_1 F_2 ... F_N -----Output----- Print the minimum possible score of the team. -----Sample Input----- 3 5 4 2 1 2 3 1 -----Sample Output----- 2 They can achieve the score of 2, as follows: - Member 1 does 4 sets of training and eats Food 2 in (4-4) \times 3 = 0 seconds. - Member 2 does 1 set of training and eats Food 3 in (2-1) \times 1 = 1 second. - Member 3 does 0 sets of training and eats Food 1 in (1-0) \times 2 = 2 seconds. They cannot achieve a score of less than 2, 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. You are given two integers $n$ and $m$ ($m < n$). Consider a convex regular polygon of $n$ vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). [Image] Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with $m$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. The next $t$ lines describe test cases. Each test case is given as two space-separated integers $n$ and $m$ ($3 \le m < n \le 100$) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build. -----Output----- For each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with $m$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise. -----Example----- Input 2 6 3 7 3 Output YES NO -----Note----- $0$ The first test case of the example It can be shown that the answer for the second test case of the example is "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. Arkady decided to buy roses for his girlfriend. A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color. Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is b_{i}, and its color is c_{i} ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose). Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet. -----Input----- The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy. The second line contains a sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10 000), where b_{i} equals the beauty of the i-th rose. The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where c_{i} denotes the color of the i-th rose: 'W' denotes white, 'O'  — orange, 'R' — red. -----Output----- Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1. -----Examples----- Input 5 3 4 3 4 1 6 RROWW Output 11 Input 5 2 10 20 14 20 11 RRRRR Output -1 Input 11 5 5 6 3 2 3 4 7 5 4 5 6 RWOORWORROW Output 28 -----Note----- In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11. In the second example Arkady can not buy a bouquet because all roses have the same color. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$. Find out the non-negative remainder of division of $\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$ by $10^{9} + 9$. Note that the modulo is unusual! -----Input----- The first line contains four integers $n, a, b$ and $k$ $(1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5})$. The second line contains a sequence of length $k$ consisting of characters '+' and '-'. If the $i$-th character (0-indexed) is '+', then $s_{i} = 1$, otherwise $s_{i} = -1$. Note that only the first $k$ members of the sequence are given, the rest can be obtained using the periodicity property. -----Output----- Output a single integer — value of given expression modulo $10^{9} + 9$. -----Examples----- Input 2 2 3 3 +-+ Output 7 Input 4 1 5 1 - Output 999999228 -----Note----- In the first example: $(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i})$ = $2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2}$ = 7 In the second example: $(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and a_{i} is the length of i-th segment. No two segments touch or intersect. For example: If x = 6 and the crossword is 111011, then its encoding is an array {3, 2}; If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1}; If x = 5 and the crossword is 11111, then its encoding is an array {5}; If x = 5 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it! -----Input----- The first line contains two integer numbers n and x (1 ≤ n ≤ 100000, 1 ≤ x ≤ 10^9) — the number of elements in the encoding and the length of the crossword Mishka picked. The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10000) — the encoding. -----Output----- Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO. -----Examples----- Input 2 4 1 3 Output NO Input 3 10 3 3 2 Output YES Input 2 10 1 3 Output NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. Figure 4: another example of a path that does not satisfy the condition -----Constraints----- - 2≦N≦8 - 0≦M≦N(N-1)/2 - 1≦a_i<b_i≦N - The given graph contains neither self-loops nor double edges. -----Input----- The input is given from Standard Input in the following format: N M a_1 b_1 a_2 b_2 : a_M b_M -----Output----- Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. -----Sample Input----- 3 3 1 2 1 3 2 3 -----Sample Output----- 2 The given graph is shown in the following figure: The following two paths satisfy the condition: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Example Input mmemewwemeww Output Cat Read the inputs from stdin solve the problem and write the answer to stdout (do 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 coins labeled from 1 to n. Initially, coin c_i is on position i and is facing upwards ((c_1, c_2, ..., c_n) is a permutation of numbers from 1 to n). You can do some operations on these coins. In one operation, you can do the following: * Choose 2 distinct indices i and j. * Then, swap the coins on positions i and j. * Then, flip both coins on positions i and j. (If they are initially faced up, they will be faced down after the operation and vice versa) Construct a sequence of at most n+1 operations such that after performing all these operations the coin i will be on position i at the end, facing up. Note that you do not need to minimize the number of operations. Input The first line contains an integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of coins. The second line contains n integers c_1,c_2,...,c_n (1 ≤ c_i ≤ n, c_i ≠ c_j for i≠ j). Output In the first line, output an integer q (0 ≤ q ≤ n+1) — the number of operations you used. In the following q lines, output two integers i and j (1 ≤ i, j ≤ n, i ≠ j) — the positions you chose for the current operation. Examples Input 3 2 1 3 Output 3 1 3 3 2 3 1 Input 5 1 2 3 4 5 Output 0 Note Let coin i facing upwards be denoted as i and coin i facing downwards be denoted as -i. The series of moves performed in the first sample changes the coins as such: * [~~~2,~~~1,~~~3] * [-3,~~~1,-2] * [-3,~~~2,-1] * [~~~1,~~~2,~~~3] In the second sample, the coins are already in their correct positions so there is no need to swap. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Devu has an array A consisting of N positive integers. He would like to perform following operation on array. - Pick some two elements a, b in the array (a could be same as b, but their corresponding indices in the array should not be same). Remove both the elements a and b and instead add a number x such that x lies between min(a, b) and max(a, b), both inclusive, (i.e. min(a, b) ≤ x ≤ max(a, b)). Now, as you know after applying the above operation N - 1 times, Devu will end up with a single number in the array. He is wondering whether it is possible to do the operations in such a way that he ends up a number t. He asks your help in answering Q such queries, each of them will contain an integer t and you have to tell whether it is possible to end up t. -----Input----- There is only one test case per test file. First line of the input contains two space separated integers N, Q denoting number of elements in A and number of queries for which Devu asks your help, respectively Second line contains N space separated integers denoting the content of array A. Each of the next Q lines, will contain a single integer t corresponding to the query. -----Output----- Output Q lines, each containing "Yes" or "No" (both without quotes) corresponding to the answer of corresponding query. -----Constraints----- - 1 ≤ N, Q ≤ 105 - 0 ≤ t ≤ 109 -----Subtasks----- Subtask #1 : 30 points - 1 ≤ Ai ≤ 2 Subtask #2 : 70 points - 1 ≤ Ai ≤ 109 -----Example----- Input 1: 1 2 1 1 2 Output: Yes No Input 2: 2 4 1 3 1 2 3 4 Output: Yes Yes Yes No -----Explanation----- In the first example, Devu can't apply any operation. So the final element in the array will be 1 itself. In the second example, Devu can replace 1 and 3 with any of the numbers among 1, 2, 3. Hence final element of the array could be 1, 2 or 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. problem JOI, who has been suffering from his winter vacation homework every time, decided to do his homework systematically this time. Homework is a national language and math drill, with a national language drill on page A and a math drill on page B. JOI can advance the Japanese drill up to C pages and the math drill up to D pages a day, but if he does his homework, he can't play that day. There are L days during the winter vacation, and JOI must finish his homework during the winter vacation. Create a program that asks how many days JOI can play during the winter vacation. input The input consists of 5 lines, with one positive integer written on each line. The integer L (2 ≤ L ≤ 40) is written on the first line, which indicates the number of days of winter vacation. The integer A (1 ≤ A ≤ 1000) is written on the second line, which indicates the number of pages of the Japanese drill. The integer B (1 ≤ B ≤ 1000) is written on the third line, which indicates the number of pages of the math drill. The integer C (1 ≤ C ≤ 100) is written on the 4th line, which indicates the maximum number of pages of a national language drill that JOI can advance in a day. The integer D (1 ≤ D ≤ 100) is written on the 5th line, which indicates the maximum number of pages of the math drill that JOI can advance in a day. However, given the input data, JOI is guaranteed to be able to finish his homework during the winter vacation and play for at least a day. Example Input 20 25 30 6 8 Output 15 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You've come to your favorite store Infinitesco to buy some ice tea. The store sells ice tea in bottles of different volumes at different costs. Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen. The store has an infinite supply of bottles of each type. You want to buy exactly N liters of ice tea. How many yen do you have to spend? Constraints * 1 \leq Q, H, S, D \leq 10^8 * 1 \leq N \leq 10^9 * All input values are integers. Input Input is given from Standard Input in the following format: Q H S D N Output Print the smallest number of yen you have to spend to buy exactly N liters of ice tea. Examples Input 20 30 70 90 3 Output 150 Input 10000 1000 100 10 1 Output 100 Input 10 100 1000 10000 1 Output 40 Input 12345678 87654321 12345678 87654321 123456789 Output 1524157763907942 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression. To achieve the goal, the gym teacher ordered a lot of magical buns from the dining room. The magic buns come in two types: when a student eats one magic bun of the first type, his height increases by one, when the student eats one magical bun of the second type, his height decreases by one. The physical education teacher, as expected, cares about the health of his students, so he does not want them to eat a lot of buns. More precisely, he wants the maximum number of buns eaten by some student to be minimum. Help the teacher, get the maximum number of buns that some pupils will have to eat to achieve the goal of the teacher. Also, get one of the possible ways for achieving the objective, namely, the height of the lowest student in the end and the step of the resulting progression. -----Input----- The single line contains integer n (2 ≤ n ≤ 10^3) — the number of students. The second line contains n space-separated integers — the heights of all students. The height of one student is an integer which absolute value doesn't exceed 10^4. -----Output----- In the first line print the maximum number of buns eaten by some student to achieve the teacher's aim. In the second line, print two space-separated integers — the height of the lowest student in the end and the step of the progression. Please, pay attention that the step should be non-negative. If there are multiple possible answers, you can print any of them. -----Examples----- Input 5 -3 -4 -2 -3 3 Output 2 -3 1 Input 5 2 -3 -1 -4 3 Output 1 -4 2 -----Note----- Lets look at the first sample. We can proceed in the following manner: don't feed the 1-st student, his height will stay equal to -3; give two buns of the first type to the 2-nd student, his height become equal to -2; give two buns of the first type to the 3-rd student, his height become equal to 0; give two buns of the first type to the 4-th student, his height become equal to -1; give two buns of the second type to the 5-th student, his height become equal to 1. To sum it up, when the students line up in non-decreasing height it will be an arithmetic progression: -3, -2, -1, 0, 1. The height of the lowest student is equal to -3, the step of the progression is equal to 1. The maximum number of buns eaten by one student is equal to 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 can see a clock in the mirror from the place he sits in the office. When he saw the clock shows 12:22 1 2 3 4 5 6 7 8 9 10 11 12 He knows that the time is 11:38 1 2 3 4 5 6 7 8 9 10 11 12 in the same manner: 05:25 --> 06:35 01:50 --> 10:10 11:58 --> 12:02 12:01 --> 11:59 Please complete the function `WhatIsTheTime(timeInMirror)`, where `timeInMirror` is the mirrored time (what Peter sees) as string. Return the _real_ time as a string. Consider hours to be between 1 <= hour < 13. So there is no 00:20, instead it is 12:20. There is no 13:20, instead it is 01:20. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even? Input The first line contains the only integer n (1 ≤ n ≤ 100) — the number of cookie bags Anna and Maria have. The second line contains n integers ai (1 ≤ ai ≤ 100) — the number of cookies in the i-th bag. Output Print in the only line the only number — the sought number of ways. If there are no such ways print 0. Examples Input 1 1 Output 1 Input 10 1 2 2 3 4 4 4 2 2 2 Output 8 Input 11 2 2 2 2 2 2 2 2 2 2 99 Output 1 Note In the first sample Olga should take the only bag so that the twins ended up with the even number of cookies. In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies — 5 + 3 = 8 ways in total. In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2 * 9 + 99 = 117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 integer N, find the base -2 representation of N. Here, S is the base -2 representation of N when the following are all satisfied: - S is a string consisting of 0 and 1. - Unless S = 0, the initial character of S is 1. - Let S = S_k S_{k-1} ... S_0, then S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S_k \times (-2)^k = N. It can be proved that, for any integer M, the base -2 representation of M is uniquely determined. -----Constraints----- - Every value in input is integer. - -10^9 \leq N \leq 10^9 -----Input----- Input is given from Standard Input in the following format: N -----Output----- Print the base -2 representation of N. -----Sample Input----- -9 -----Sample Output----- 1011 As (-2)^0 + (-2)^1 + (-2)^3 = 1 + (-2) + (-8) = -9, 1011 is the base -2 representation of -9. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible. Input The first line contains an integer N (1 ≤ N ≤ 1000) — the number of bars at Vasya’s disposal. The second line contains N space-separated integers li — the lengths of the bars. All the lengths are natural numbers not exceeding 1000. Output In one line output two numbers — the height of the largest tower and their total number. Remember that Vasya should use all the bars. Examples Input 3 1 2 3 Output 1 3 Input 4 6 5 6 7 Output 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. Treeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town. In Treeland there are 2k universities which are located in different towns. Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done! To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in k pairs should be as large as possible. Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1. -----Input----- The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ n / 2) — the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to n. The second line contains 2k distinct integers u_1, u_2, ..., u_2k (1 ≤ u_{i} ≤ n) — indices of towns in which universities are located. The next n - 1 line contains the description of roads. Each line contains the pair of integers x_{j} and y_{j} (1 ≤ x_{j}, y_{j} ≤ n), which means that the j-th road connects towns x_{j} and y_{j}. All of them are two-way roads. You can move from any town to any other using only these roads. -----Output----- Print the maximum possible sum of distances in the division of universities into k pairs. -----Examples----- Input 7 2 1 5 6 2 1 3 3 2 4 5 3 7 4 3 4 6 Output 6 Input 9 3 3 2 1 6 5 9 8 9 3 2 2 7 3 4 7 6 4 5 2 1 2 8 Output 9 -----Note----- The figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example. [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Pushok the dog has been chasing Imp for a few hours already. $48$ Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and $t_{i} = s$ and $t_{j} = h$. The robot is off at the moment. Imp knows that it has a sequence of strings t_{i} in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation. Help Imp to find the maximum noise he can achieve by changing the order of the strings. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of strings in robot's memory. Next n lines contain the strings t_1, t_2, ..., t_{n}, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 10^5. -----Output----- Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings. -----Examples----- Input 4 ssh hs s hhhs Output 18 Input 2 h s Output 1 -----Note----- The optimal concatenation in the first sample is ssshhshhhs. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Monocarp is playing a computer game. He's going to kill $n$ monsters, the $i$-th of them has $h_i$ health. Monocarp's character has two spells, either of which he can cast an arbitrary number of times (possibly, zero) and in an arbitrary order: choose exactly two alive monsters and decrease their health by $1$; choose a single monster and kill it. When a monster's health becomes $0$, it dies. What's the minimum number of spell casts Monocarp should perform in order to kill all monsters? -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases. The first line of each testcase contains a single integer $n$ ($1 \le n \le 100$) — the number of monsters. The second line contains $n$ integers $h_1, h_2, \dots, h_n$ ($1 \le h_i \le 100$) — the health of each monster. The sum of $n$ over all testcases doesn't exceed $2 \cdot 10^4$. -----Output----- For each testcase, print a single integer — the minimum number of spell casts Monocarp should perform in order to kill all monsters. -----Examples----- Input 3 4 1 2 1 2 3 2 4 2 5 1 2 3 4 5 Output 3 3 5 -----Note----- In the first testcase, the initial health list is $[1, 2, 1, 2]$. Three spells are casted: the first spell on monsters $1$ and $2$ — monster $1$ dies, monster $2$ has now health $1$, new health list is $[0, 1, 1, 2]$; the first spell on monsters $3$ and $4$ — monster $3$ dies, monster $4$ has now health $1$, new health list is $[0, 1, 0, 1]$; the first spell on monsters $2$ and $4$ — both monsters $2$ and $4$ die. In the second testcase, the initial health list is $[2, 4, 2]$. Three spells are casted: the first spell on monsters $1$ and $3$ — both monsters have health $1$ now, new health list is $[1, 4, 1]$; the second spell on monster $2$ — monster $2$ dies, new health list is $[1, 0, 1]$; the first spell on monsters $1$ and $3$ — both monsters $1$ and $3$ die. In the third testcase, the initial health list is $[1, 2, 3, 4, 5]$. Five spells are casted. The $i$-th of them kills the $i$-th monster with the second spell. Health list sequence: $[1, 2, 3, 4, 5]$ $\rightarrow$ $[0, 2, 3, 4, 5]$ $\rightarrow$ $[0, 0, 3, 4, 5]$ $\rightarrow$ $[0, 0, 0, 4, 5]$ $\rightarrow$ $[0, 0, 0, 0, 5]$ $\rightarrow$ $[0, 0, 0, 0, 0]$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In another Kata I came across a weird `sort` function to implement. We had to sort characters as usual ( 'A' before 'Z' and 'Z' before 'a' ) except that the `numbers` had to be sorted **after** the `letters` ( '0' after 'z') !!! (After a couple of hours trying to solve this unusual-sorting-kata I discovered final tests used **usual** sort (digits **before** letters :-) So, the `unusualSort/unusual_sort` function you'll have to code will sort `letters` as usual, but will put `digits` (or one-digit-long `numbers` ) **after** `letters`. ## Examples ```python unusual_sort(["a","z","b"]) # -> ["a","b","z"] as usual unusual_sort(["a","Z","B"]) # -> ["B","Z","a"] as usual //... but ... unusual_sort(["1","z","a"]) # -> ["a","z","1"] unusual_sort(["1","Z","a"]) # -> ["Z","a","1"] unusual_sort([3,2,1"a","z","b"]) # -> ["a","b","z",1,2,3] unusual_sort([3,"2",1,"a","c","b"]) # -> ["a","b","c",1,"2",3] ``` **Note**: `digits` will be sorted **after** "`same-digit-numbers`", eg: `1` is before `"1"`, `"2"` after `2`. ```python unusual_sort([3,"2",1,"1","3",2]) # -> [1,"1",2,"2",3,"3"] ``` You may assume that **argument** will always be an `array/list` of **characters** or **one-digit-long numbers**. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Nick has n bottles of soda left after his birthday. Each bottle is described by two values: remaining amount of soda a_{i} and bottle volume b_{i} (a_{i} ≤ b_{i}). Nick has decided to pour all remaining soda into minimal number of bottles, moreover he has to do it as soon as possible. Nick spends x seconds to pour x units of soda from one bottle to another. Nick asks you to help him to determine k — the minimal number of bottles to store all remaining soda and t — the minimal time to pour soda into k bottles. A bottle can't store more soda than its volume. All remaining soda should be saved. -----Input----- The first line contains positive integer n (1 ≤ n ≤ 100) — the number of bottles. The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100), where a_{i} is the amount of soda remaining in the i-th bottle. The third line contains n positive integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 100), where b_{i} is the volume of the i-th bottle. It is guaranteed that a_{i} ≤ b_{i} for any i. -----Output----- The only line should contain two integers k and t, where k is the minimal number of bottles that can store all the soda and t is the minimal time to pour the soda into k bottles. -----Examples----- Input 4 3 3 4 3 4 7 6 5 Output 2 6 Input 2 1 1 100 100 Output 1 1 Input 5 10 30 5 6 24 10 41 7 8 24 Output 3 11 -----Note----- In the first example Nick can pour soda from the first bottle to the second bottle. It will take 3 seconds. After it the second bottle will contain 3 + 3 = 6 units of soda. Then he can pour soda from the fourth bottle to the second bottle and to the third bottle: one unit to the second and two units to the third. It will take 1 + 2 = 3 seconds. So, all the soda will be in two bottles and he will spend 3 + 3 = 6 seconds to do it. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly a_{i} feet high. [Image] A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group. Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x. -----Input----- The first line of input contains integer n (1 ≤ n ≤ 2 × 10^5), the number of bears. The second line contains n integers separated by space, a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), heights of bears. -----Output----- Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x. -----Examples----- Input 10 1 2 3 4 5 4 3 2 1 6 Output 6 4 4 3 3 2 2 1 1 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya has gotten interested in programming contests in TCMCF+++ rules. On the contest n problems were suggested and every problem had a cost — a certain integral number of points (perhaps, negative or even equal to zero). According to TCMCF+++ rules, only accepted problems can earn points and the overall number of points of a contestant was equal to the product of the costs of all the problems he/she had completed. If a person didn't solve anything, then he/she didn't even appear in final standings and wasn't considered as participant. Vasya understood that to get the maximal number of points it is not always useful to solve all the problems. Unfortunately, he understood it only after the contest was finished. Now he asks you to help him: find out what problems he had to solve to earn the maximal number of points. Input The first line contains an integer n (1 ≤ n ≤ 100) — the number of the suggested problems. The next line contains n space-separated integers ci ( - 100 ≤ ci ≤ 100) — the cost of the i-th task. The tasks' costs may coinсide. Output Print space-separated the costs of the problems that needed to be solved to get the maximal possible number of points. Do not forget, please, that it was necessary to solve at least one problem. If there are several solutions to that problem, print any of them. Examples Input 5 1 2 -3 3 3 Output 3 1 2 3 Input 13 100 100 100 100 100 100 100 100 100 100 100 100 100 Output 100 100 100 100 100 100 100 100 100 100 100 100 100 Input 4 -2 -2 -2 -2 Output -2 -2 -2 -2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has $n$ positions to install lamps, they correspond to the integer numbers from $0$ to $n - 1$ on the OX axis. However, some positions are blocked and no post lamp can be placed there. There are post lamps of different types which differ only by their power. When placed in position $x$, post lamp of power $l$ illuminates the segment $[x; x + l]$. The power of each post lamp is always a positive integer number. The post lamp shop provides an infinite amount of lamps of each type from power $1$ to power $k$. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power $l$ cost $a_l$ each. What is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment $[0; n]$ of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power $3$ in position $n - 1$ (even though its illumination zone doesn't completely belong to segment $[0; n]$). -----Input----- The first line contains three integer numbers $n$, $m$ and $k$ ($1 \le k \le n \le 10^6$, $0 \le m \le n$) — the length of the segment of the street Adilbek wants to illuminate, the number of the blocked positions and the maximum power of the post lamp available. The second line contains $m$ integer numbers $s_1, s_2, \dots, s_m$ ($0 \le s_1 < s_2 < \dots s_m < n$) — the blocked positions. The third line contains $k$ integer numbers $a_1, a_2, \dots, a_k$ ($1 \le a_i \le 10^6$) — the costs of the post lamps. -----Output----- Print the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment $[0; n]$ of the street. If illumintaing the entire segment $[0; n]$ is impossible, print -1. -----Examples----- Input 6 2 3 1 3 1 2 3 Output 6 Input 4 3 4 1 2 3 1 10 100 1000 Output 1000 Input 5 1 5 0 3 3 3 3 3 Output -1 Input 7 4 3 2 4 5 6 3 14 15 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. A valid parentheses sequence is a non-empty string where each character is either '(' or ')', which satisfies the following constraint: You can find a way to repeat erasing adjacent pairs of parentheses '()' until it becomes empty. For example, '(())' and '()((()()))' are valid parentheses sequences, but ')()(' and '(()' are not. Mike has a valid parentheses sequence. He really likes everything about his sequence, except the fact that it is quite long. So Mike has recently decided that he will replace his parentheses sequence with a new one in the near future. But not every valid parentheses sequence will satisfy him. To help you understand his requirements we'll introduce the pseudocode of function F(S): FUNCTION F( S - a valid parentheses sequence ) BEGIN balance = 0 max_balance = 0 FOR index FROM 1 TO LENGTH(S) BEGIN if S[index] == '(' then balance = balance + 1 if S[index] == ')' then balance = balance - 1 max_balance = max( max_balance, balance ) END RETURN max_balance END In other words, F(S) is equal to the maximal balance over all prefixes of S. Let's denote A as Mike's current parentheses sequence, and B as a candidate for a new one. Mike is willing to replace A with B if F(A) is equal to F(B). He would also like to choose B with the minimal possible length amongst ones satisfying the previous condition. If there are several such strings with the minimal possible length, then Mike will choose the least one lexicographically, considering '(' to be less than ')'. Help Mike! -----Input----- The first line of the input contains one integer T denoting the number of testcases to process. The only line of each testcase contains one string A denoting Mike's parentheses sequence. It is guaranteed that A only consists of the characters '(' and ')'. It is also guaranteed that A is a valid parentheses sequence. -----Output----- The output should contain exactly T lines, one line per each testcase in the order of their appearance. The only line of each testcase should contain one string B denoting the valid parentheses sequence that should be chosen by Mike to replace A. -----Constraints----- 1 ≤ T ≤ 5; 1 ≤ |A| ≤ 100000(105). -----Example----- Input: 1 ()((()())) Output: ((())) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of $n$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light. Denis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $g$ seconds green, and then $r$ seconds red, then again $g$ seconds green and so on. Formally, the road can be represented as a segment $[0, n]$. Initially, Denis is at point $0$. His task is to get to point $n$ in the shortest possible time. He knows many different integers $d_1, d_2, \ldots, d_m$, where $0 \leq d_i \leq n$  — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on. Unfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed: He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $\pm 1$ in $1$ second. While doing so, he must always stay inside the segment $[0, n]$. He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $+1$ and he walked on a safety island, then he can change his position by $\pm 1$. Otherwise, he can change his position only by $+1$. Similarly, if in the previous second he changed his position by $-1$, on a safety island he can change position by $\pm 1$, and at any other point by $-1$. At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on. Denis has crossed the road as soon as his coordinate becomes equal to $n$. This task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do. -----Input----- The first line contains two integers $n$ and $m$ $(1 \leq n \leq 10^6, 2 \leq m \leq min(n + 1, 10^4))$  — road width and the number of safety islands. The second line contains $m$ distinct integers $d_1, d_2, \ldots, d_m$ $(0 \leq d_i \leq n)$  — the points where the safety islands are located. It is guaranteed that there are $0$ and $n$ among them. The third line contains two integers $g, r$ $(1 \leq g, r \leq 1000)$  — the time that the green light stays on and the time that the red light stays on. -----Output----- Output a single integer  — the minimum time for which Denis can cross the road with obeying all the rules. If it is impossible to cross the road output $-1$. -----Examples----- Input 15 5 0 3 7 14 15 11 11 Output 45 Input 13 4 0 3 7 13 9 9 Output -1 -----Note----- In the first test, the optimal route is:      for the first green light, go to $7$ and return to $3$. In this case, we will change the direction of movement at the point $7$, which is allowed, since there is a safety island at this point. In the end, we will be at the point of $3$, where there is also a safety island. The next $11$ seconds we have to wait for the red light.      for the second green light reaches $14$. Wait for the red light again.      for $1$ second go to $15$. As a result, Denis is at the end of the road. In total, $45$ seconds are obtained. In the second test, it is impossible to cross the road according to all the rules. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke has an integer sequence A of length N. He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E. The positions of the cuts can be freely chosen. Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively. Snuke is happier when the absolute difference of the maximum and the minimum among P,Q,R,S is smaller. Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S. -----Constraints----- - 4 \leq N \leq 2 \times 10^5 - 1 \leq A_i \leq 10^9 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N A_1 A_2 ... A_N -----Output----- Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S. -----Sample Input----- 5 3 2 4 1 2 -----Sample Output----- 2 If we divide A as B,C,D,E=(3),(2),(4),(1,2), then P=3,Q=2,R=4,S=1+2=3. Here, the maximum and the minimum among P,Q,R,S are 4 and 2, with the absolute difference of 2. We cannot make the absolute difference of the maximum and the minimum less than 2, 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. A sequence of $n$ numbers is called a permutation if it contains all integers from $1$ to $n$ exactly once. For example, the sequences [$3, 1, 4, 2$], [$1$] and [$2,1$] are permutations, but [$1,2,1$], [$0,1$] and [$1,3,4$] — are not. Polycarp lost his favorite permutation and found only some of its elements — the numbers $b_1, b_2, \dots b_m$. He is sure that the sum of the lost elements equals $s$. Determine whether one or more numbers can be appended to the given sequence $b_1, b_2, \dots b_m$ such that the sum of the added numbers equals $s$, and the resulting new array is a permutation? -----Input----- The first line of input contains a single integer $t$ ($1 \le t \le 100$) —the number of test cases. Then the descriptions of the test cases follow. The first line of each test set contains two integers $m$ and $s$ ($1 \le m \le 50$, $1 \le s \le 1000$)—-the number of found elements and the sum of forgotten numbers. The second line of each test set contains $m$ different integers $b_1, b_2 \dots b_m$ ($1 \le b_i \le 50$) — the elements Polycarp managed to find. -----Output----- Print $t$ lines, each of which is the answer to the corresponding test set. Print as the answer YES if you can append several elements to the array $b$, that their sum equals $s$ and the result will be a permutation. Output NO otherwise. You can output the answer in any case (for example, yEs, yes, Yes and YES will be recognized as positive answer). -----Examples----- Input 5 3 13 3 1 4 1 1 1 3 3 1 4 2 2 1 4 3 5 6 1 2 3 4 5 Output YES NO YES NO YES -----Note----- In the test case of the example, $m=3, s=13, b=[3,1,4]$. You can append to $b$ the numbers $6,2,5$, the sum of which is $6+2+5=13$. Note that the final array will become $[3,1,4,6,2,5]$, which is a permutation. In the second test case of the example, $m=1, s=1, b=[1]$. You cannot append one or more numbers to $[1]$ such that their sum equals $1$ and the result is a permutation. In the third test case of the example, $m=3, s=3, b=[1,4,2]$. You can append the number $3$ to $b$. Note that the resulting array will be $[1,4,2,3]$, which is a permutation. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is a triangle formed by three points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$ on a plain. Write a program which prints "YES" if a point $P$ $(x_p, y_p)$ is in the triangle and "NO" if not. Constraints You can assume that: * $ -100 \leq x_1, y_1, x_2, y_2, x_3, y_3, x_p, y_p \leq 100$ * 1.0 $\leq$ Length of each side of a tringle * 0.001 $\leq$ Distance between $P$ and each side of a triangle Input Input consists of several datasets. Each dataset consists of: $x_1$ $y_1$ $x_2$ $y_2$ $x_3$ $y_3$ $x_p$ $y_p$ All the input are real numbers. Input ends with EOF. The number of datasets is less than or equal to 100. Output For each dataset, print "YES" or "NO" in a line. Example Input 0.0 0.0 2.0 0.0 2.0 2.0 1.5 0.5 0.0 0.0 1.0 4.0 5.0 3.0 -1.0 3.0 Output YES NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. # Task You're given a two-dimensional array of integers `matrix`. Your task is to determine the smallest non-negative integer that is not present in this array. # Input/Output - `[input]` 2D integer array `matrix` A non-empty rectangular matrix. `1 ≤ matrix.length ≤ 10` `1 ≤ matrix[0].length ≤ 10` - `[output]` an integer The smallest non-negative integer that is not present in matrix. # Example For ``` matrix = [ [0, 2], [5, 1]]``` the result should be `3` 0,1,2,`(3)`...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. There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i). We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation: * Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates of this ball. If we collected a ball at coordinates (a - p, b - q) in the previous operation, the cost of this operation is 0. Otherwise, including when this is the first time to do this operation, the cost of this operation is 1. Find the minimum total cost required to collect all the balls when we optimally choose p and q. Constraints * 1 \leq N \leq 50 * |x_i|, |y_i| \leq 10^9 * If i \neq j, x_i \neq x_j or y_i \neq y_j. * All values in input are integers. Input Input is given from Standard Input in the following format: N x_1 y_1 : x_N y_N Output Print the minimum total cost required to collect all the balls. Examples Input 2 1 1 2 2 Output 1 Input 3 1 4 4 6 7 8 Output 1 Input 4 1 1 1 2 2 1 2 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. You are given N integers; the i-th of them is A_i. Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 : A_N Output Print the maximum possible sum of the absolute differences between the adjacent elements after arranging the given integers in a row in any order you like. Examples Input 5 6 8 1 2 3 Output 21 Input 6 3 1 4 1 5 9 Output 25 Input 3 5 5 1 Output 8 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Triangular number is the amount of points that can fill equilateral triangle. Example: the number 6 is a triangular number because all sides of a triangle has the same amount of points. ``` Hint! T(n) = n * (n + 1) / 2, n - is the size of one side. T(n) - is the triangular number. ``` Given a number 'T' from interval [1; 2147483646], find if it is triangular number or not. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry. He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1. Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used. Help Sherlock complete this trivial task. -----Input----- The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces. -----Output----- The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them. -----Examples----- Input 3 Output 2 1 1 2 Input 4 Output 2 2 1 1 2 -----Note----- In the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively. In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room n × m meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that its sides are parallel to the office walls. Bob doesn't want to change or rearrange anything, that's why all the squares that will be occupied by the table should be initially free. Bob wants the new table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the maximum possible perimeter of a bargaining table for his office. Input The first line contains 2 space-separated numbers n and m (1 ≤ n, m ≤ 25) — the office room dimensions. Then there follow n lines with m characters 0 or 1 each. 0 stands for a free square meter of the office room. 1 stands for an occupied square meter. It's guaranteed that at least one square meter in the room is free. Output Output one number — the maximum possible perimeter of a bargaining table for Bob's office room. Examples Input 3 3 000 010 000 Output 8 Input 5 4 1100 0000 0000 0000 0000 Output 16 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are two standard ways to represent a graph $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges; Adjacency list representation and Adjacency matrix representation. An adjacency-list representation consists of an array $Adj[|V|]$ of $|V|$ lists, one for each vertex in $V$. For each $u \in V$, the adjacency list $Adj[u]$ contains all vertices $v$ such that there is an edge $(u, v) \in E$. That is, $Adj[u]$ consists of all vertices adjacent to $u$ in $G$. An adjacency-matrix representation consists of $|V| \times |V|$ matrix $A = a_{ij}$ such that $a_{ij} = 1$ if $(i, j) \in E$, $a_{ij} = 0$ otherwise. Write a program which reads a directed graph $G$ represented by the adjacency list, and prints its adjacency-matrix representation. $G$ consists of $n\; (=|V|)$ vertices identified by their IDs $1, 2,.., n$ respectively. Constraints * $1 \leq n \leq 100$ Input In the first line, an integer $n$ is given. In the next $n$ lines, an adjacency list $Adj[u]$ for vertex $u$ are given in the following format: $u$ $k$ $v_1$ $v_2$ ... $v_k$ $u$ is vertex ID and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$. Output As shown in the following sample output, print the adjacent-matrix representation of $G$. Put a single space character between $a_{ij}$. Example Input 4 1 2 2 4 2 1 4 3 0 4 1 3 Output 0 1 0 1 0 0 0 1 0 0 0 0 0 0 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. Given are integers A, B, and N. Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N. Here floor(t) denotes the greatest integer not greater than the real number t. -----Constraints----- - 1 ≤ A ≤ 10^{6} - 1 ≤ B ≤ 10^{12} - 1 ≤ N ≤ 10^{12} - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: A B N -----Output----- Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer. -----Sample Input----- 5 7 4 -----Sample Output----- 2 When x=3, floor(Ax/B)-A×floor(x/B) = floor(15/7) - 5×floor(3/7) = 2. This is the maximum value 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. Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a number from the second bag, and then sums them modulo M. What are the residues modulo M that Ajs cannot obtain with this action? Input The first line contains two positive integer N (1 ≤ N ≤ 200 000) and M (N+1 ≤ M ≤ 10^{9}), denoting the number of the elements in the first bag and the modulus, respectively. The second line contains N nonnegative integers a_1,a_2,…,a_N (0 ≤ a_1<a_2< …< a_N<M), the contents of the first bag. Output In the first line, output the cardinality K of the set of residues modulo M which Ajs cannot obtain. In the second line of the output, print K space-separated integers greater or equal than zero and less than M, which represent the residues Ajs cannot obtain. The outputs should be sorted in increasing order of magnitude. If K=0, do not output the second line. Examples Input 2 5 3 4 Output 1 2 Input 4 1000000000 5 25 125 625 Output 0 Input 2 4 1 3 Output 2 0 2 Note In the first sample, the first bag and the second bag contain \{3,4\} and \{0,1,2\}, respectively. Ajs can obtain every residue modulo 5 except the residue 2: 4+1 ≡ 0, 4+2 ≡ 1, 3+0 ≡ 3, 3+1 ≡ 4 modulo 5. One can check that there is no choice of elements from the first and the second bag which sum to 2 modulo 5. In the second sample, the contents of the first bag are \{5,25,125,625\}, while the second bag contains all other nonnegative integers with at most 9 decimal digits. Every residue modulo 1 000 000 000 can be obtained as a sum of an element in the first bag and an element in the second bag. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 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. Professor Pathfinder is a distinguished authority on the structure of hyperlinks in the World Wide Web. For establishing his hypotheses, he has been developing software agents, which automatically traverse hyperlinks and analyze the structure of the Web. Today, he has gotten an intriguing idea to improve his software agents. However, he is very busy and requires help from good programmers. You are now being asked to be involved in his development team and to create a small but critical software module of his new type of software agents. Upon traversal of hyperlinks, Pathfinder’s software agents incrementally generate a map of visited portions of the Web. So the agents should maintain the list of traversed hyperlinks and visited web pages. One problem in keeping track of such information is that two or more different URLs can point to the same web page. For instance, by typing any one of the following five URLs, your favorite browsers probably bring you to the same web page, which as you may have visited is the home page of the ACM ICPC Ehime contest. http://www.ehime-u.ac.jp/ICPC/ http://www.ehime-u.ac.jp/ICPC http://www.ehime-u.ac.jp/ICPC/../ICPC/ http://www.ehime-u.ac.jp/ICPC/./ http://www.ehime-u.ac.jp/ICPC/index.html Your program should reveal such aliases for Pathfinder’s experiments. Well, . . . but it were a real challenge and to be perfect you might have to embed rather compli- cated logic into your program. We are afraid that even excellent programmers like you could not complete it in five hours. So, we make the problem a little simpler and subtly unrealis- tic. You should focus on the path parts (i.e. /ICPC/, /ICPC, /ICPC/../ICPC/, /ICPC/./, and /ICPC/index.html in the above example) of URLs and ignore the scheme parts (e.g. http://), the server parts (e.g. www.ehime-u.ac.jp), and other optional parts. You should carefully read the rules described in the sequel since some of them may not be based on the reality of today’s Web and URLs. Each path part in this problem is an absolute pathname, which specifies a path from the root directory to some web page in a hierarchical (tree-shaped) directory structure. A pathname always starts with a slash (/), representing the root directory, followed by path segments delim- ited by a slash. For instance, /ICPC/index.html is a pathname with two path segments ICPC and index.html. All those path segments but the last should be directory names and the last one the name of an ordinary file where a web page is stored. However, we have one exceptional rule: an ordinary file name index.html at the end of a pathname may be omitted. For instance, a pathname /ICPC/index.html can be shortened to /ICPC/, if index.html is an existing ordinary file name. More precisely, if ICPC is the name of an existing directory just under the root and index.html is the name of an existing ordinary file just under the /ICPC directory, /ICPC/index.html and /ICPC/ refer to the same web page. Furthermore, the last slash following the last path segment can also be omitted. That is, for instance, /ICPC/ can be further shortened to /ICPC. However, /index.html can only be abbreviated to / (a single slash). You should pay special attention to path segments consisting of a single period (.) or a double period (..), both of which are always regarded as directory names. The former represents the directory itself and the latter represents its parent directory. Therefore, if /ICPC/ refers to some web page, both /ICPC/./ and /ICPC/../ICPC/ refer to the same page. Also /ICPC2/../ICPC/ refers to the same page if ICPC2 is the name of an existing directory just under the root; otherwise it does not refer to any web page. Note that the root directory does not have any parent directory and thus such pathnames as /../ and /ICPC/../../index.html cannot point to any web page. Your job in this problem is to write a program that checks whether two given pathnames refer to existing web pages and, if so, examines whether they are the same. Input The input consists of multiple datasets. The first line of each dataset contains two positive integers N and M, both of which are less than or equal to 100 and are separated by a single space character. The rest of the dataset consists of N + 2M lines, each of which contains a syntactically correct pathname of at most 100 characters. You may assume that each path segment enclosed by two slashes is of length at least one. In other words, two consecutive slashes cannot occur in any pathname. Each path segment does not include anything other than alphanumerical characters (i.e. ‘a’-‘z’, ‘A’-‘Z’, and ‘0’-‘9’) and periods (‘.’). The first N pathnames enumerate all the web pages (ordinary files). Every existing directory name occurs at least once in these pathnames. You can assume that these pathnames do not include any path segments consisting solely of single or double periods and that the last path segments are ordinary file names. Therefore, you do not have to worry about special rules for index.html and single/double periods. You can also assume that no two of the N pathnames point to the same page. Each of the following M pairs of pathnames is a question: do the two pathnames point to the same web page? These pathnames may include single or double periods and may be terminated by a slash. They may include names that do not correspond to existing directories or ordinary files. Two zeros in a line indicate the end of the input. Output For each dataset, your program should output the M answers to the M questions, each in a separate line. Each answer should be “yes” if both point to the same web page, “not found” if at least one of the pathnames does not point to any one of the first N web pages listed in the input, or “no” otherwise. Example Input 5 6 /home/ACM/index.html /ICPC/index.html /ICPC/general.html /ICPC/japanese/index.html /ICPC/secret/confidential/2005/index.html /home/ACM/ /home/ICPC/../ACM/ /ICPC/secret/ /ICPC/secret/index.html /ICPC /ICPC/../ICPC/index.html /ICPC /ICPC/general.html /ICPC/japanese/.././ /ICPC/japanese/./../ /home/ACM/index.html /home/ACM/index.html/ 1 4 /index.html/index.html / /index.html/index.html /index.html /index.html/index.html /.. /index.html/../.. /index.html/ /index.html/index.html/.. 0 0 Output not found not found yes no yes not found not found yes not found not found Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. From Wikipedia : "The n-back task is a continuous performance task that is commonly used as an assessment in cognitive neuroscience to measure a part of working memory and working memory capacity. [...] The subject is presented with a sequence of stimuli, and the task consists of indicating when the current stimulus matches the one from n steps earlier in the sequence. The load factor n can be adjusted to make the task more or less difficult." In this kata, your task is to "teach" your computer to do the n-back task. Specifically, you will be implementing a function that counts the number of "targets" (stimuli that match the one from n steps earlier) in a sequence of digits. Your function will take two parameters : n, a positive integer equal to the number of steps to look back to find a match sequence, a sequence of digits containing 0 or more targets A few hints : The first digit in a sequence can never be a target Targets can be "chained" together (e.g., for n = 1 and sequence = [1, 1, 1], there are 2 targets) Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first. Consider the 2D plane. There is a token which is initially at $(0,0)$. In one move a player must increase either the $x$ coordinate or the $y$ coordinate of the token by exactly $k$. In doing so, the player must ensure that the token stays within a (Euclidean) distance $d$ from $(0,0)$. In other words, if after a move the coordinates of the token are $(p,q)$, then $p^2 + q^2 \leq d^2$ must hold. The game ends when a player is unable to make a move. It can be shown that the game will end in a finite number of moves. If both players play optimally, determine who will win. -----Input----- The first line contains a single integer $t$ ($1 \leq t \leq 100$) — the number of test cases. The only line of each test case contains two space separated integers $d$ ($1 \leq d \leq 10^5$) and $k$ ($1 \leq k \leq d$). -----Output----- For each test case, if Ashish wins the game, print "Ashish", otherwise print "Utkarsh" (without the quotes). -----Examples----- Input 5 2 1 5 2 10 3 25 4 15441 33 Output Utkarsh Ashish Utkarsh Utkarsh Ashish -----Note----- In the first test case, one possible sequence of moves can be $(0, 0) \xrightarrow{\text{Ashish }} (0, 1) \xrightarrow{\text{Utkarsh }} (0, 2)$. Ashish has no moves left, so Utkarsh wins. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke loves constructing integer sequences. There are N piles of stones, numbered 1 through N. The pile numbered i consists of a_i stones. Snuke will construct an integer sequence s of length Σa_i, as follows: - Among the piles with the largest number of stones remaining, let x be the index of the pile with the smallest index. Append x to the end of s. - Select a pile with one or more stones remaining, and remove a stone from that pile. - If there is a pile with one or more stones remaining, go back to step 1. Otherwise, terminate the process. We are interested in the lexicographically smallest sequence that can be constructed. For each of the integers 1,2,3,...,N, how many times does it occur in the lexicographically smallest sequence? -----Constraints----- - 1 ≤ N ≤ 10^{5} - 1 ≤ a_i ≤ 10^{9} -----Input----- The input is given from Standard Input in the following format: N a_1 a_2 ... a_{N} -----Output----- Print N lines. The i-th line should contain the number of the occurrences of the integer i in the lexicographically smallest sequence that can be constructed. -----Sample Input----- 2 1 2 -----Sample Output----- 2 1 The lexicographically smallest sequence is constructed as follows: - Since the pile with the largest number of stones remaining is pile 2, append 2 to the end of s. Then, remove a stone from pile 2. - Since the piles with the largest number of stones remaining are pile 1 and 2, append 1 to the end of s (we take the smallest index). Then, remove a stone from pile 2. - Since the pile with the largest number of stones remaining is pile 1, append 1 to the end of s. Then, remove a stone from pile 1. The resulting sequence is (2,1,1). In this sequence, 1 occurs twice, and 2 occurs once. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are two persons, numbered 0 and 1, and a variable x whose initial value is 0. The two persons now play a game. The game is played in N rounds. The following should be done in the i-th round (1 \leq i \leq N): * Person S_i does one of the following: * Replace x with x \oplus A_i, where \oplus represents bitwise XOR. * Do nothing. Person 0 aims to have x=0 at the end of the game, while Person 1 aims to have x \neq 0 at the end of the game. Determine whether x becomes 0 at the end of the game when the two persons play optimally. Solve T test cases for each input file. Constraints * 1 \leq T \leq 100 * 1 \leq N \leq 200 * 1 \leq A_i \leq 10^{18} * S is a string of length N consisting of `0` and `1`. * All numbers in input are integers. Input Input is given from Standard Input in the following format. The first line is as follows: T Then, T test cases follow. Each test case is given in the following format: N A_1 A_2 \cdots A_N S Output For each test case, print a line containing `0` if x becomes 0 at the end of the game, and `1` otherwise. Example Input 3 2 1 2 10 2 1 1 10 6 2 3 4 5 6 7 111000 Output 1 0 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. For given three integers $a, b, c$, print the minimum value and the maximum value. Constraints * $-1,000,000,000 \leq a, b, c \leq 1,000,000,000$ Input The input is given in the following format. $a \; b \; c\;$ Three integers $a, b, c$ are given in a line. Output Print the minimum and maximum values separated by a space in a line. Example Input 4 5 3 Output 3 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. Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with? Input The first line contains two integers n and k (1 ≤ n ≤ 200 000, 0 ≤ k ≤ n) — the number of digits in the decimal representation of S and the maximum allowed number of changed digits. The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes. Output Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits. Examples Input 5 3 51528 Output 10028 Input 3 2 102 Output 100 Input 1 1 1 Output 0 Note A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1. Constraints * 1\leq N,K\leq 100 * N and K are integers. Input Input is given from Standard Input in the following format: N K Output If we can choose K integers as above, print `YES`; otherwise, print `NO`. Examples Input 3 2 Output YES Input 5 5 Output NO Input 31 10 Output YES Input 10 90 Output NO Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is an array with n elements a_1, a_2, ..., a_{n} and the number x. In one operation you can select some i (1 ≤ i ≤ n) and replace element a_{i} with a_{i} & x, where & denotes the bitwise and operation. You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that a_{i} = a_{j}. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply. -----Input----- The first line contains integers n and x (2 ≤ n ≤ 100 000, 1 ≤ x ≤ 100 000), number of elements in the array and the number to and with. The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 100 000), the elements of the array. -----Output----- Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible. -----Examples----- Input 4 3 1 2 3 7 Output 1 Input 2 228 1 1 Output 0 Input 3 7 1 2 3 Output -1 -----Note----- In the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move. In the second example the array already has two equal elements. In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Chef has prepared the appetizers in the shapes of letters to spell a special message for the guests. There are n appetizers numbered from 0 to n-1 such that if the appetizers are arrayed in this order, they will display the message. The Chef plans to display them in this order on a table that can be viewed by all guests as they enter. The appetizers will only be served once all guests are seated. The appetizers are not necessarily finished in the same order as they are numbered. So, when an appetizer is finished the Chef will write the number on a piece of paper and place it beside the appetizer on a counter between the kitchen and the restaurant. A server will retrieve this appetizer and place it in the proper location according to the number written beside it. The Chef has a penchant for binary numbers. The number of appetizers created is a power of 2, say n = 2^{k}. Furthermore, he has written the number of the appetizer in binary with exactly k bits. That is, binary numbers with fewer than k bits are padded on the left with zeros so they are written with exactly k bits. Unfortunately, this has unforseen complications. A binary number still "looks" binary when it is written upside down. For example, the binary number "0101" looks like "1010" when read upside down and the binary number "110" looks like "011" (the Chef uses simple vertical lines to denote a 1 bit). The Chef didn't realize that the servers would read the numbers upside down so he doesn't rotate the paper when he places it on the counter. Thus, when the server picks up an appetizer they place it the location indexed by the binary number when it is read upside down. You are given the message the chef intended to display and you are to display the message that will be displayed after the servers move all appetizers to their locations based on the binary numbers they read. ------ Input ------ The first line consists of a single integer T ≤ 25 indicating the number of test cases to follow. Each test case consists of a single line beginning with an integer 1 ≤ k ≤ 16 followed by a string of precisely 2^{k} characters. The integer and the string are separated by a single space. The string has no spaces and is composed only of lower case letters from a to z. ------ Output ------ For each test case you are to output the scrambled message on a single line. ----- Sample Input 1 ------ 2 2 chef 4 enjoyourapplepie ----- Sample Output 1 ------ cehf eayejpuinpopolre Read the inputs from stdin solve the problem and write the answer to stdout (do 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 observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i. There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j. Obs. i is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road. Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road. How many good observatories are there? -----Constraints----- - 2 \leq N \leq 10^5 - 1 \leq M \leq 10^5 - 1 \leq H_i \leq 10^9 - 1 \leq A_i,B_i \leq N - A_i \neq B_i - Multiple roads may connect the same pair of observatories. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N M H_1 H_2 ... H_N A_1 B_1 A_2 B_2 : A_M B_M -----Output----- Print the number of good observatories. -----Sample Input----- 4 3 1 2 3 4 1 3 2 3 2 4 -----Sample Output----- 2 - From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good. - From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good. - From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good. - From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good. Thus, the good observatories are Obs. 3 and 4, so there are two good observatories. Read the inputs from stdin solve the problem and write the answer to stdout (do 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. All bandits are afraid of Sheriff. Sheriff constantly fights crime, but when bandits lay low, he gets bored and starts to entertain himself. This time Sheriff gathered all the bandits in his garden and ordered them to line up. After the whistle all bandits should change the order in which they stand. Sheriff gave all the bandits numbers from 1 to N. For each place i he determined the unique position j. After whistling the bandit staying on position i should run to the j-th position. Sheriff loved seeing how the bandits move around, and he continued whistling until the evening. He finished the game only when he noticed that the bandits are in the same order in which they were standing originally. Now the Sheriff asks the question: How many times has he whistled?   ------ Input ------ The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the number of bandits. The second line contains N space-separated integers A_{1}, A_{2}, ..., A_{N} denoting that the bandit staying on position i should run to the A_{i}-th position after the whistle.   ------ Output ------ For each test case, output a single line containing number of times the sheriff had to whistle, print it modulo 10^{9} + 7.   ------ Constraints ------ $1 ≤ T ≤ 5$ $1 ≤ N ≤ 100000$ $All A_{i} are distinct numbers from 1 to N$   ----- Sample Input 1 ------ 2 3 1 2 3 5 2 3 1 5 4 ----- Sample Output 1 ------ 1 6 ----- explanation 1 ------ Example case 2. the bandits positions are: 0. 1 2 3 4 5 1. 3 1 2 5 4 2. 2 3 1 4 5 3. 1 2 3 5 4 4. 3 1 2 4 5 5. 2 3 1 5 4 6. 1 2 3 4 5. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $(0, 0)$ on an infinite grid. You also have the sequence of instructions of this robot. It is written as the string $s$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $(x, y)$ right now, he can move to one of the adjacent cells (depending on the current instruction). If the current instruction is 'L', then the robot can move to the left to $(x - 1, y)$; if the current instruction is 'R', then the robot can move to the right to $(x + 1, y)$; if the current instruction is 'U', then the robot can move to the top to $(x, y + 1)$; if the current instruction is 'D', then the robot can move to the bottom to $(x, y - 1)$. You've noticed the warning on the last page of the manual: if the robot visits some cell (except $(0, 0)$) twice then it breaks. So the sequence of instructions is valid if the robot starts in the cell $(0, 0)$, performs the given instructions, visits no cell other than $(0, 0)$ two or more times and ends the path in the cell $(0, 0)$. Also cell $(0, 0)$ should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: "UD", "RL", "UUURULLDDDDLDDRRUU", and the following are considered invalid: "U" (the endpoint is not $(0, 0)$) and "UUDD" (the cell $(0, 1)$ is visited twice). The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain. Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric). You have to answer $q$ independent test cases. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 2 \cdot 10^4$) — the number of test cases. The next $q$ lines contain test cases. The $i$-th test case is given as the string $s$ consisting of at least $1$ and no more than $10^5$ characters 'L', 'R', 'U' and 'D' — the initial sequence of instructions. It is guaranteed that the sum of $|s|$ (where $|s|$ is the length of $s$) does not exceed $10^5$ over all test cases ($\sum |s| \le 10^5$). -----Output----- For each test case print the answer on it. In the first line print the maximum number of remaining instructions. In the second line print the valid sequence of remaining instructions $t$ the robot has to perform. The moves are performed from left to right in the order of the printed sequence. If there are several answers, you can print any. If the answer is $0$, you are allowed to print an empty line (but you can don't print it). -----Example----- Input 6 LRU DURLDRUDRULRDURDDL LRUDDLRUDRUL LLLLRRRR URDUR LLL Output 2 LR 14 RUURDDDDLLLUUR 12 ULDDDRRRUULL 2 LR 2 UD 0 -----Note----- There are only two possible answers in the first test case: "LR" and "RL". The picture corresponding to the second test case: [Image] Note that the direction of traverse does not matter Another correct answer to the third test case: "URDDLLLUURDR". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's imagine that you're playing the following simple computer game. The screen displays n lined-up cubes. Each cube is painted one of m colors. You are allowed to delete not more than k cubes (that do not necessarily go one after another). After that, the remaining cubes join together (so that the gaps are closed) and the system counts the score. The number of points you score equals to the length of the maximum sequence of cubes of the same color that follow consecutively. Write a program that determines the maximum possible number of points you can score. Remember, you may delete no more than k any cubes. It is allowed not to delete cubes at all. Input The first line contains three integers n, m and k (1 ≤ n ≤ 2·105, 1 ≤ m ≤ 105, 0 ≤ k < n). The second line contains n integers from 1 to m — the numbers of cube colors. The numbers of colors are separated by single spaces. Output Print the maximum possible number of points you can score. Examples Input 10 3 2 1 2 1 1 3 2 1 1 2 2 Output 4 Input 10 2 2 1 2 1 2 1 1 2 1 1 2 Output 5 Input 3 1 2 1 1 1 Output 3 Note In the first sample you should delete the fifth and the sixth cubes. In the second sample you should delete the fourth and the seventh cubes. In the third sample you shouldn't delete any cubes. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. British mathematician John Littlewood once said about Indian mathematician Srinivasa Ramanujan that "every positive integer was one of his personal friends." It turns out that positive integers can also be friends with each other! You are given an array a of distinct positive integers. Define a subarray a_i, a_{i+1}, …, a_j to be a friend group if and only if there exists an integer m ≥ 2 such that a_i mod m = a_{i+1} mod m = … = a_j mod m, where x mod y denotes the remainder when x is divided by y. Your friend Gregor wants to know the size of the largest friend group in a. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 2⋅ 10^4). Each test case begins with a line containing the integer n (1 ≤ n ≤ 2 ⋅ 10^5), the size of the array a. The next line contains n positive integers a_1, a_2, …, a_n (1 ≤ a_i ≤ {10}^{18}), representing the contents of the array a. It is guaranteed that all the numbers in a are distinct. It is guaranteed that the sum of n over all test cases is less than 2⋅ 10^5. Output Your output should consist of t lines. Each line should consist of a single integer, the size of the largest friend group in a. Example Input 4 5 1 5 2 4 6 4 8 2 5 10 2 1000 2000 8 465 55 3 54 234 12 45 78 Output 3 3 2 6 Note In the first test case, the array is [1,5,2,4,6]. The largest friend group is [2,4,6], since all those numbers are congruent to 0 modulo 2, so m=2. In the second test case, the array is [8,2,5,10]. The largest friend group is [8,2,5], since all those numbers are congruent to 2 modulo 3, so m=3. In the third case, the largest friend group is [1000,2000]. There are clearly many possible values of m that work. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Our hardworking chef is bored of sleeping in his restaurants. He has decided to settle down. The first thing he must do is to find a suitable location to build a palatial home. Think of the city as a two-dimensional grid. There are N restaurants in the city. Each of the chef's restaurant is a point denoted by (X , Y). A house can be located at a grid point (R, S) if the sum of the distances between this point and each of the restaurants is as small as possible. Find the number of possible house locations in the city to help out chef build a home. More than one restaurant can be located at the same point. Houses and restaurants can be located at the same point. Every house must have integer co-ordinates. In other words, R and S are integers. The distance between two points (A,B) and (C,D) is |A-C| + |B-D|. Here |X| is the absolute function. ------ Input ------ First line in the input contains T, number of test cases. First line of each test case contains N, number of restaurants. Each of the next N lines contain two integers X and Y separated by a space. T ≤ 100 N ≤ 10^{3} -10^{8} ≤ X ≤10^{8} -10^{8} ≤ Y ≤10^{8} ------ Output ------ The number of possible locations (grid points) where houses can be built. ----- Sample Input 1 ------ 3 5 0 0 -1 0 1 0 0 1 0 -1 5 31 11 30 -41 20 14 25 18 25 38 2 0 0 1 1 ----- Sample Output 1 ------ 1 1 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. This is the hard version of the problem. The difference between the versions is that in the easy version all prices $a_i$ are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All $n$ ice spheres are placed in a row and they are numbered from $1$ to $n$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal. An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them. You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. -----Input----- The first line contains a single integer $n$ $(1 \le n \le 10^5)$ — the number of ice spheres in the shop. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^9)$ — the prices of ice spheres. -----Output----- In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. -----Example----- Input 7 1 3 2 2 4 5 4 Output 3 3 1 4 2 4 2 5 -----Note----- In the sample it's not possible to place the ice spheres in any order so that Sage would buy $4$ of them. If the spheres are placed in the order $(3, 1, 4, 2, 4, 2, 5)$, then Sage will buy one sphere for $1$ and two spheres for $2$ each. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has a_{i} apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length). Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses. In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things: eat the apples, if the node is a leaf. move the apples to one of the children, if the node is non-leaf. Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v. Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u, v) and (v, u) are considered to be the same pair. -----Input----- The first line will contain one integer n (2 ≤ n ≤ 10^5) — the number of nodes in the apple tree. The second line will contain n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^7) — the number of apples on each node of the tree. The third line will contain n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_{i} ≤ n) — the parent of each node of the tree. Node i has parent p_{i} (for 2 ≤ i ≤ n). Node 1 is the root of the tree. It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity. -----Output----- On a single line, print the number of different pairs of nodes (u, v), u ≠ v such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u, v) and (v, u) are considered to be the same pair. -----Examples----- Input 3 2 2 3 1 1 Output 1 Input 3 1 2 3 1 1 Output 0 Input 8 7 2 2 5 4 3 1 1 1 1 1 4 4 5 6 Output 4 -----Note----- In the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move. In the second sample, There is no swap that will make Sagheer win the game. Note that Sagheer must make the swap even if he can win with the initial tree. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 One day, mo3tthi and tubuann decided to play a game with magic pockets and biscuits. Now there are $ K $ pockets, numbered $ 1,2, \ ldots, K $. The capacity of the $ i $ th pocket is $ M_i $, which initially contains $ N_i $ biscuits. mo3tthi and tubuann start with mo3tthi and perform the following series of operations alternately. * Choose one pocket. * Perform one of the following operations only once. However, if the number of biscuits in the pocket selected as a result of the operation exceeds the capacity of the pocket, the operation cannot be performed. * Stroking the selected pocket. Magical power increases the number of biscuits in your chosen pocket by $ 1 $. * Hit the selected pocket. The number of biscuits in the pocket chosen by magical power is doubled by $ 2 $. The game ends when you can't operate it, the person who can't operate loses, and the person who doesn't can win. You, a friend of mo3tthi, were asked by mo3tthi in advance if you could decide if you could win this game. For mo3tthi, make a program to determine if mo3tthi can definitely win this game. Constraints The input satisfies the following conditions. * $ 1 \ leq K \ leq 10 ^ 5 $ * $ 1 \ leq N_i \ leq M_i \ leq 10 ^ {18} $ * All inputs are integers Input The input is given in the following format. $ K $ $ N_1 $ $ M_1 $ $ \ vdots $ $ N_K $ $ M_K $ Output When mo3tthi acts optimally, "mo3tthi" is output on one line if he can win, and "tubuann" is output otherwise. Examples Input 1 2 4 Output mo3tthi Input 2 2 3 3 8 Output tubuann Input 10 2 8 5 9 7 20 8 41 23 48 90 112 4 5 7 7 2344 8923 1 29 Output mo3tthi Read the inputs from stdin solve the problem and write the answer to stdout (do 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 blocks, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), Block i has a weight of w_i, a solidness of s_i and a value of v_i. Taro has decided to build a tower by choosing some of the N blocks and stacking them vertically in some order. Here, the tower must satisfy the following condition: * For each Block i contained in the tower, the sum of the weights of the blocks stacked above it is not greater than s_i. Find the maximum possible sum of the values of the blocks contained in the tower. Constraints * All values in input are integers. * 1 \leq N \leq 10^3 * 1 \leq w_i, s_i \leq 10^4 * 1 \leq v_i \leq 10^9 Input Input is given from Standard Input in the following format: N w_1 s_1 v_1 w_2 s_2 v_2 : w_N s_N v_N Output Print the maximum possible sum of the values of the blocks contained in the tower. Examples Input 3 2 2 20 2 1 30 3 1 40 Output 50 Input 4 1 2 10 3 1 10 2 4 10 1 6 10 Output 40 Input 5 1 10000 1000000000 1 10000 1000000000 1 10000 1000000000 1 10000 1000000000 1 10000 1000000000 Output 5000000000 Input 8 9 5 7 6 2 7 5 7 3 7 8 8 1 9 6 3 3 3 4 1 7 4 5 5 Output 22 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. To participate in a prize draw each one gives his/her firstname. Each letter of a firstname has a value which is its rank in the English alphabet. `A` and `a` have rank `1`, `B` and `b` rank `2` and so on. The *length* of the firstname is added to the *sum* of these ranks hence a number `som`. An array of random weights is linked to the firstnames and each `som` is multiplied by its corresponding weight to get what they call a `winning number`. Example: ``` names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH" weights: [1, 4, 4, 5, 2, 1] PauL -> som = length of firstname + 16 + 1 + 21 + 12 = 4 + 50 -> 54 The *weight* associated with PauL is 2 so PauL's *winning number* is 54 * 2 = 108. ``` Now one can sort the firstnames in decreasing order of the `winning numbers`. When two people have the same `winning number` sort them *alphabetically* by their firstnames. ### Task: - parameters: `st` a string of firstnames, `we` an array of weights, `n` a rank - return: the firstname of the participant whose rank is `n` (ranks are numbered from 1) ### Example: ``` names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH" weights: [1, 4, 4, 5, 2, 1] n: 4 The function should return: "PauL" ``` # Notes: - The weight array is at least as long as the number of names, it can be longer. - If `st` is empty return "No participants". - If n is greater than the number of participants then return "Not enough participants". - See Examples Test Cases for more examples. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ### Happy Holidays fellow Code Warriors! Now, Dasher! Now, Dancer! Now, Prancer, and Vixen! On, Comet! On, Cupid! On, Donder and Blitzen! That's the order Santa wanted his reindeer...right? What do you mean he wants them in order by their last names!? Looks like we need your help Code Warrior! ### Sort Santa's Reindeer Write a function that accepts a sequence of Reindeer names, and returns a sequence with the Reindeer names sorted by their last names. ### Notes: * It's guaranteed that each string is composed of two words * In case of two identical last names, keep the original order ### Examples For this input: ``` [ "Dasher Tonoyan", "Dancer Moore", "Prancer Chua", "Vixen Hall", "Comet Karavani", "Cupid Foroutan", "Donder Jonker", "Blitzen Claus" ] ``` You should return this output: ``` [ "Prancer Chua", "Blitzen Claus", "Cupid Foroutan", "Vixen Hall", "Donder Jonker", "Comet Karavani", "Dancer Moore", "Dasher Tonoyan", ] ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ### Background We **all** know about "balancing parentheses" (plus brackets, braces and chevrons) and even balancing characters that are identical. Read that last sentence again, I balanced different characters and identical characters twice and you didn't even notice... :) ### Kata Your challenge in this kata is to write a piece of code to validate that a supplied string is balanced. You must determine if all that is open is then closed, and nothing is closed which is not already open! You will be given a string to validate, and a second string, where each pair of characters defines an opening and closing sequence that needs balancing. You may assume that the second string always has an even number of characters. ### Example ```python # In this case '(' opens a section, and ')' closes a section is_balanced("(Sensei says yes!)", "()") # => True is_balanced("(Sensei says no!", "()") # => False # In this case '(' and '[' open a section, while ')' and ']' close a section is_balanced("(Sensei [says] yes!)", "()[]") # => True is_balanced("(Sensei [says) no!]", "()[]") # => False # In this case a single quote (') both opens and closes a section is_balanced("Sensei says 'yes'!", "''") # => True is_balanced("Sensei say's no!", "''") # => False ``` Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Compute A + B. Constraints * -1000 ≤ A, B ≤ 1000 Input The input will consist of a series of pairs of integers A and B separated by a space, one pair of integers per line. The input will be terminated by EOF. Output For each pair of input integers A and B, you must output the sum of A and B in one line. Example Input 1 2 10 5 100 20 Output 3 15 120 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 city of Saint Petersburg, a day lasts for $2^{100}$ minutes. From the main station of Saint Petersburg, a train departs after $1$ minute, $4$ minutes, $16$ minutes, and so on; in other words, the train departs at time $4^k$ for each integer $k \geq 0$. Team BowWow has arrived at the station at the time $s$ and it is trying to count how many trains have they missed; in other words, the number of trains that have departed strictly before time $s$. For example if $s = 20$, then they missed trains which have departed at $1$, $4$ and $16$. As you are the only one who knows the time, help them! Note that the number $s$ will be given you in a binary representation without leading zeroes. -----Input----- The first line contains a single binary number $s$ ($0 \leq s < 2^{100}$) without leading zeroes. -----Output----- Output a single number — the number of trains which have departed strictly before the time $s$. -----Examples----- Input 100000000 Output 4 Input 101 Output 2 Input 10100 Output 3 -----Note----- In the first example $100000000_2 = 256_{10}$, missed trains have departed at $1$, $4$, $16$ and $64$. In the second example $101_2 = 5_{10}$, trains have departed at $1$ and $4$. The third example is explained in the statements. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is a vertex number $1$. A tree is a connected undirected graph with $n-1$ edges. You are given $m$ queries. The $i$-th query consists of the set of $k_i$ distinct vertices $v_i[1], v_i[2], \dots, v_i[k_i]$. Your task is to say if there is a path from the root to some vertex $u$ such that each of the given $k$ vertices is either belongs to this path or has the distance $1$ to some vertex of this path. -----Input----- The first line of the input contains two integers $n$ and $m$ ($2 \le n \le 2 \cdot 10^5$, $1 \le m \le 2 \cdot 10^5$) — the number of vertices in the tree and the number of queries. Each of the next $n-1$ lines describes an edge of the tree. Edge $i$ is denoted by two integers $u_i$ and $v_i$, the labels of vertices it connects $(1 \le u_i, v_i \le n, u_i \ne v_i$). It is guaranteed that the given edges form a tree. The next $m$ lines describe queries. The $i$-th line describes the $i$-th query and starts with the integer $k_i$ ($1 \le k_i \le n$) — the number of vertices in the current query. Then $k_i$ integers follow: $v_i[1], v_i[2], \dots, v_i[k_i]$ ($1 \le v_i[j] \le n$), where $v_i[j]$ is the $j$-th vertex of the $i$-th query. It is guaranteed that all vertices in a single query are distinct. It is guaranteed that the sum of $k_i$ does not exceed $2 \cdot 10^5$ ($\sum\limits_{i=1}^{m} k_i \le 2 \cdot 10^5$). -----Output----- For each query, print the answer — "YES", if there is a path from the root to some vertex $u$ such that each of the given $k$ vertices is either belongs to this path or has the distance $1$ to some vertex of this path and "NO" otherwise. -----Example----- Input 10 6 1 2 1 3 1 4 2 5 2 6 3 7 7 8 7 9 9 10 4 3 8 9 10 3 2 4 6 3 2 1 5 3 4 8 2 2 6 10 3 5 4 7 Output YES YES YES YES NO NO -----Note----- The picture corresponding to the example: [Image] Consider the queries. The first query is $[3, 8, 9, 10]$. The answer is "YES" as you can choose the path from the root $1$ to the vertex $u=10$. Then vertices $[3, 9, 10]$ belong to the path from $1$ to $10$ and the vertex $8$ has distance $1$ to the vertex $7$ which also belongs to this path. The second query is $[2, 4, 6]$. The answer is "YES" as you can choose the path to the vertex $u=2$. Then the vertex $4$ has distance $1$ to the vertex $1$ which belongs to this path and the vertex $6$ has distance $1$ to the vertex $2$ which belongs to this path. The third query is $[2, 1, 5]$. The answer is "YES" as you can choose the path to the vertex $u=5$ and all vertices of the query belong to this path. The fourth query is $[4, 8, 2]$. The answer is "YES" as you can choose the path to the vertex $u=9$ so vertices $2$ and $4$ both have distance $1$ to the vertex $1$ which belongs to this path and the vertex $8$ has distance $1$ to the vertex $7$ which belongs to this path. The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex $u$. Read the inputs from stdin solve the problem and write the answer to stdout (do 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. Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position $3$ and ends in position $6$), but "aa" or "d" aren't substrings of this string. So the substring of the string $s$ from position $l$ to position $r$ is $s[l; r] = s_l s_{l + 1} \dots s_r$. You have to choose exactly one of the substrings of the given string and reverse it (i. e. make $s[l; r] = s_r s_{r - 1} \dots s_l$) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string. If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring. String $x$ is lexicographically less than string $y$, if either $x$ is a prefix of $y$ (and $x \ne y$), or there exists such $i$ ($1 \le i \le min(|x|, |y|)$), that $x_i < y_i$, and for any $j$ ($1 \le j < i$) $x_j = y_j$. Here $|a|$ denotes the length of the string $a$. The lexicographic comparison of strings is implemented by operator < in modern programming languages​​. -----Input----- The first line of the input contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the length of $s$. The second line of the input contains the string $s$ of length $n$ consisting only of lowercase Latin letters. -----Output----- If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices $l$ and $r$ ($1 \le l < r \le n$) denoting the substring you have to reverse. If there are multiple answers, you can print any. -----Examples----- Input 7 abacaba Output YES 2 5 Input 6 aabcfg Output NO -----Note----- In the first testcase the resulting string is "aacabba". Read the inputs from stdin solve the problem and write the answer to stdout (do 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 new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement. How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007 = 10^9 + 7. -----Input----- Input will begin with a line containing N (1 ≤ N ≤ 100000), the number of engineers. N lines follow, each containing exactly two integers. The i-th line contains the number of the current desk of the i-th engineer and the number of the desk the i-th engineer wants to move to. Desks are numbered from 1 to 2·N. It is guaranteed that no two engineers sit at the same desk. -----Output----- Print the number of possible assignments, modulo 1000000007 = 10^9 + 7. -----Examples----- Input 4 1 5 5 2 3 7 7 3 Output 6 Input 5 1 10 2 10 3 10 4 10 5 5 Output 5 -----Note----- These are the possible assignments for the first example: 1 5 3 7 1 2 3 7 5 2 3 7 1 5 7 3 1 2 7 3 5 2 7 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. Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)? -----Input----- The first line of the input contains two integers s and x (2 ≤ s ≤ 10^12, 0 ≤ x ≤ 10^12), the sum and bitwise xor of the pair of positive integers, respectively. -----Output----- Print a single integer, the number of solutions to the given conditions. If no solutions exist, print 0. -----Examples----- Input 9 5 Output 4 Input 3 3 Output 2 Input 5 2 Output 0 -----Note----- In the first sample, we have the following solutions: (2, 7), (3, 6), (6, 3), (7, 2). In the second sample, the only solutions are (1, 2) and (2, 1). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are N slimes standing on a number line. The i-th slime from the left is at position x_i. It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}. Niwango will perform N-1 operations. The i-th operation consists of the following procedures: * Choose an integer k between 1 and N-i (inclusive) with equal probability. * Move the k-th slime from the left, to the position of the neighboring slime to the right. * Fuse the two slimes at the same position into one slime. Find the total distance traveled by the slimes multiplied by (N-1)! (we can show that this value is an integer), modulo (10^{9}+7). If a slime is born by a fuse and that slime moves, we count it as just one slime. Constraints * 2 \leq N \leq 10^{5} * 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9} * x_i is an integer. Input Input is given from Standard Input in the following format: N x_1 x_2 \ldots x_N Output Print the answer. Examples Input 3 1 2 3 Output 5 Input 12 161735902 211047202 430302156 450968417 628894325 707723857 731963982 822804784 880895728 923078537 971407775 982631932 Output 750927044 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 string is a string that consists of characters $0$ and $1$. Let $\operatorname{MEX}$ of a binary string be the smallest digit among $0$, $1$, or $2$ that does not occur in the string. For example, $\operatorname{MEX}$ of $001011$ is $2$, because $0$ and $1$ occur in the string at least once, $\operatorname{MEX}$ of $1111$ is $0$, because $0$ and $2$ do not occur in the string and $0 < 2$. A binary string $s$ is given. You should cut it into any number of substrings such that each character is in exactly one substring. It is possible to cut the string into a single substring — the whole string. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. What is the minimal sum of $\operatorname{MEX}$ of all substrings pieces can be? -----Input----- The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Description of the test cases follows. Each test case contains a single binary string $s$ ($1 \le |s| \le 10^5$). It's guaranteed that the sum of lengths of $s$ over all test cases does not exceed $10^5$. -----Output----- For each test case print a single integer — the minimal sum of $\operatorname{MEX}$ of all substrings that it is possible to get by cutting $s$ optimally. -----Examples----- Input 6 01 1111 01100 101 0000 01010 Output 1 0 2 1 1 2 -----Note----- In the first test case the minimal sum is $\operatorname{MEX}(0) + \operatorname{MEX}(1) = 1 + 0 = 1$. In the second test case the minimal sum is $\operatorname{MEX}(1111) = 0$. In the third test case the minimal sum is $\operatorname{MEX}(01100) = 2$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A Bingo game is played by one gamemaster and several players. At the beginning of a game, each player is given a card with M × M numbers in a matrix (See Figure 10). <image> As the game proceeds, the gamemaster announces a series of numbers one by one. Each player punches a hole in his card on the announced number, if any. When at least one 'Bingo' is made on the card, the player wins and leaves the game. The 'Bingo' means that all the M numbers in a line are punched vertically, horizontally or diagonally (See Figure 11). <image> The gamemaster continues announcing numbers until all the players make a Bingo. In the ordinary Bingo games, the gamemaster chooses numbers by a random process and has no control on them. But in this problem the gamemaster knows all the cards at the beginning of the game and controls the game by choosing the number sequence to be announced at his will. Specifically, he controls the game to satisfy the following condition. Cardi makes a Bingo no later than Cardj, for i < j. (*) Figure 12 shows an example of how a game proceeds. The gamemaster cannot announce '5' before '16', because Card4 makes a Bingo before Card2 and Card3, violating the condition (*). Your job is to write a program which finds the minimum length of such sequence of numbers for the given cards. Input The input consists of multiple datasets. The format of each dataset is as follows. <image> All data items are integers. P is the number of the cards, namely the number of the players. M is the number of rows and the number of columns of the matrix on each card. Nkij means the number written at the position (i, j) on the k-th card. If (i, j) ≠ (p, q), then Nkij ≠ Nkpq. The parameters P, M, and N satisfy the conditions 2 ≤ P ≤ 4, 3 ≤ M ≤ 4, and 0 ≤ Nkij ≤ 99. The end of the input is indicated by a line containing two zeros separated by a space. It is not a dataset. Output For each dataset, output the minimum length of the sequence of numbers which satisfy the condition (*). Output a zero if there are no such sequences. Output for each dataset must be printed on a separate line. Example Input 4 3 10 25 11 20 6 2 1 15 23 5 21 3 12 23 17 7 26 2 8 18 4 22 13 27 16 5 11 19 9 24 2 11 5 14 28 16 4 3 12 13 20 24 28 32 15 16 17 12 13 21 25 29 33 16 17 18 12 13 22 26 30 34 17 18 15 12 13 23 27 31 35 18 15 16 4 3 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 41 42 43 44 45 46 47 48 49 4 4 2 6 9 21 15 23 17 31 33 12 25 4 8 24 13 36 22 18 27 26 35 28 3 7 11 20 38 16 5 32 14 29 26 7 16 29 27 3 38 14 18 28 20 32 22 35 11 5 36 13 24 8 4 25 12 33 31 17 23 15 21 9 6 2 0 0 Output 5 4 12 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. The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness". The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct. A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves. Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case? Input The first line contains a positive integer n (1 ≤ n ≤ 100). It is the number of questions in the test. The second line contains space-separated n positive integers ai (1 ≤ ai ≤ 109), the number of answer variants to question i. Output Print a single number — the minimal number of clicks needed to pass the test it the worst-case scenario. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 1 1 Output 2 Input 2 2 2 Output 5 Input 1 10 Output 10 Note Note to the second sample. In the worst-case scenario you will need five clicks: * the first click selects the first variant to the first question, this answer turns out to be wrong. * the second click selects the second variant to the first question, it proves correct and we move on to the second question; * the third click selects the first variant to the second question, it is wrong and we go back to question 1; * the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question; * the fifth click selects the second variant to the second question, it proves correct, the test is finished. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth. Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition. Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property? Input The first line contains two integers n, m (1 ≤ n, m ≤ 2000) — the number of rows and the number columns in the labyrinth respectively. The second line contains two integers r, c (1 ≤ r ≤ n, 1 ≤ c ≤ m) — index of the row and index of the column that define the starting cell. The third line contains two integers x, y (0 ≤ x, y ≤ 109) — the maximum allowed number of movements to the left and to the right respectively. The next n lines describe the labyrinth. Each of them has length of m and consists only of symbols '.' and '*'. The j-th character of the i-th line corresponds to the cell of labyrinth at row i and column j. Symbol '.' denotes the free cell, while symbol '*' denotes the cell with an obstacle. It is guaranteed, that the starting cell contains no obstacles. Output Print exactly one integer — the number of cells in the labyrinth, which are reachable from starting cell, including the starting cell itself. Examples Input 4 5 3 2 1 2 ..... .***. ...** *.... Output 10 Input 4 4 2 2 0 1 .... ..*. .... .... Output 7 Note Cells, reachable in the corresponding example, are marked with '+'. First example: +++.. +***. +++** *+++. Second example: .++. .+*. .++. .++. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.