question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right. Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is: - There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i. In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7. -----Constraints----- - 1 ≤ N ≤ 300 - 1 ≤ M ≤ 300 - 1 ≤ l_i ≤ r_i ≤ N - 1 ≤ x_i ≤ 3 -----Input----- Input is given from Standard Input in the following format: N M l_1 r_1 x_1 l_2 r_2 x_2 : l_M r_M x_M -----Output----- Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7. -----Sample Input----- 3 1 1 3 3 -----Sample Output----- 6 The six ways are: - RGB - RBG - GRB - GBR - BRG - BGR where R, G and B correspond to red, green and blue squares, respectively. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows: - f(b,n) = n, when n < b - f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b, and n \ {\rm mod} \ b denotes the remainder of n divided by b. Less formally, f(b,n) is equal to the sum of the digits of n written in base b. For example, the following hold: - f(10,\,87654)=8+7+6+5+4=30 - f(100,\,87654)=8+76+54=138 You are given integers n and s. Determine if there exists an integer b (b \geq 2) such that f(b,n)=s. If the answer is positive, also find the smallest such b. -----Constraints----- - 1 \leq n \leq 10^{11} - 1 \leq s \leq 10^{11} - n,\,s are integers. -----Input----- The input is given from Standard Input in the following format: n s -----Output----- If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b. If such b does not exist, print -1 instead. -----Sample Input----- 87654 30 -----Sample Output----- 10 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 string s of length 3 or greater. No two neighboring characters in s are equal. Takahashi and Aoki will play a game against each other. The two players alternately performs the following operation, Takahashi going first: - Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s. The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally. -----Constraints----- - 3 ≤ |s| ≤ 10^5 - s consists of lowercase English letters. - No two neighboring characters in s are equal. -----Input----- The input is given from Standard Input in the following format: s -----Output----- If Takahashi will win, print First. If Aoki will win, print Second. -----Sample Input----- aba -----Sample Output----- Second Takahashi, who goes first, cannot perform the operation, since removal of the b, which is the only character not at either ends of s, would result in s becoming aa, with two as neighboring. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The only difference between easy and hard versions is constraints. Nauuo is a girl who loves random picture websites. One day she made a random picture website by herself which includes $n$ pictures. When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The $i$-th picture has a non-negative weight $w_i$, and the probability of the $i$-th picture being displayed is $\frac{w_i}{\sum_{j=1}^nw_j}$. That is to say, the probability of a picture to be displayed is proportional to its weight. However, Nauuo discovered that some pictures she does not like were displayed too often. To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add $1$ to its weight; otherwise, she would subtract $1$ from its weight. Nauuo will visit the website $m$ times. She wants to know the expected weight of each picture after all the $m$ visits modulo $998244353$. Can you help her? The expected weight of the $i$-th picture can be denoted by $\frac {q_i} {p_i}$ where $\gcd(p_i,q_i)=1$, you need to print an integer $r_i$ satisfying $0\le r_i<998244353$ and $r_i\cdot p_i\equiv q_i\pmod{998244353}$. It can be proved that such $r_i$ exists and is unique. -----Input----- The first line contains two integers $n$ and $m$ ($1\le n\le 50$, $1\le m\le 50$) — the number of pictures and the number of visits to the website. The second line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($a_i$ is either $0$ or $1$) — if $a_i=0$ , Nauuo does not like the $i$-th picture; otherwise Nauuo likes the $i$-th picture. It is guaranteed that there is at least one picture which Nauuo likes. The third line contains $n$ integers $w_1,w_2,\ldots,w_n$ ($1\le w_i\le50$) — the initial weights of the pictures. -----Output----- The output contains $n$ integers $r_1,r_2,\ldots,r_n$ — the expected weights modulo $998244353$. -----Examples----- Input 2 1 0 1 2 1 Output 332748119 332748119 Input 1 2 1 1 Output 3 Input 3 3 0 1 1 4 3 5 Output 160955686 185138929 974061117 -----Note----- In the first example, if the only visit shows the first picture with a probability of $\frac 2 3$, the final weights are $(1,1)$; if the only visit shows the second picture with a probability of $\frac1 3$, the final weights are $(2,2)$. So, both expected weights are $\frac2 3\cdot 1+\frac 1 3\cdot 2=\frac4 3$ . Because $332748119\cdot 3\equiv 4\pmod{998244353}$, you need to print $332748119$ instead of $\frac4 3$ or $1.3333333333$. In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, $w_1$ will be increased by $1$. So, the expected weight is $1+2=3$. Nauuo is very naughty so she didn't give you any hint of the third 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.
Solve the programming task below in a Python markdown code block. In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF. You are given two strings s_1, s_2 and another string called virus. Your task is to find the longest common subsequence of s_1 and s_2, such that it doesn't contain virus as a substring. -----Input----- The input contains three strings in three separate lines: s_1, s_2 and virus (1 ≤ |s_1|, |s_2|, |virus| ≤ 100). Each string consists only of uppercase English letters. -----Output----- Output the longest common subsequence of s_1 and s_2 without virus as a substring. If there are multiple answers, any of them will be accepted. If there is no valid common subsequence, output 0. -----Examples----- Input AJKEQSLOBSROFGZ OVGURWZLWVLUXTH OZ Output ORZ Input AA A A Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A monster is attacking the Cyberland! Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (HP), offensive power (ATK) and defensive power (DEF). During the battle, every second the monster's HP decrease by max(0, ATK_{Y} - DEF_{M}), while Yang's HP decreases by max(0, ATK_{M} - DEF_{Y}), where index Y denotes Master Yang and index M denotes monster. Both decreases happen simultaneously Once monster's HP ≤ 0 and the same time Master Yang's HP > 0, Master Yang wins. Master Yang can buy attributes from the magic shop of Cyberland: h bitcoins per HP, a bitcoins per ATK, and d bitcoins per DEF. Now Master Yang wants to know the minimum number of bitcoins he can spend in order to win. -----Input----- The first line contains three integers HP_{Y}, ATK_{Y}, DEF_{Y}, separated by a space, denoting the initial HP, ATK and DEF of Master Yang. The second line contains three integers HP_{M}, ATK_{M}, DEF_{M}, separated by a space, denoting the HP, ATK and DEF of the monster. The third line contains three integers h, a, d, separated by a space, denoting the price of 1 HP, 1 ATK and 1 DEF. All numbers in input are integer and lie between 1 and 100 inclusively. -----Output----- The only output line should contain an integer, denoting the minimum bitcoins Master Yang should spend in order to win. -----Examples----- Input 1 2 1 1 100 1 1 100 100 Output 99 Input 100 100 100 1 1 1 1 1 1 Output 0 -----Note----- For the first sample, prices for ATK and DEF are extremely high. Master Yang can buy 99 HP, then he can beat the monster with 1 HP left. For the second sample, Master Yang is strong enough to beat the monster, so he doesn't need to buy anything. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again. The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): [Image] Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut. To understand the problem better please read the notes to the test samples. -----Input----- The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≤ n ≤ 100000). The i-th (1 ≤ i ≤ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise. -----Output----- Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled. -----Examples----- Input -++- Output Yes Input +- Output No Input ++ Output Yes Input - Output No -----Note----- The first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses. In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: [Image] In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: [Image] In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself: [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. Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path. Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine. Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him. -----Input----- The first line of the input contains three integers — the number of vertices of the polygon n ($3 \leq n \leq 100000$), and coordinates of point P. Each of the next n lines contains two integers — coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value. -----Output----- Print a single real value number — the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$. -----Examples----- Input 3 0 0 0 1 -1 2 1 2 Output 12.566370614359172464 Input 4 1 -1 0 0 1 2 2 0 1 1 Output 21.991148575128551812 -----Note----- In the first sample snow will be removed from that area: $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. Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length. A block with side a has volume a^3. A tower consisting of blocks with sides a_1, a_2, ..., a_{k} has the total volume a_1^3 + a_2^3 + ... + a_{k}^3. Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X. Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X. Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks. -----Input----- The only line of the input contains one integer m (1 ≤ m ≤ 10^15), meaning that Limak wants you to choose X between 1 and m, inclusive. -----Output----- Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks. -----Examples----- Input 48 Output 9 42 Input 6 Output 6 6 -----Note----- In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42. In more detail, after choosing X = 42 the process of building a tower is: Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15. The second added block has side 2, so the remaining volume is 15 - 8 = 7. Finally, Limak adds 7 blocks with side 1, one by one. So, there are 9 blocks in the tower. The total volume is is 3^3 + 2^3 + 7·1^3 = 27 + 8 + 7 = 42. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence $s$ is called correct if: $s$ is empty; $s$ is equal to "($t$)", where $t$ is correct bracket sequence; $s$ is equal to $t_1 t_2$, i.e. concatenation of $t_1$ and $t_2$, where $t_1$ and $t_2$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct. -----Input----- First of line of input contains a single number $n$ ($1 \leq n \leq 200\,000$) — length of the sequence which Petya received for his birthday. Second line of the input contains bracket sequence of length $n$, containing symbols "(" and ")". -----Output----- Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No". -----Examples----- Input 2 )( Output Yes Input 3 (() Output No Input 2 () Output Yes Input 10 )))))((((( Output No -----Note----- In the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence. In the second example, there is no way to move at most one bracket so that the sequence becomes correct. In the third example, the sequence is already correct and there's no need to move brackets. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. SIHanatsuka - EMber SIHanatsuka - ATONEMENT Back in time, the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities. One day, Nora's adoptive father, Phoenix Wyle, brought Nora $n$ boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO. She labelled all $n$ boxes with $n$ distinct integers $a_1, a_2, \ldots, a_n$ and asked ROBO to do the following action several (possibly zero) times: Pick three distinct indices $i$, $j$ and $k$, such that $a_i \mid a_j$ and $a_i \mid a_k$. In other words, $a_i$ divides both $a_j$ and $a_k$, that is $a_j \bmod a_i = 0$, $a_k \bmod a_i = 0$. After choosing, Nora will give the $k$-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. After doing so, the box $k$ becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes. Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them? As the number of such piles can be very large, you should print the answer modulo $10^9 + 7$. -----Input----- The first line contains an integer $n$ ($3 \le n \le 60$), denoting the number of boxes. The second line contains $n$ distinct integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 60$), where $a_i$ is the label of the $i$-th box. -----Output----- Print the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo $10^9 + 7$. -----Examples----- Input 3 2 6 8 Output 2 Input 5 2 3 4 9 12 Output 4 Input 4 5 7 2 9 Output 1 -----Note----- Let's illustrate the box pile as a sequence $b$, with the pile's bottommost box being at the leftmost position. In the first example, there are $2$ distinct piles possible: $b = [6]$ ($[2, \mathbf{6}, 8] \xrightarrow{(1, 3, 2)} [2, 8]$) $b = [8]$ ($[2, 6, \mathbf{8}] \xrightarrow{(1, 2, 3)} [2, 6]$) In the second example, there are $4$ distinct piles possible: $b = [9, 12]$ ($[2, 3, 4, \mathbf{9}, 12] \xrightarrow{(2, 5, 4)} [2, 3, 4, \mathbf{12}] \xrightarrow{(1, 3, 4)} [2, 3, 4]$) $b = [4, 12]$ ($[2, 3, \mathbf{4}, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, 9, \mathbf{12}] \xrightarrow{(2, 3, 4)} [2, 3, 9]$) $b = [4, 9]$ ($[2, 3, \mathbf{4}, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, \mathbf{9}, 12] \xrightarrow{(2, 4, 3)} [2, 3, 12]$) $b = [9, 4]$ ($[2, 3, 4, \mathbf{9}, 12] \xrightarrow{(2, 5, 4)} [2, 3, \mathbf{4}, 12] \xrightarrow{(1, 4, 3)} [2, 3, 12]$) In the third sequence, ROBO can do nothing at all. Therefore, there is only $1$ valid pile, and that pile is empty. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers. For a given list of pairs of integers $(a_1, b_1)$, $(a_2, b_2)$, ..., $(a_n, b_n)$ their WCD is arbitrary integer greater than $1$, such that it divides at least one element in each pair. WCD may not exist for some lists. For example, if the list looks like $[(12, 15), (25, 18), (10, 24)]$, then their WCD can be equal to $2$, $3$, $5$ or $6$ (each of these numbers is strictly greater than $1$ and divides at least one number in each pair). You're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 150\,000$) — the number of pairs. Each of the next $n$ lines contains two integer values $a_i$, $b_i$ ($2 \le a_i, b_i \le 2 \cdot 10^9$). -----Output----- Print a single integer — the WCD of the set of pairs. If there are multiple possible answers, output any; if there is no answer, print $-1$. -----Examples----- Input 3 17 18 15 24 12 15 Output 6 Input 2 10 16 7 17 Output -1 Input 5 90 108 45 105 75 40 165 175 33 30 Output 5 -----Note----- In the first example the answer is $6$ since it divides $18$ from the first pair, $24$ from the second and $12$ from the third ones. Note that other valid answers will also be accepted. In the second example there are no integers greater than $1$ satisfying the conditions. In the third example one of the possible answers is $5$. Note that, for example, $15$ is also allowed, but it's not necessary to maximize the 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. We have a tree with N vertices. Vertex 1 is the root of the tree, and the parent of Vertex i (2 \leq i \leq N) is Vertex P_i. To each vertex in the tree, Snuke will allocate a color, either black or white, and a non-negative integer weight. Snuke has a favorite integer sequence, X_1, X_2, ..., X_N, so he wants to allocate colors and weights so that the following condition is satisfied for all v. - The total weight of the vertices with the same color as v among the vertices contained in the subtree whose root is v, is X_v. Here, the subtree whose root is v is the tree consisting of Vertex v and all of its descendants. Determine whether it is possible to allocate colors and weights in this way. -----Constraints----- - 1 \leq N \leq 1 000 - 1 \leq P_i \leq i - 1 - 0 \leq X_i \leq 5 000 -----Inputs----- Input is given from Standard Input in the following format: N P_2 P_3 ... P_N X_1 X_2 ... X_N -----Outputs----- If it is possible to allocate colors and weights to the vertices so that the condition is satisfied, print POSSIBLE; otherwise, print IMPOSSIBLE. -----Sample Input----- 3 1 1 4 3 2 -----Sample Output----- POSSIBLE For example, the following allocation satisfies the condition: - Set the color of Vertex 1 to white and its weight to 2. - Set the color of Vertex 2 to black and its weight to 3. - Set the color of Vertex 3 to white and its weight to 2. There are also other possible allocations. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 "Takahashi-ya", a ramen restaurant, basically they have one menu: "ramen", but N kinds of toppings are also offered. When a customer orders a bowl of ramen, for each kind of topping, he/she can choose whether to put it on top of his/her ramen or not. There is no limit on the number of toppings, and it is allowed to have all kinds of toppings or no topping at all. That is, considering the combination of the toppings, 2^N types of ramen can be ordered. Akaki entered Takahashi-ya. She is thinking of ordering some bowls of ramen that satisfy both of the following two conditions: - Do not order multiple bowls of ramen with the exactly same set of toppings. - Each of the N kinds of toppings is on two or more bowls of ramen ordered. You are given N and a prime number M. Find the number of the sets of bowls of ramen that satisfy these conditions, disregarding order, modulo M. Since she is in extreme hunger, ordering any number of bowls of ramen is fine. -----Constraints----- - 2 \leq N \leq 3000 - 10^8 \leq M \leq 10^9 + 9 - N is an integer. - M is a prime number. -----Subscores----- - 600 points will be awarded for passing the test set satisfying N ≤ 50. -----Input----- Input is given from Standard Input in the following format: N M -----Output----- Print the number of the sets of bowls of ramen that satisfy the conditions, disregarding order, modulo M. -----Sample Input----- 2 1000000007 -----Sample Output----- 2 Let the two kinds of toppings be A and B. Four types of ramen can be ordered: "no toppings", "with A", "with B" and "with A, B". There are two sets of ramen that satisfy the conditions: - The following three ramen: "with A", "with B", "with A, B". - Four ramen, one for each type. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. 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. 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. Nauuo is a girl who loves playing cards. One day she was playing cards but found that the cards were mixed with some empty ones. There are $n$ cards numbered from $1$ to $n$, and they were mixed with another $n$ empty cards. She piled up the $2n$ cards and drew $n$ of them. The $n$ cards in Nauuo's hands are given. The remaining $n$ cards in the pile are also given in the order from top to bottom. In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile. Nauuo wants to make the $n$ numbered cards piled up in increasing order (the $i$-th card in the pile from top to bottom is the card $i$) as quickly as possible. Can you tell her the minimum number of operations? -----Input----- The first line contains a single integer $n$ ($1\le n\le 2\cdot 10^5$) — the number of numbered cards. The second line contains $n$ integers $a_1,a_2,\ldots,a_n$ ($0\le a_i\le n$) — the initial cards in Nauuo's hands. $0$ represents an empty card. The third line contains $n$ integers $b_1,b_2,\ldots,b_n$ ($0\le b_i\le n$) — the initial cards in the pile, given in order from top to bottom. $0$ represents an empty card. It is guaranteed that each number from $1$ to $n$ appears exactly once, either in $a_{1..n}$ or $b_{1..n}$. -----Output----- The output contains a single integer — the minimum number of operations to make the $n$ numbered cards piled up in increasing order. -----Examples----- Input 3 0 2 0 3 0 1 Output 2 Input 3 0 2 0 1 0 3 Output 4 Input 11 0 0 0 5 0 0 0 4 0 0 11 9 2 6 0 8 1 7 0 3 0 10 Output 18 -----Note----- Example 1 We can play the card $2$ and draw the card $3$ in the first operation. After that, we have $[0,3,0]$ in hands and the cards in the pile are $[0,1,2]$ from top to bottom. Then, we play the card $3$ in the second operation. The cards in the pile are $[1,2,3]$, in which the cards are piled up in increasing order. Example 2 Play an empty card and draw the card $1$, then play $1$, $2$, $3$ in order. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two strings $s$ and $t$. The string $s$ consists of lowercase Latin letters and at most one wildcard character '*', the string $t$ consists only of lowercase Latin letters. The length of the string $s$ equals $n$, the length of the string $t$ equals $m$. The wildcard character '*' in the string $s$ (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of $s$ can be replaced with anything. If it is possible to replace a wildcard character '*' in $s$ to obtain a string $t$, then the string $t$ matches the pattern $s$. For example, if $s=$"aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba". If the given string $t$ matches the given string $s$, print "YES", otherwise print "NO". -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the length of the string $s$ and the length of the string $t$, respectively. The second line contains string $s$ of length $n$, which consists of lowercase Latin letters and at most one wildcard character '*'. The third line contains string $t$ of length $m$, which consists only of lowercase Latin letters. -----Output----- Print "YES" (without quotes), if you can obtain the string $t$ from the string $s$. Otherwise print "NO" (without quotes). -----Examples----- Input 6 10 code*s codeforces Output YES Input 6 5 vk*cup vkcup Output YES Input 1 1 v k Output NO Input 9 6 gfgf*gfgf gfgfgf Output NO -----Note----- In the first example a wildcard character '*' can be replaced with a string "force". So the string $s$ after this replacement is "codeforces" and the answer is "YES". In the second example a wildcard character '*' can be replaced with an empty string. So the string $s$ after this replacement is "vkcup" and the answer is "YES". There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO". In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string $t$ so the answer 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. Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him. Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 100) — the number of Andrey's friends. The second line contains n real numbers p_{i} (0.0 ≤ p_{i} ≤ 1.0) — the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point. -----Output----- Print a single real number — the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10^{ - 9}. -----Examples----- Input 4 0.1 0.2 0.3 0.8 Output 0.800000000000 Input 2 0.1 0.2 Output 0.260000000000 -----Note----- In the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one. In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1·0.8 + 0.9·0.2 = 0.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. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v_1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v_2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. -----Input----- The first line of the input contains five positive integers n, l, v_1, v_2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 10^9, 1 ≤ v_1 < v_2 ≤ 10^9, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. -----Output----- Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10^{ - 6}. -----Examples----- Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 -----Note----- In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Jeff got 2n real numbers a_1, a_2, ..., a_2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows: choose indexes i and j (i ≠ j) that haven't been chosen yet; round element a_{i} to the nearest integer that isn't more than a_{i} (assign to a_{i}: ⌊ a_{i} ⌋); round element a_{j} to the nearest integer that isn't less than a_{j} (assign to a_{j}: ⌈ a_{j} ⌉). Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference. -----Input----- The first line contains integer n (1 ≤ n ≤ 2000). The next line contains 2n real numbers a_1, a_2, ..., a_2n (0 ≤ a_{i} ≤ 10000), given with exactly three digits after the decimal point. The numbers are separated by spaces. -----Output----- In a single line print a single real number — the required difference with exactly three digits after the decimal point. -----Examples----- Input 3 0.000 0.500 0.750 1.000 2.000 3.000 Output 0.250 Input 3 4469.000 6526.000 4864.000 9356.383 7490.000 995.896 Output 0.279 -----Note----- In the first test case you need to perform the operations as follows: (i = 1, j = 4), (i = 2, j = 3), (i = 5, j = 6). In this case, the difference will equal |(0 + 0.5 + 0.75 + 1 + 2 + 3) - (0 + 0 + 1 + 1 + 2 + 3)| = 0.25. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarp takes part in a quadcopter competition. According to the rules a flying robot should: start the race from some point of a field, go around the flag, close cycle returning back to the starting point. Polycarp knows the coordinates of the starting point (x_1, y_1) and the coordinates of the point where the flag is situated (x_2, y_2). Polycarp’s quadcopter can fly only parallel to the sides of the field each tick changing exactly one coordinate by 1. It means that in one tick the quadcopter can fly from the point (x, y) to any of four points: (x - 1, y), (x + 1, y), (x, y - 1) or (x, y + 1). Thus the quadcopter path is a closed cycle starting and finishing in (x_1, y_1) and containing the point (x_2, y_2) strictly inside. [Image] The picture corresponds to the first example: the starting (and finishing) point is in (1, 5) and the flag is in (5, 2). What is the minimal length of the quadcopter path? -----Input----- The first line contains two integer numbers x_1 and y_1 ( - 100 ≤ x_1, y_1 ≤ 100) — coordinates of the quadcopter starting (and finishing) point. The second line contains two integer numbers x_2 and y_2 ( - 100 ≤ x_2, y_2 ≤ 100) — coordinates of the flag. It is guaranteed that the quadcopter starting point and the flag do not coincide. -----Output----- Print the length of minimal path of the quadcopter to surround the flag and return back. -----Examples----- Input 1 5 5 2 Output 18 Input 0 1 0 0 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. Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers $1$, $5$, $10$ and $50$ respectively. The use of other roman digits is not allowed. Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as the sum of digits in it. For example, the number XXXV evaluates to $35$ and the number IXI — to $12$. Pay attention to the difference to the traditional roman system — in our system any sequence of digits is valid, moreover the order of digits doesn't matter, for example IX means $11$, not $9$. One can notice that this system is ambiguous, and some numbers can be written in many different ways. Your goal is to determine how many distinct integers can be represented by exactly $n$ roman digits I, V, X, L. -----Input----- The only line of the input file contains a single integer $n$ ($1 \le n \le 10^9$) — the number of roman digits to use. -----Output----- Output a single integer — the number of distinct integers which can be represented using $n$ roman digits exactly. -----Examples----- Input 1 Output 4 Input 2 Output 10 Input 10 Output 244 -----Note----- In the first sample there are exactly $4$ integers which can be represented — I, V, X and L. In the second sample it is possible to represent integers $2$ (II), $6$ (VI), $10$ (VV), $11$ (XI), $15$ (XV), $20$ (XX), $51$ (IL), $55$ (VL), $60$ (XL) and $100$ (LL). Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string. B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time. You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes). -----Input----- The first and only line consists of a string $S$ ($ 1 \le |S| \le 5\,000 $). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'. -----Output----- Print "YES" or "NO", according to the condition. -----Examples----- Input aaabccc Output YES Input bbacc Output NO Input aabc Output YES -----Note----- Consider first example: the number of 'c' is equal to the number of 'a'. Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct. Consider third example: the number of 'c' is equal to the number of 'b'. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability $\frac{1}{m}$. Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times. -----Input----- A single line contains two integers m and n (1 ≤ m, n ≤ 10^5). -----Output----- Output a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn't exceed 10 ^{ - 4}. -----Examples----- Input 6 1 Output 3.500000000000 Input 6 3 Output 4.958333333333 Input 2 2 Output 1.750000000000 -----Note----- Consider the third test example. If you've made two tosses: You can get 1 in the first toss, and 2 in the second. Maximum equals to 2. You can get 1 in the first toss, and 1 in the second. Maximum equals to 1. You can get 2 in the first toss, and 1 in the second. Maximum equals to 2. You can get 2 in the first toss, and 2 in the second. Maximum equals to 2. The probability of each outcome is 0.25, that is expectation equals to: $(2 + 1 + 2 + 2) \cdot 0.25 = \frac{7}{4}$ You can read about expectation using the following link: http://en.wikipedia.org/wiki/Expected_value Read the inputs from stdin solve the problem and write the answer to stdout (do 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 snake exhibition, there are $n$ rooms (numbered $0$ to $n - 1$) arranged in a circle, with a snake in each room. The rooms are connected by $n$ conveyor belts, and the $i$-th conveyor belt connects the rooms $i$ and $(i+1) \bmod n$. In the other words, rooms $0$ and $1$, $1$ and $2$, $\ldots$, $n-2$ and $n-1$, $n-1$ and $0$ are connected with conveyor belts. The $i$-th conveyor belt is in one of three states: If it is clockwise, snakes can only go from room $i$ to $(i+1) \bmod n$. If it is anticlockwise, snakes can only go from room $(i+1) \bmod n$ to $i$. If it is off, snakes can travel in either direction. [Image] Above is an example with $4$ rooms, where belts $0$ and $3$ are off, $1$ is clockwise, and $2$ is anticlockwise. Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there? -----Input----- Each test contains multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 1000$): the number of test cases. The description of the test cases follows. The first line of each test case description contains a single integer $n$ ($2 \le n \le 300\,000$): the number of rooms. The next line of each test case description contains a string $s$ of length $n$, consisting of only '<', '>' and '-'. If $s_{i} = $ '>', the $i$-th conveyor belt goes clockwise. If $s_{i} = $ '<', the $i$-th conveyor belt goes anticlockwise. If $s_{i} = $ '-', the $i$-th conveyor belt is off. It is guaranteed that the sum of $n$ among all test cases does not exceed $300\,000$. -----Output----- For each test case, output the number of returnable rooms. -----Example----- Input 4 4 -><- 5 >>>>> 3 <-- 2 <> Output 3 5 3 0 -----Note----- In the first test case, all rooms are returnable except room $2$. The snake in the room $2$ is trapped and cannot exit. This test case corresponds to the picture from the problem statement. In the second test case, all rooms are returnable by traveling on the series of clockwise belts. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy! The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time on the street. The street is split into n equal length parts from left to right, the i-th part is characterized by two integers: width of road s_{i} and width of lawn g_{i}. [Image] For each of n parts the Mayor should decide the size of lawn to demolish. For the i-th part he can reduce lawn width by integer x_{i} (0 ≤ x_{i} ≤ g_{i}). After it new road width of the i-th part will be equal to s'_{i} = s_{i} + x_{i} and new lawn width will be equal to g'_{i} = g_{i} - x_{i}. On the one hand, the Mayor wants to demolish as much lawn as possible (and replace it with road). On the other hand, he does not want to create a rapid widening or narrowing of the road, which would lead to car accidents. To avoid that, the Mayor decided that width of the road for consecutive parts should differ by at most 1, i.e. for each i (1 ≤ i < n) the inequation |s'_{i} + 1 - s'_{i}| ≤ 1 should hold. Initially this condition might not be true. You need to find the the total width of lawns the Mayor will destroy according to his plan. -----Input----- The first line contains integer n (1 ≤ n ≤ 2·10^5) — number of parts of the street. Each of the following n lines contains two integers s_{i}, g_{i} (1 ≤ s_{i} ≤ 10^6, 0 ≤ g_{i} ≤ 10^6) — current width of road and width of the lawn on the i-th part of the street. -----Output----- In the first line print the total width of lawns which will be removed. In the second line print n integers s'_1, s'_2, ..., s'_{n} (s_{i} ≤ s'_{i} ≤ s_{i} + g_{i}) — new widths of the road starting from the first part and to the last. If there is no solution, print the only integer -1 in the first line. -----Examples----- Input 3 4 5 4 5 4 10 Output 16 9 9 10 Input 4 1 100 100 1 1 100 100 1 Output 202 101 101 101 101 Input 3 1 1 100 100 1 1 Output -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height a_{i}. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5, 4, 6, 2, then houses could be built on hills with heights 5 and 6 only. The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan? However, the exact value of k is not yet determined, so could you please calculate answers for all k in range $1 \leq k \leq \lceil \frac{n}{2} \rceil$? Here $\lceil \frac{n}{2} \rceil$ denotes n divided by two, rounded up. -----Input----- The first line of input contains the only integer n (1 ≤ n ≤ 5000)—the number of the hills in the sequence. Second line contains n integers a_{i} (1 ≤ a_{i} ≤ 100 000)—the heights of the hills in the sequence. -----Output----- Print exactly $\lceil \frac{n}{2} \rceil$ numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. -----Examples----- Input 5 1 1 1 1 1 Output 1 2 2 Input 3 1 2 3 Output 0 2 Input 5 1 2 3 2 2 Output 0 1 3 -----Note----- In the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1, 0, 1, 1, 1 and the first hill becomes suitable for construction. In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1, 0, 1, 0, 1, and hills 1, 3, 5 become suitable for construction. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $s$, which can be represented as a binary string, in which the $i$-th symbol is '1' if students will write the contest in the $i$-th day and '0' if they will have a day off. At the last moment Gleb said that the camp will be the most productive if it runs with the schedule $t$ (which can be described in the same format as schedule $s$). Since the number of days in the current may be different from number of days in schedule $t$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $t$ in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change. Could you rearrange the schedule in the best possible way? -----Input----- The first line contains string $s$ ($1 \leqslant |s| \leqslant 500\,000$), denoting the current project of the camp's schedule. The second line contains string $t$ ($1 \leqslant |t| \leqslant 500\,000$), denoting the optimal schedule according to Gleb. Strings $s$ and $t$ contain characters '0' and '1' only. -----Output----- In the only line print the schedule having the largest number of substrings equal to $t$. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in $s$ and the number of ones should be equal to the number of ones in $s$. In case there multiple optimal schedules, print any of them. -----Examples----- Input 101101 110 Output 110110 Input 10010110 100011 Output 01100011 Input 10 11100 Output 01 -----Note----- In the first example there are two occurrences, one starting from first position and one starting from fourth position. In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of $t$ wouldn't change. In the third example it's impossible to make even a single occurrence. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sereja has an n × m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size h × w, then the component must contain exactly hw cells. A connected component of the same values is a set of cells of the table that meet the following conditions: every two cells of the set have the same value; the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table); it is impossible to add any cell to the set unless we violate the two previous conditions. Can Sereja change the values of at most k cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case? -----Input----- The first line contains integers n, m and k (1 ≤ n, m ≤ 100; 1 ≤ k ≤ 10). Next n lines describe the table a: the i-th of them contains m integers a_{i}1, a_{i}2, ..., a_{im} (0 ≤ a_{i}, j ≤ 1) — the values in the cells of the i-th row. -----Output----- Print -1, if it is impossible to meet the requirement. Otherwise, print the minimum number of cells which should be changed. -----Examples----- Input 5 5 2 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 Output 1 Input 3 4 1 1 0 0 0 0 1 1 1 1 1 1 0 Output -1 Input 3 4 1 1 0 0 1 0 1 1 0 1 0 0 1 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $M$ with $n$ rows and $n$ columns such that $M_{ij}=a_i \cdot a_j$ where $a_1, \dots, a_n$ is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $a_1, \dots, a_n$. Help Sasha restore the array! -----Input----- The first line contains a single integer $n$ ($3 \leqslant n \leqslant 10^3$), the size of the table. The next $n$ lines contain $n$ integers each. The $j$-th number of the $i$-th line contains the number $M_{ij}$ ($1 \leq M_{ij} \leq 10^9$). The table has zeroes on the main diagonal, that is, $M_{ii}=0$. -----Output----- In a single line print $n$ integers, the original array $a_1, \dots, a_n$ ($1 \leq a_i \leq 10^9$). It is guaranteed that an answer exists. If there are multiple answers, print any. -----Examples----- Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Elections in Berland are coming. There are only two candidates — Alice and Bob. The main Berland TV channel plans to show political debates. There are $n$ people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views: supporting none of candidates (this kind is denoted as "00"), supporting Alice but not Bob (this kind is denoted as "10"), supporting Bob but not Alice (this kind is denoted as "01"), supporting both candidates (this kind is denoted as "11"). The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions: at least half of spectators support Alice (i.e. $2 \cdot a \ge m$, where $a$ is number of spectators supporting Alice and $m$ is the total number of spectators), at least half of spectators support Bob (i.e. $2 \cdot b \ge m$, where $b$ is number of spectators supporting Bob and $m$ is the total number of spectators), the total influence of spectators is maximal possible. Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible. -----Input----- The first line contains integer $n$ ($1 \le n \le 4\cdot10^5$) — the number of people who want to take part in the debate as a spectator. These people are described on the next $n$ lines. Each line describes a single person and contains the string $s_i$ and integer $a_i$ separated by space ($1 \le a_i \le 5000$), where $s_i$ denotes person's political views (possible values — "00", "10", "01", "11") and $a_i$ — the influence of the $i$-th person. -----Output----- Print a single integer — maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead. -----Examples----- Input 6 11 6 10 4 01 3 00 3 00 7 00 9 Output 22 Input 5 11 1 01 1 00 100 10 1 01 1 Output 103 Input 6 11 19 10 22 00 18 00 29 11 29 10 28 Output 105 Input 3 00 5000 00 5000 00 5000 Output 0 -----Note----- In the first example $4$ spectators can be invited to maximize total influence: $1$, $2$, $3$ and $6$. Their political views are: "11", "10", "01" and "00". So in total $2$ out of $4$ spectators support Alice and $2$ out of $4$ spectators support Bob. The total influence is $6+4+3+9=22$. In the second example the direction can select all the people except the $5$-th person. In the third example the direction can select people with indices: $1$, $4$, $5$ and $6$. In the fourth example it is impossible to select any non-empty set of spectators. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the only hope of the organizers, so they don't want to work for free: the i-th student wants to get c_{i} 'passes' in his subjects (regardless of the volume of his work). Bugs, like students, are not the same: every bug is characterized by complexity a_{j}, and every student has the level of his abilities b_{i}. Student i can fix a bug j only if the level of his abilities is not less than the complexity of the bug: b_{i} ≥ a_{j}, and he does it in one day. Otherwise, the bug will have to be fixed by another student. Of course, no student can work on a few bugs in one day. All bugs are not dependent on each other, so they can be corrected in any order, and different students can work simultaneously. The university wants to fix all the bugs as quickly as possible, but giving the students the total of not more than s passes. Determine which students to use for that and come up with the schedule of work saying which student should fix which bug. -----Input----- The first line contains three space-separated integers: n, m and s (1 ≤ n, m ≤ 10^5, 0 ≤ s ≤ 10^9) — the number of students, the number of bugs in the system and the maximum number of passes the university is ready to give the students. The next line contains m space-separated integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^9) — the bugs' complexities. The next line contains n space-separated integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^9) — the levels of the students' abilities. The next line contains n space-separated integers c_1, c_2, ..., c_{n} (0 ≤ c_{i} ≤ 10^9) — the numbers of the passes the students want to get for their help. -----Output----- If the university can't correct all bugs print "NO". Otherwise, on the first line print "YES", and on the next line print m space-separated integers: the i-th of these numbers should equal the number of the student who corrects the i-th bug in the optimal answer. The bugs should be corrected as quickly as possible (you must spend the minimum number of days), and the total given passes mustn't exceed s. If there are multiple optimal answers, you can output any of them. -----Examples----- Input 3 4 9 1 3 1 2 2 1 3 4 3 6 Output YES 2 3 2 3 Input 3 4 10 2 3 1 2 2 1 3 4 3 6 Output YES 1 3 1 3 Input 3 4 9 2 3 1 2 2 1 3 4 3 6 Output YES 3 3 2 3 Input 3 4 5 1 3 1 2 2 1 3 5 3 6 Output NO -----Note----- Consider the first sample. The third student (with level 3) must fix the 2nd and 4th bugs (complexities 3 and 2 correspondingly) and the second student (with level 1) must fix the 1st and 3rd bugs (their complexity also equals 1). Fixing each bug takes one day for each student, so it takes 2 days to fix all bugs (the students can work in parallel). The second student wants 3 passes for his assistance, the third student wants 6 passes. It meets the university's capabilities as it is ready to give at most 9 passes. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ivan places knights on infinite chessboard. Initially there are $n$ knights. If there is free cell which is under attack of at least $4$ knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the end does not depend on the order in which new knights are placed. Ivan asked you to find initial placement of exactly $n$ knights such that in the end there will be at least $\lfloor \frac{n^{2}}{10} \rfloor$ knights. -----Input----- The only line of input contains one integer $n$ ($1 \le n \le 10^{3}$) — number of knights in the initial placement. -----Output----- Print $n$ lines. Each line should contain $2$ numbers $x_{i}$ and $y_{i}$ ($-10^{9} \le x_{i}, \,\, y_{i} \le 10^{9}$) — coordinates of $i$-th knight. For all $i \ne j$, $(x_{i}, \,\, y_{i}) \ne (x_{j}, \,\, y_{j})$ should hold. In other words, all knights should be in different cells. It is guaranteed that the solution exists. -----Examples----- Input 4 Output 1 1 3 1 1 5 4 4 Input 7 Output 2 1 1 2 4 1 5 2 2 6 5 7 6 6 -----Note----- Let's look at second example: $\left. \begin{array}{|l|l|l|l|l|l|l|l|l|} \hline 7 & {} & {} & {} & {} & {0} & {} & {} \\ \hline 6 & {} & {0} & {} & {} & {} & {0} & {} \\ \hline 5 & {} & {} & {} & {2} & {} & {} & {} \\ \hline 4 & {} & {} & {} & {} & {} & {} & {} \\ \hline 3 & {} & {} & {1} & {} & {} & {} & {} \\ \hline 2 & {0} & {} & {} & {} & {0} & {} & {} \\ \hline 1 & {} & {0} & {} & {0} & {} & {} & {} \\ \hline & {1} & {2} & {3} & {4} & {5} & {6} & {7} \\ \hline \end{array} \right.$ Green zeroes are initial knights. Cell $(3, \,\, 3)$ is under attack of $4$ knights in cells $(1, \,\, 2)$, $(2, \,\, 1)$, $(4, \,\, 1)$ and $(5, \,\, 2)$, therefore Ivan will place a knight in this cell. Cell $(4, \,\, 5)$ is initially attacked by only $3$ knights in cells $(2, \,\, 6)$, $(5, \,\, 7)$ and $(6, \,\, 6)$. But new knight in cell $(3, \,\, 3)$ also attacks cell $(4, \,\, 5)$, now it is attacked by $4$ knights and Ivan will place another knight in this cell. There are no more free cells which are attacked by $4$ or more knights, so the process stops. There are $9$ knights in the end, which is not less than $\lfloor \frac{7^{2}}{10} \rfloor = 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. In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must. Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this... Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients strictly less than k, whose remainder is p when divided by (x + k). That is, f(x) = q(x)·(x + k) + p, where q(x) is a polynomial (not necessarily with integer coefficients). -----Input----- The only line of input contains two space-separated integers p and k (1 ≤ p ≤ 10^18, 2 ≤ k ≤ 2 000). -----Output----- If the polynomial does not exist, print a single integer -1, or output two lines otherwise. In the first line print a non-negative integer d — the number of coefficients in the polynomial. In the second line print d space-separated integers a_0, a_1, ..., a_{d} - 1, describing a polynomial $f(x) = \sum_{i = 0}^{d - 1} a_{i} \cdot x^{i}$ fulfilling the given requirements. Your output should satisfy 0 ≤ a_{i} < k for all 0 ≤ i ≤ d - 1, and a_{d} - 1 ≠ 0. If there are many possible solutions, print any of them. -----Examples----- Input 46 2 Output 7 0 1 0 0 1 1 1 Input 2018 214 Output 3 92 205 1 -----Note----- In the first example, f(x) = x^6 + x^5 + x^4 + x = (x^5 - x^4 + 3x^3 - 6x^2 + 12x - 23)·(x + 2) + 46. In the second example, f(x) = x^2 + 205x + 92 = (x - 9)·(x + 214) + 2018. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site. He has suggestions to work on n distinct projects. Mikhail has already evaluated that the participation in the i-th project will increase his experience by a_{i} per day and bring b_{i} dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time. Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true. For example, suppose Mikhail is suggested to work on three projects and a_1 = 6, b_1 = 2, a_2 = 1, b_2 = 3, a_3 = 2, b_3 = 6. Also, p = 20 and q = 20. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, a_1·2.5 + a_2·0 + a_3·2.5 = 6·2.5 + 1·0 + 2·2.5 = 20 and b_1·2.5 + b_2·0 + b_3·2.5 = 2·2.5 + 3·0 + 6·2.5 = 20. -----Input----- The first line of the input contains three integers n, p and q (1 ≤ n ≤ 100 000, 1 ≤ p, q ≤ 1 000 000) — the number of projects and the required number of experience and money. Each of the next n lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 1 000 000) — the daily increase in experience and daily income for working on the i-th project. -----Output----- Print a real value — the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$. -----Examples----- Input 3 20 20 6 2 1 3 2 6 Output 5.000000000000000 Input 4 1 1 2 3 3 2 2 3 3 2 Output 0.400000000000000 -----Note----- First sample corresponds to the example in the problem statement. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number a_{i} written on it. They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that a_{j} < a_{i}. A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally. -----Input----- The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of cards Conan has. The next line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5), where a_{i} is the number on the i-th card. -----Output----- If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes). -----Examples----- Input 3 4 5 7 Output Conan Input 2 1 1 Output Agasa -----Note----- In the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn. In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two integers A and B. Print a grid where each square is painted white or black that satisfies the following conditions, in the format specified in Output section: - Let the size of the grid be h \times w (h vertical, w horizontal). Both h and w are at most 100. - The set of the squares painted white is divided into exactly A connected components. - The set of the squares painted black is divided into exactly B connected components. It can be proved that there always exist one or more solutions under the conditions specified in Constraints section. If there are multiple solutions, any of them may be printed. -----Notes----- Two squares painted white, c_1 and c_2, are called connected when the square c_2 can be reached from the square c_1 passing only white squares by repeatedly moving up, down, left or right to an adjacent square. A set of squares painted white, S, forms a connected component when the following conditions are met: - Any two squares in S are connected. - No pair of a square painted white that is not included in S and a square included in S is connected. A connected component of squares painted black is defined similarly. -----Constraints----- - 1 \leq A \leq 500 - 1 \leq B \leq 500 -----Input----- Input is given from Standard Input in the following format: A B -----Output----- Output should be in the following format: - In the first line, print integers h and w representing the size of the grid you constructed, with a space in between. - Then, print h more lines. The i-th (1 \leq i \leq h) of these lines should contain a string s_i as follows: - If the square at the i-th row and j-th column (1 \leq j \leq w) in the grid is painted white, the j-th character in s_i should be .. - If the square at the i-th row and j-th column (1 \leq j \leq w) in the grid is painted black, the j-th character in s_i should be #. -----Sample Input----- 2 3 -----Sample Output----- 3 3 ##. ..# #.# This output corresponds to the grid below: Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat. One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting. You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting). -----Input----- The first line contains integers n and m (1 ≤ n, m ≤ 10^5) — the number of team participants and the number of messages. Each of the next m lines contains a message in the format: '+ id': the record means that the person with number id (1 ≤ id ≤ n) has logged on to the meeting. '- id': the record means that the person with number id (1 ≤ id ≤ n) has logged off from the meeting. Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously. -----Output----- In the first line print integer k (0 ≤ k ≤ n) — how many people can be leaders. In the next line, print k integers in the increasing order — the numbers of the people who can be leaders. If the data is such that no member of the team can be a leader, print a single number 0. -----Examples----- Input 5 4 + 1 + 2 - 2 - 1 Output 4 1 3 4 5 Input 3 2 + 1 - 2 Output 1 3 Input 2 4 + 1 - 1 + 2 - 2 Output 0 Input 5 6 + 1 - 1 - 3 + 3 + 4 - 4 Output 3 2 3 5 Input 2 4 + 1 - 2 + 2 - 1 Output 0 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two arrays $a$ and $b$ of positive integers, with length $n$ and $m$ respectively. Let $c$ be an $n \times m$ matrix, where $c_{i,j} = a_i \cdot b_j$. You need to find a subrectangle of the matrix $c$ such that the sum of its elements is at most $x$, and its area (the total number of elements) is the largest possible. Formally, you need to find the largest number $s$ such that it is possible to choose integers $x_1, x_2, y_1, y_2$ subject to $1 \leq x_1 \leq x_2 \leq n$, $1 \leq y_1 \leq y_2 \leq m$, $(x_2 - x_1 + 1) \times (y_2 - y_1 + 1) = s$, and $$\sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} \leq x.$$ -----Input----- The first line contains two integers $n$ and $m$ ($1 \leq n, m \leq 2000$). The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 2000$). The third line contains $m$ integers $b_1, b_2, \ldots, b_m$ ($1 \leq b_i \leq 2000$). The fourth line contains a single integer $x$ ($1 \leq x \leq 2 \cdot 10^{9}$). -----Output----- If it is possible to choose four integers $x_1, x_2, y_1, y_2$ such that $1 \leq x_1 \leq x_2 \leq n$, $1 \leq y_1 \leq y_2 \leq m$, and $\sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} \leq x$, output the largest value of $(x_2 - x_1 + 1) \times (y_2 - y_1 + 1)$ among all such quadruplets, otherwise output $0$. -----Examples----- Input 3 3 1 2 3 1 2 3 9 Output 4 Input 5 1 5 4 2 4 5 2 5 Output 1 -----Note----- Matrix from the first sample and the chosen subrectangle (of blue color): [Image] Matrix from the second sample and the chosen subrectangle (of blue color): $\left. \begin{array}{l l l l l}{10} & {8} & {4} & {8} & {10} \end{array} \right.$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more. Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist. -----Input----- The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition). -----Output----- If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes). -----Examples----- Input 3 3 cba Output NO Input 3 4 cba Output cbd Input 4 4 abcd Output abda -----Note----- String s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s_1 = t_1, ..., s_{i} = t_{i}, s_{i} + 1 > t_{i} + 1. The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one. A palindrome is a string that reads the same forward or reversed. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. "Duel!" Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started. There are $n$ cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping cards, in which Tokitsukaze moves first. In each move, one should choose exactly $k$ consecutive cards and flip them to the same side, which means to make their color sides all face up or all face down. If all the color sides of these $n$ cards face the same direction after one's move, the one who takes this move will win. Princess Claris wants to know who will win the game if Tokitsukaze and Quailty are so clever that they won't make mistakes. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 10^5$). The second line contains a single string of length $n$ that only consists of $0$ and $1$, representing the situation of these $n$ cards, where the color side of the $i$-th card faces up if the $i$-th character is $1$, or otherwise, it faces down and the $i$-th character is $0$. -----Output----- Print "once again" (without quotes) if the total number of their moves can exceed $10^9$, which is considered a draw. In other cases, print "tokitsukaze" (without quotes) if Tokitsukaze will win, or "quailty" (without quotes) if Quailty will win. Note that the output characters are case-sensitive, and any wrong spelling would be rejected. -----Examples----- Input 4 2 0101 Output quailty Input 6 1 010101 Output once again Input 6 5 010101 Output tokitsukaze Input 4 1 0011 Output once again -----Note----- In the first example, no matter how Tokitsukaze moves, there would be three cards with color sides facing the same direction after her move, and Quailty can flip the last card to this direction and win. In the second example, no matter how Tokitsukaze moves, Quailty can choose the same card and flip back to the initial situation, which can allow the game to end in a draw. In the third example, Tokitsukaze can win by flipping the leftmost five cards up or flipping the rightmost five cards down. The fourth example can be explained in the same way as the second example does. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through $n \cdot k$ cities. The cities are numerated from $1$ to $n \cdot k$, the distance between the neighboring cities is exactly $1$ km. Sergey does not like beetles, he loves burgers. Fortunately for him, there are $n$ fast food restaurants on the circle, they are located in the $1$-st, the $(k + 1)$-st, the $(2k + 1)$-st, and so on, the $((n-1)k + 1)$-st cities, i.e. the distance between the neighboring cities with fast food restaurants is $k$ km. Sergey began his journey at some city $s$ and traveled along the circle, making stops at cities each $l$ km ($l > 0$), until he stopped in $s$ once again. Sergey then forgot numbers $s$ and $l$, but he remembers that the distance from the city $s$ to the nearest fast food restaurant was $a$ km, and the distance from the city he stopped at after traveling the first $l$ km from $s$ to the nearest fast food restaurant was $b$ km. Sergey always traveled in the same direction along the circle, but when he calculated distances to the restaurants, he considered both directions. Now Sergey is interested in two integers. The first integer $x$ is the minimum number of stops (excluding the first) Sergey could have done before returning to $s$. The second integer $y$ is the maximum number of stops (excluding the first) Sergey could have done before returning to $s$. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le n, k \le 100\,000$) — the number of fast food restaurants on the circle and the distance between the neighboring restaurants, respectively. The second line contains two integers $a$ and $b$ ($0 \le a, b \le \frac{k}{2}$) — the distances to the nearest fast food restaurants from the initial city and from the city Sergey made the first stop at, respectively. -----Output----- Print the two integers $x$ and $y$. -----Examples----- Input 2 3 1 1 Output 1 6 Input 3 2 0 0 Output 1 3 Input 1 10 5 3 Output 5 5 -----Note----- In the first example the restaurants are located in the cities $1$ and $4$, the initial city $s$ could be $2$, $3$, $5$, or $6$. The next city Sergey stopped at could also be at cities $2, 3, 5, 6$. Let's loop through all possible combinations of these cities. If both $s$ and the city of the first stop are at the city $2$ (for example, $l = 6$), then Sergey is at $s$ after the first stop already, so $x = 1$. In other pairs Sergey needs $1, 2, 3$, or $6$ stops to return to $s$, so $y = 6$. In the second example Sergey was at cities with fast food restaurant both initially and after the first stop, so $l$ is $2$, $4$, or $6$. Thus $x = 1$, $y = 3$. In the third example there is only one restaurant, so the possible locations of $s$ and the first stop are: $(6, 8)$ and $(6, 4)$. For the first option $l = 2$, for the second $l = 8$. In both cases Sergey needs $x=y=5$ stops to go to $s$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}. He can perform the following operation any number of times: - Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y. He would like to perform this operation between 0 and 2N times (inclusive) so that a satisfies the condition below. Show one such sequence of operations. It can be proved that such a sequence of operations always exists under the constraints in this problem. - Condition: a_1 \leq a_2 \leq ... \leq a_{N} -----Constraints----- - 2 \leq N \leq 50 - -10^{6} \leq a_i \leq 10^{6} - All input values are integers. -----Input----- Input is given from Standard Input in the following format: N a_1 a_2 ... a_{N} -----Output----- Let m be the number of operations in your solution. In the first line, print m. In the i-th of the subsequent m lines, print the numbers x and y chosen in the i-th operation, with a space in between. The output will be considered correct if m is between 0 and 2N (inclusive) and a satisfies the condition after the m operations. -----Sample Input----- 3 -2 5 -1 -----Sample Output----- 2 2 3 3 3 - After the first operation, a = (-2,5,4). - After the second operation, a = (-2,5,8), and the condition is now satisfied. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is c_{i}. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya. Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k. Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins. -----Input----- The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of coins and the price of the chocolate, respectively. Next line will contain n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 500) — the values of Pari's coins. It's guaranteed that one can make value k using these coins. -----Output----- First line of the output must contain a single integer q— the number of suitable values x. Then print q integers in ascending order — the values that Arya can make for some subset of coins of Pari that pays for the chocolate. -----Examples----- Input 6 18 5 6 1 10 12 2 Output 16 0 1 2 3 5 6 7 8 10 11 12 13 15 16 17 18 Input 3 50 25 25 50 Output 3 0 25 50 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have $n$ coins, each of the same value of $1$. Distribute them into packets such that any amount $x$ ($1 \leq x \leq n$) can be formed using some (possibly one or all) number of these packets. Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single $x$, however it may be reused for the formation of other $x$'s. Find the minimum number of packets in such a distribution. -----Input----- The only line contains a single integer $n$ ($1 \leq n \leq 10^9$) — the number of coins you have. -----Output----- Output a single integer — the minimum possible number of packets, satisfying the condition above. -----Examples----- Input 6 Output 3 Input 2 Output 2 -----Note----- In the first example, three packets with $1$, $2$ and $3$ coins can be made to get any amount $x$ ($1\leq x\leq 6$). To get $1$ use the packet with $1$ coin. To get $2$ use the packet with $2$ coins. To get $3$ use the packet with $3$ coins. To get $4$ use packets with $1$ and $3$ coins. To get $5$ use packets with $2$ and $3$ coins To get $6$ use all packets. In the second example, two packets with $1$ and $1$ coins can be made to get any amount $x$ ($1\leq x\leq 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. Many years have passed, and n friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo. Simply speaking, the process of photographing can be described as follows. Each friend occupies a rectangle of pixels on the photo: the i-th of them in a standing state occupies a w_{i} pixels wide and a h_{i} pixels high rectangle. But also, each person can lie down for the photo, and then he will occupy a h_{i} pixels wide and a w_{i} pixels high rectangle. The total photo will have size W × H, where W is the total width of all the people rectangles, and H is the maximum of the heights. The friends want to determine what minimum area the group photo can they obtain if no more than n / 2 of them can lie on the ground (it would be strange if more than n / 2 gentlemen lie on the ground together, isn't it?..) Help them to achieve this goal. -----Input----- The first line contains integer n (1 ≤ n ≤ 1000) — the number of friends. The next n lines have two integers w_{i}, h_{i} (1 ≤ w_{i}, h_{i} ≤ 1000) each, representing the size of the rectangle, corresponding to the i-th friend. -----Output----- Print a single integer equal to the minimum possible area of the photo containing all friends if no more than n / 2 of them can lie on the ground. -----Examples----- Input 3 10 1 20 2 30 3 Output 180 Input 3 3 1 2 2 4 3 Output 21 Input 1 5 10 Output 50 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most x_{i} boxes on its top (we'll call x_{i} the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile.[Image] Fox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than x_{i} boxes on the top of i-th box. What is the minimal number of piles she needs to construct? -----Input----- The first line contains an integer n (1 ≤ n ≤ 100). The next line contains n integers x_1, x_2, ..., x_{n} (0 ≤ x_{i} ≤ 100). -----Output----- Output a single integer — the minimal possible number of piles. -----Examples----- Input 3 0 0 10 Output 2 Input 5 0 1 2 3 4 Output 1 Input 4 0 0 0 0 Output 4 Input 9 0 1 0 2 0 1 1 2 10 Output 3 -----Note----- In example 1, one optimal way is to build 2 piles: the first pile contains boxes 1 and 3 (from top to bottom), the second pile contains only box 2.[Image] In example 2, we can build only 1 pile that contains boxes 1, 2, 3, 4, 5 (from top to bottom).[Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given N points (x_i,y_i) located on a two-dimensional plane. Consider a subset S of the N points that forms a convex polygon. Here, we say a set of points S forms a convex polygon when there exists a convex polygon with a positive area that has the same set of vertices as S. All the interior angles of the polygon must be strictly less than 180°. For example, in the figure above, {A,C,E} and {B,D,E} form convex polygons; {A,C,D,E}, {A,B,C,E}, {A,B,C}, {D,E} and {} do not. For a given set S, let n be the number of the points among the N points that are inside the convex hull of S (including the boundary and vertices). Then, we will define the score of S as 2^{n-|S|}. Compute the scores of all possible sets S that form convex polygons, and find the sum of all those scores. However, since the sum can be extremely large, print the sum modulo 998244353. -----Constraints----- - 1≤N≤200 - 0≤x_i,y_i<10^4 (1≤i≤N) - If i≠j, x_i≠x_j or y_i≠y_j. - x_i and y_i are integers. -----Input----- The input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N -----Output----- Print the sum of all the scores modulo 998244353. -----Sample Input----- 4 0 0 0 1 1 0 1 1 -----Sample Output----- 5 We have five possible sets as S, four sets that form triangles and one set that forms a square. Each of them has a score of 2^0=1, so the answer is 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. Given an array a_1, a_2, ..., a_{n} of n integers, find the largest number in the array that is not a perfect square. A number x is said to be a perfect square if there exists an integer y such that x = y^2. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^6 ≤ a_{i} ≤ 10^6) — the elements of the array. It is guaranteed that at least one element of the array is not a perfect square. -----Output----- Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists. -----Examples----- Input 2 4 2 Output 2 Input 8 1 2 4 8 16 32 64 576 Output 32 -----Note----- In the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square 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. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration $\frac{a_{i}}{1000}$. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration $\frac{n}{1000}$. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration $\frac{n}{1000}$. Assume that the friends have unlimited amount of each Coke type. -----Input----- The first line contains two integers n, k (0 ≤ n ≤ 1000, 1 ≤ k ≤ 10^6) — carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a_1, a_2, ..., a_{k} (0 ≤ a_{i} ≤ 1000) — carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. -----Output----- Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration $\frac{n}{1000}$, or -1 if it is impossible. -----Examples----- Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 -----Note----- In the first sample case, we can achieve concentration $\frac{400}{1000}$ using one liter of Coke of types $\frac{300}{1000}$ and $\frac{500}{1000}$: $\frac{300 + 500}{1000 + 1000} = \frac{400}{1000}$. In the second case, we can achieve concentration $\frac{50}{1000}$ using two liters of $\frac{25}{1000}$ type and one liter of $\frac{100}{1000}$ type: $\frac{25 + 25 + 100}{3 \cdot 1000} = \frac{50}{1000}$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Kuro and Shiro are playing with a board composed of n squares lining up in a row. The squares are numbered 1 to n from left to right, and Square s has a mark on it. First, for each square, Kuro paints it black or white with equal probability, independently from other squares. Then, he puts on Square s a stone of the same color as the square. Kuro and Shiro will play a game using this board and infinitely many black stones and white stones. In this game, Kuro and Shiro alternately put a stone as follows, with Kuro going first: - Choose an empty square adjacent to a square with a stone on it. Let us say Square i is chosen. - Put on Square i a stone of the same color as the square. - If there are squares other than Square i that contain a stone of the same color as the stone just placed, among such squares, let Square j be the one nearest to Square i. Change the color of every stone between Square i and Square j to the color of Square i. The game ends when the board has no empty square. Kuro plays optimally to maximize the number of black stones at the end of the game, while Shiro plays optimally to maximize the number of white stones at the end of the game. For each of the cases s=1,\dots,n, find the expected value, modulo 998244353, of the number of black stones at the end of the game. -----Notes----- When the expected value in question is represented as an irreducible fraction p/q, there uniquely exists an integer r such that rq=p ~(\text{mod } 998244353) and 0 \leq r \lt 998244353, which we ask you to find. -----Constraints----- - 1 \leq n \leq 2\times 10^5 -----Input----- Input is given from Standard Input in the following format: n -----Output----- Print n values. The i-th value should be the expected value, modulo 998244353, of the number of black stones at the end of the game for the case s=i. -----Sample Input----- 3 -----Sample Output----- 499122178 499122178 499122178 Let us use b to represent a black square and w to represent a white square. There are eight possible boards: www, wwb, wbw, wbb, bww, bwb, bbw, and bbb, which are chosen with equal probability. For each of these boards, there will be 0, 1, 0, 2, 1, 3, 2, and 3 black stones at the end of the game, respectively, regardless of the value of s. Thus, the expected number of stones is (0+1+0+2+1+3+2+3)/8 = 3/2, and the answer is r = 499122178, which satisfies 2r = 3 ~(\text{mod } 998244353) and 0 \leq r \lt 998244353. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A positive integer $a$ is given. Baron Munchausen claims that he knows such a positive integer $n$ that if one multiplies $n$ by $a$, the sum of its digits decreases $a$ times. In other words, $S(an) = S(n)/a$, where $S(x)$ denotes the sum of digits of the number $x$. Find out if what Baron told can be true. -----Input----- The only line contains a single integer $a$ ($2 \le a \le 10^3$). -----Output----- If there is no such number $n$, print $-1$. Otherwise print any appropriate positive integer $n$. Your number must not consist of more than $5\cdot10^5$ digits. We can show that under given constraints either there is no answer, or there is an answer no longer than $5\cdot10^5$ digits. -----Examples----- Input 2 Output 6 Input 3 Output 6669 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. Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not. A permutation triple of permutations of length n (a, b, c) is called a Lucky Permutation Triple if and only if $\forall i(1 \leq i \leq n), a_{i} + b_{i} \equiv c_{i} \operatorname{mod} n$. The sign a_{i} denotes the i-th element of permutation a. The modular equality described above denotes that the remainders after dividing a_{i} + b_{i} by n and dividing c_{i} by n are equal. Now, he has an integer n and wants to find a Lucky Permutation Triple. Could you please help him? -----Input----- The first line contains a single integer n (1 ≤ n ≤ 10^5). -----Output----- If no Lucky Permutation Triple of length n exists print -1. Otherwise, you need to print three lines. Each line contains n space-seperated integers. The first line must contain permutation a, the second line — permutation b, the third — permutation c. If there are multiple solutions, print any of them. -----Examples----- Input 5 Output 1 4 3 2 0 1 0 2 4 3 2 4 0 1 3 Input 2 Output -1 -----Note----- In Sample 1, the permutation triple ([1, 4, 3, 2, 0], [1, 0, 2, 4, 3], [2, 4, 0, 1, 3]) is Lucky Permutation Triple, as following holds: $1 + 1 \equiv 2 \equiv 2 \operatorname{mod} 5$; $4 + 0 \equiv 4 \equiv 4 \operatorname{mod} 5$; $3 + 2 \equiv 0 \equiv 0 \operatorname{mod} 5$; $2 + 4 \equiv 6 \equiv 1 \operatorname{mod} 5$; $0 + 3 \equiv 3 \equiv 3 \operatorname{mod} 5$. In Sample 2, you can easily notice that no lucky permutation triple exists. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process. There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems. You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day. Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days. -----Input----- The first line of input contains three integers n, m and k (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 10^5, 1 ≤ k ≤ 10^6). The i-th of the following m lines contains the description of the i-th flight defined by four integers d_{i}, f_{i}, t_{i} and c_{i} (1 ≤ d_{i} ≤ 10^6, 0 ≤ f_{i} ≤ n, 0 ≤ t_{i} ≤ n, 1 ≤ c_{i} ≤ 10^6, exactly one of f_{i} and t_{i} equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost. -----Output----- Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities. If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes). -----Examples----- Input 2 6 5 1 1 0 5000 3 2 0 5500 2 2 0 6000 15 0 2 9000 9 0 1 7000 8 0 2 6500 Output 24500 Input 2 4 5 1 2 0 5000 2 1 0 4500 2 1 0 3000 8 0 1 6000 Output -1 -----Note----- The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more. In the second sample it is impossible to send jury member from city 2 back home from Metropolis. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle α. [Image] Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture. -----Input----- The first line contains three integers w, h, α (1 ≤ w, h ≤ 10^6; 0 ≤ α ≤ 180). Angle α is given in degrees. -----Output----- In a single line print a real number — the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10^{ - 6}. -----Examples----- Input 1 1 45 Output 0.828427125 Input 6 4 30 Output 19.668384925 -----Note----- The second sample has been drawn on the picture above. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Fox Ciel is playing a card game with her friend Jiro. Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack. Now is Ciel's battle phase, Ciel can do the following operation many times: Choose one of her cards X. This card mustn't be chosen before. If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then: If Y's position is Attack, then (X's strength) ≥ (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength). If Y's position is Defense, then (X's strength) > (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage. Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get. -----Input----- The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of cards Jiro and Ciel have. Each of the next n lines contains a string position and an integer strength (0 ≤ strength ≤ 8000) — the position and strength of Jiro's current card. Position is the string "ATK" for attack, and the string "DEF" for defense. Each of the next m lines contains an integer strength (0 ≤ strength ≤ 8000) — the strength of Ciel's current card. -----Output----- Output an integer: the maximal damage Jiro can get. -----Examples----- Input 2 3 ATK 2000 DEF 1700 2500 2500 2500 Output 3000 Input 3 4 ATK 10 ATK 100 ATK 1000 1 11 101 1001 Output 992 Input 2 4 DEF 0 ATK 0 0 0 1 1 Output 1 -----Note----- In the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack "ATK 2000" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the "DEF 1700" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500 + 2500 = 3000. In the second test case, she should use the "1001" card to attack the "ATK 100" card, then use the "101" card to attack the "ATK 10" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001 - 100) + (101 - 10) = 992. In the third test case note that she can destroy the "ATK 0" card by a card with strength equal to 0, but she can't destroy a "DEF 0" card with that card. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 popular reality show is recruiting a new cast for the third season! $n$ candidates numbered from $1$ to $n$ have been interviewed. The candidate $i$ has aggressiveness level $l_i$, and recruiting this candidate will cost the show $s_i$ roubles. The show host reviewes applications of all candidates from $i=1$ to $i=n$ by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate $i$ is strictly higher than that of any already accepted candidates, then the candidate $i$ will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit. The show makes revenue as follows. For each aggressiveness level $v$ a corresponding profitability value $c_v$ is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant $i$ enters the stage, events proceed as follows: The show makes $c_{l_i}$ roubles, where $l_i$ is initial aggressiveness level of the participant $i$. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes $c_t$ roubles, where $t$ is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates). The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total $s_i$). Help the host to make the show as profitable as possible. -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2000$) — the number of candidates and an upper bound for initial aggressiveness levels. The second line contains $n$ integers $l_i$ ($1 \le l_i \le m$) — initial aggressiveness levels of all candidates. The third line contains $n$ integers $s_i$ ($0 \le s_i \le 5000$) — the costs (in roubles) to recruit each of the candidates. The fourth line contains $n + m$ integers $c_i$ ($|c_i| \le 5000$) — profitability for each aggrressiveness level. It is guaranteed that aggressiveness level of any participant can never exceed $n + m$ under given conditions. -----Output----- Print a single integer — the largest profit of the show. -----Examples----- Input 5 4 4 3 1 2 1 1 2 1 2 1 1 2 3 4 5 6 7 8 9 Output 6 Input 2 2 1 2 0 0 2 1 -100 -100 Output 2 Input 5 4 4 3 2 1 1 0 2 6 7 4 12 12 12 6 -3 -5 3 10 -4 Output 62 -----Note----- In the first sample case it is optimal to recruit candidates $1, 2, 3, 5$. Then the show will pay $1 + 2 + 1 + 1 = 5$ roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level $4$ enters the stage, the show makes $4$ roubles; a participant with aggressiveness level $3$ enters the stage, the show makes $3$ roubles; a participant with aggressiveness level $1$ enters the stage, the show makes $1$ rouble; a participant with aggressiveness level $1$ enters the stage, the show makes $1$ roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to $2$. The show will make extra $2$ roubles for this. Total revenue of the show will be $4 + 3 + 1 + 1 + 2=11$ roubles, and the profit is $11 - 5 = 6$ roubles. In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate $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. Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: They are equal. If we split string a into two halves of the same size a_1 and a_2, and string b into two halves of the same size b_1 and b_2, then one of the following is correct: a_1 is equivalent to b_1, and a_2 is equivalent to b_2 a_1 is equivalent to b_2, and a_2 is equivalent to b_1 As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent. Gerald has already completed this home task. Now it's your turn! -----Input----- The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length. -----Output----- Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise. -----Examples----- Input aaba abaa Output YES Input aabb abab Output NO -----Note----- In the first sample you should split the first string into strings "aa" and "ba", the second one — into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a". In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions (i, j), where i < j, exactly once. MoJaK doesn't like to upset Sajjad. Given the permutation, determine whether it is possible to swap all pairs of positions so that the permutation stays the same. If it is possible find how to do that. -----Input----- The first line contains single integer n (1 ≤ n ≤ 1000) — the size of the permutation. As the permutation is not important, you can consider a_{i} = i, where the permutation is a_1, a_2, ..., a_{n}. -----Output----- If it is not possible to swap all pairs of positions so that the permutation stays the same, print "NO", Otherwise print "YES", then print $\frac{n(n - 1)}{2}$ lines: the i-th of these lines should contain two integers a and b (a < b) — the positions where the i-th swap is performed. -----Examples----- Input 3 Output NO Input 1 Output YES Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarp is a beginner programmer. He is studying how to use a command line. Polycarp faced the following problem. There are n files in a directory and he needs to delete some of them. Polycarp wants to run a single delete command with filename pattern as an argument. All the files to be deleted should match the pattern and all other files shouldn't match the pattern. Polycarp doesn't know about an asterisk '*', the only special character he knows is a question mark '?' which matches any single character. All other characters in the pattern match themselves only. Formally, a pattern matches a filename if and only if they have equal lengths and all characters in the corresponding positions are equal except when the character in the pattern is '?', in which case the corresponding filename character does not matter. For example, the filename pattern "a?ba?": matches filenames "aabaa", "abba.", "a.ba9" and "a.ba."; does not match filenames "aaba", "abaab", "aabaaa" and "aabaa.". Help Polycarp find a pattern which matches files to be deleted and only them or report if there is no such pattern. -----Input----- The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 100) — the total number of files and the number of files to be deleted. The following n lines contain filenames, single filename per line. All filenames are non-empty strings containing only lowercase English letters, digits and dots ('.'). The length of each filename doesn't exceed 100. It is guaranteed that all filenames are distinct. The last line of the input contains m distinct integer numbers in ascending order a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ n) — indices of files to be deleted. All files are indexed from 1 to n in order of their appearance in the input. -----Output----- If the required pattern exists, print "Yes" in the first line of the output. The second line should contain the required pattern. If there are multiple solutions, print any of them. If the required pattern doesn't exist, print the only line containing "No". -----Examples----- Input 3 2 ab ac cd 1 2 Output Yes a? Input 5 3 test tezt test. .est tes. 1 4 5 Output Yes ?es? Input 4 4 a b c dd 1 2 3 4 Output No Input 6 3 .svn .git .... ... .. . 1 2 3 Output Yes .??? Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Given is an integer sequence of length N: A_1, A_2, \cdots, A_N. An integer sequence X, which is also of length N, will be chosen randomly by independently choosing X_i from a uniform distribution on the integers 1, 2, \ldots, A_i for each i (1 \leq i \leq N). Compute the expected value of the length of the longest increasing subsequence of this sequence X, modulo 1000000007. More formally, under the constraints of the problem, we can prove that the expected value can be represented as a rational number, that is, an irreducible fraction \frac{P}{Q}, and there uniquely exists an integer R such that R \times Q \equiv P \pmod {1000000007} and 0 \leq R < 1000000007, so print this integer R. -----Notes----- A subsequence of a sequence X is a sequence obtained by extracting some of the elements of X and arrange them without changing the order. The longest increasing subsequence of a sequence X is the sequence of the greatest length among the strictly increasing subsequences of X. -----Constraints----- - 1 \leq N \leq 6 - 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 \cdots A_N -----Output----- Print the expected value modulo 1000000007. -----Sample Input----- 3 1 2 3 -----Sample Output----- 2 X becomes one of the following, with probability 1/6 for each: - X = (1,1,1), for which the length of the longest increasing subsequence is 1; - X = (1,1,2), for which the length of the longest increasing subsequence is 2; - X = (1,1,3), for which the length of the longest increasing subsequence is 2; - X = (1,2,1), for which the length of the longest increasing subsequence is 2; - X = (1,2,2), for which the length of the longest increasing subsequence is 2; - X = (1,2,3), for which the length of the longest increasing subsequence is 3. Thus, the expected value of the length of the longest increasing subsequence is (1 + 2 + 2 + 2 + 2 + 3) / 6 \equiv 2 \pmod {1000000007}. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 N be an even number. There is a tree with N vertices. The vertices are numbered 1, 2, ..., N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i. Snuke would like to decorate the tree with ribbons, as follows. First, he will divide the N vertices into N / 2 pairs. Here, each vertex must belong to exactly one pair. Then, for each pair (u, v), put a ribbon through all the edges contained in the shortest path between u and v. Snuke is trying to divide the vertices into pairs so that the following condition is satisfied: "for every edge, there is at least one ribbon going through it." How many ways are there to divide the vertices into pairs, satisfying this condition? Find the count modulo 10^9 + 7. Here, two ways to divide the vertices into pairs are considered different when there is a pair that is contained in one of the two ways but not in the other. -----Constraints----- - N is an even number. - 2 \leq N \leq 5000 - 1 \leq x_i, y_i \leq N - The given graph is a tree. -----Input----- Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N - 1} y_{N - 1} -----Output----- Print the number of the ways to divide the vertices into pairs, satisfying the condition, modulo 10^9 + 7. -----Sample Input----- 4 1 2 2 3 3 4 -----Sample Output----- 2 There are three possible ways to divide the vertices into pairs, as shown below, and two satisfy the condition: the middle one and the right one. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position $\lfloor \frac{x}{2} \rfloor$, $x \operatorname{mod} 2$, $\lfloor \frac{x}{2} \rfloor$ sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? -----Input----- The first line contains three integers n, l, r (0 ≤ n < 2^50, 0 ≤ r - l ≤ 10^5, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. -----Output----- Output the total number of 1s in the range l to r in the final sequence. -----Examples----- Input 7 2 5 Output 4 Input 10 3 10 Output 5 -----Note----- Consider first example: $[ 7 ] \rightarrow [ 3,1,3 ] \rightarrow [ 1,1,1,1,3 ] \rightarrow [ 1,1,1,1,1,1,1 ] \rightarrow [ 1,1,1,1,1,1,1 ]$ Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: $[ 10 ] \rightarrow [ 1,0,1,1,1,0,1,0,1,0,1,1,1,0,1 ]$ Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 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. Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure. At each step he selects one of his guests A, who pairwise introduces all of his friends to each other. After this action any two friends of A become friends. This process is run until all pairs of guests are friends. Arseny doesn't want to spend much time doing it, so he wants to finish this process using the minimum number of steps. Help Arseny to do it. -----Input----- The first line contains two integers n and m (1 ≤ n ≤ 22; $0 \leq m \leq \frac{n \cdot(n - 1)}{2}$) — the number of guests at the party (including Arseny) and the number of pairs of people which are friends. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n; u ≠ v), which means that people with numbers u and v are friends initially. It's guaranteed that each pair of friends is described not more than once and the graph of friendship is connected. -----Output----- In the first line print the minimum number of steps required to make all pairs of guests friends. In the second line print the ids of guests, who are selected at each step. If there are multiple solutions, you can output any of them. -----Examples----- Input 5 6 1 2 1 3 2 3 2 5 3 4 4 5 Output 2 2 3 Input 4 4 1 2 1 3 1 4 3 4 Output 1 1 -----Note----- In the first test case there is no guest who is friend of all other guests, so at least two steps are required to perform the task. After second guest pairwise introduces all his friends, only pairs of guests (4, 1) and (4, 2) are not friends. Guest 3 or 5 can introduce them. In the second test case guest number 1 is a friend of all guests, so he can pairwise introduce all guests in one step. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size a_{i} dollars. Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot? -----Input----- First line of input contains an integer n (2 ≤ n ≤ 10^5), the number of players. The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the bids of players. -----Output----- Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise. -----Examples----- Input 4 75 150 75 50 Output Yes Input 3 100 150 250 Output No -----Note----- In the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid. It can be shown that in the second sample test there is no way to make all bids 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. Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav. -----Input----- The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value. -----Output----- In a single line print the answer to the problem — the maximum sum that Yaroslav can get. -----Examples----- Input 2 50 50 50 Output 150 Input 2 -1 -100 -1 Output 100 -----Note----- In the first sample you do not need to change anything. The sum of elements equals 150. In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'. You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string a_{i} of length two and a string b_{i} of length one. No two of q possible operations have the same string a_{i}. When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string a_{i}. Performing the i-th operation removes first two letters of s and inserts there a string b_{i}. See the notes section for further clarification. You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any a_{i}. Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows. -----Input----- The first line contains two integers n and q (2 ≤ n ≤ 6, 1 ≤ q ≤ 36) — the length of the initial string and the number of available operations. The next q lines describe the possible operations. The i-th of them contains two strings a_{i} and b_{i} (|a_{i}| = 2, |b_{i}| = 1). It's guaranteed that a_{i} ≠ a_{j} for i ≠ j and that all a_{i} and b_{i} consist of only first six lowercase English letters. -----Output----- Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input. -----Examples----- Input 3 5 ab a cc c ca a ee c ff d Output 4 Input 2 8 af e dc d cc f bc b da b eb a bb b ff c Output 1 Input 6 2 bb a ba a Output 0 -----Note----- In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a". Other three strings may be compressed as follows: "cab" $\rightarrow$ "ab" $\rightarrow$ "a" "cca" $\rightarrow$ "ca" $\rightarrow$ "a" "eea" $\rightarrow$ "ca" $\rightarrow$ "a" In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation. A set ρ of pairs (a, b) of elements of some set A is called a binary relation on set A. For two elements a and b of the set A we say that they are in relation ρ, if pair $(a, b) \in \rho$, in this case we use a notation $a \stackrel{\rho}{\sim} b$. Binary relation is equivalence relation, if: It is reflexive (for any a it is true that $a \stackrel{\rho}{\sim} a$); It is symmetric (for any a, b it is true that if $a \stackrel{\rho}{\sim} b$, then $b \stackrel{\rho}{\sim} a$); It is transitive (if $a \stackrel{\rho}{\sim} b$ and $b \stackrel{\rho}{\sim} c$, than $a \stackrel{\rho}{\sim} c$). Little Johnny is not completely a fool and he noticed that the first condition is not necessary! Here is his "proof": Take any two elements, a and b. If $a \stackrel{\rho}{\sim} b$, then $b \stackrel{\rho}{\sim} a$ (according to property (2)), which means $a \stackrel{\rho}{\sim} a$ (according to property (3)). It's very simple, isn't it? However, you noticed that Johnny's "proof" is wrong, and decided to show him a lot of examples that prove him wrong. Here's your task: count the number of binary relations over a set of size n such that they are symmetric, transitive, but not an equivalence relations (i.e. they are not reflexive). Since their number may be very large (not 0, according to Little Johnny), print the remainder of integer division of this number by 10^9 + 7. -----Input----- A single line contains a single integer n (1 ≤ n ≤ 4000). -----Output----- In a single line print the answer to the problem modulo 10^9 + 7. -----Examples----- Input 1 Output 1 Input 2 Output 3 Input 3 Output 10 -----Note----- If n = 1 there is only one such relation — an empty one, i.e. $\rho = \varnothing$. In other words, for a single element x of set A the following is hold: [Image]. If n = 2 there are three such relations. Let's assume that set A consists of two elements, x and y. Then the valid relations are $\rho = \varnothing$, ρ = {(x, x)}, ρ = {(y, y)}. It is easy to see that the three listed binary relations are symmetric and transitive relations, but they are not equivalence relations. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. -----Input----- Only one line containing two positive integers a and b (1 ≤ a, b ≤ 10^9). -----Output----- Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10^{ - 9}. If there is no such x then output - 1 as the answer. -----Examples----- Input 3 1 Output 1.000000000000 Input 1 3 Output -1 Input 4 1 Output 1.250000000000 -----Note----- You can see following graphs for sample 1 and sample 3. [Image] [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs $(i + j) \operatorname{mod}(n + 1)$ and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of schools. -----Output----- Print single integer: the minimum cost of tickets needed to visit all schools. -----Examples----- Input 2 Output 0 Input 10 Output 4 -----Note----- In the first example we can buy a ticket between the schools that costs $(1 + 2) \operatorname{mod}(2 + 1) = 0$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. What are you doing at the end of the world? Are you busy? Will you save us? [Image] Nephren is playing a game with little leprechauns. She gives them an infinite array of strings, f_{0... ∞}. f_0 is "What are you doing at the end of the world? Are you busy? Will you save us?". She wants to let more people know about it, so she defines f_{i} = "What are you doing while sending "f_{i} - 1"? Are you busy? Will you send "f_{i} - 1"?" for all i ≥ 1. For example, f_1 is "What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of f_1. It can be seen that the characters in f_{i} are letters, question marks, (possibly) quotation marks and spaces. Nephren will ask the little leprechauns q times. Each time she will let them find the k-th character of f_{n}. The characters are indexed starting from 1. If f_{n} consists of less than k characters, output '.' (without quotes). Can you answer her queries? -----Input----- The first line contains one integer q (1 ≤ q ≤ 10) — the number of Nephren's questions. Each of the next q lines describes Nephren's question and contains two integers n and k (0 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^18). -----Output----- One line containing q characters. The i-th character in it should be the answer for the i-th query. -----Examples----- Input 3 1 1 1 2 1 111111111111 Output Wh. Input 5 0 69 1 194 1 139 0 47 1 66 Output abdef Input 10 4 1825 3 75 3 530 4 1829 4 1651 3 187 4 584 4 255 4 774 2 474 Output Areyoubusy -----Note----- For the first two examples, refer to f_0 and f_1 given in the legend. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds. -----Input----- The only line of the input contains a rebus. It's guaranteed that it contains no more than 100 question marks, integer n is positive and doesn't exceed 1 000 000, all letters and integers are separated by spaces, arithmetic operations are located only between question marks. -----Output----- The first line of the output should contain "Possible" (without quotes) if rebus has a solution and "Impossible" (without quotes) otherwise. If the answer exists, the second line should contain any valid rebus with question marks replaced by integers from 1 to n. Follow the format given in the samples. -----Examples----- Input ? + ? - ? + ? + ? = 42 Output Possible 9 + 13 - 39 + 28 + 31 = 42 Input ? - ? = 1 Output Impossible Input ? = 1000000 Output Possible 1000000 = 1000000 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Consider an N \times N matrix. Let us denote by a_{i, j} the entry in the i-th row and j-th column. For a_{i, j} where i=1 or j=1 holds, its value is one of 0, 1 and 2 and given in the input. The remaining entries are defined as follows: - a_{i,j} = \mathrm{mex}(a_{i-1,j}, a_{i,j-1}) (2 \leq i, j \leq N) where \mathrm{mex}(x, y) is defined by the following table:\mathrm{mex}(x, y)y=0y=1y=2x=0121x=1200x=2100 How many entries of the matrix are 0, 1, and 2, respectively? -----Constraints----- - 1 \leq N \leq 500{,}000 - a_{i,j}'s given in input are one of 0, 1 and 2. -----Input----- Input is given from Standard Input in the following format: N a_{1, 1} a_{1, 1} ... a_{1, N} a_{2, 1} : a_{N, 1} -----Output----- Print the number of 0's, 1's, and 2's separated by whitespaces. -----Sample Input----- 4 1 2 0 2 0 0 0 -----Sample Output----- 7 4 5 The matrix is as follows: 1 2 0 2 0 1 2 0 0 2 0 1 0 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. Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive. The committee rules strictly prohibit even the smallest diversity between doggos and hence all the puppies should be of the same color. Thus Slava, the committee employee, has been assigned the task to recolor some puppies into other colors in order to eliminate the difference and make all the puppies have one common color. Unfortunately, due to bureaucratic reasons and restricted budget, there's only one operation Slava can perform: he can choose a color $x$ such that there are currently at least two puppies of color $x$ and recolor all puppies of the color $x$ into some arbitrary color $y$. Luckily, this operation can be applied multiple times (including zero). For example, if the number of puppies is $7$ and their colors are represented as the string "abababc", then in one operation Slava can get the results "zbzbzbc", "bbbbbbc", "aaaaaac", "acacacc" and others. However, if the current color sequence is "abababc", then he can't choose $x$='c' right now, because currently only one puppy has the color 'c'. Help Slava and the committee determine whether it is possible to standardize all the puppies, i.e. after Slava's operations all the puppies should have the same color. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of puppies. The second line contains a string $s$ of length $n$ consisting of lowercase Latin letters, where the $i$-th symbol denotes the $i$-th puppy's color. -----Output----- If it's possible to recolor all puppies into one color, print "Yes". Otherwise print "No". Output the answer without quotation signs. -----Examples----- Input 6 aabddc Output Yes Input 3 abc Output No Input 3 jjj Output Yes -----Note----- In the first example Slava can perform the following steps: take all puppies of color 'a' (a total of two) and recolor them into 'b'; take all puppies of color 'd' (a total of two) and recolor them into 'c'; take all puppies of color 'b' (three puppies for now) and recolor them into 'c'. In the second example it's impossible to recolor any of the puppies. In the third example all the puppies' colors are the same; thus there's no need to recolor anything. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer p_{i} (1 ≤ p_{i} ≤ n). Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house p_{x}), then he goes to the house whose number is written on the plaque of house p_{x} (that is, to house p_{p}_{x}), and so on. We know that: When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house. You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (10^9 + 7). -----Input----- The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the number k from the statement. -----Output----- In a single line print a single integer — the answer to the problem modulo 1000000007 (10^9 + 7). -----Examples----- Input 5 2 Output 54 Input 7 4 Output 1728 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Consider a table of size $n \times m$, initially fully white. Rows are numbered $1$ through $n$ from top to bottom, columns $1$ through $m$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square. -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n, m \le 115$) — the number of rows and the number of columns in the table. The $i$-th of the next $n$ lines contains a string of $m$ characters $s_{i1} s_{i2} \ldots s_{im}$ ($s_{ij}$ is 'W' for white cells and 'B' for black cells), describing the $i$-th row of the table. -----Output----- Output two integers $r$ and $c$ ($1 \le r \le n$, $1 \le c \le m$) separated by a space — the row and column numbers of the center of the black square. -----Examples----- Input 5 6 WWBBBW WWBBBW WWBBBW WWWWWW WWWWWW Output 2 4 Input 3 3 WWW BWW WWW Output 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. This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled. Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described. Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). [Image] The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible. Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there. -----Input----- The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 100$; $1 \leq m \leq 200$) — the number of stations and the number of candies, respectively. The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$; $a_i \neq b_i$) — the station that initially contains candy $i$ and the destination station of the candy, respectively. -----Output----- In the first and only line, print $n$ space-separated integers, the $i$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $i$. -----Examples----- Input 5 7 2 4 5 1 2 3 3 4 4 1 5 3 3 5 Output 10 9 10 10 9 Input 2 3 1 2 1 2 1 2 Output 5 6 -----Note----- Consider the second sample. If the train started at station $1$, the optimal strategy is as follows. Load the first candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the first candy. Proceed to station $1$. This step takes $1$ second. Load the second candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the second candy. Proceed to station $1$. This step takes $1$ second. Load the third candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the third candy. Hence, the train needs $5$ seconds to complete the tasks. If the train were to start at station $2$, however, it would need to move to station $1$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $5+1 = 6$ seconds. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation a_{i}x + b_{i}y + c_{i} = 0, where a_{i} and b_{i} are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect. Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step). Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road. -----Input----- The first line contains two space-separated integers x_1, y_1 ( - 10^6 ≤ x_1, y_1 ≤ 10^6) — the coordinates of your home. The second line contains two integers separated by a space x_2, y_2 ( - 10^6 ≤ x_2, y_2 ≤ 10^6) — the coordinates of the university you are studying at. The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 10^6 ≤ a_{i}, b_{i}, c_{i} ≤ 10^6; |a_{i}| + |b_{i}| > 0) — the coefficients of the line a_{i}x + b_{i}y + c_{i} = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines). -----Output----- Output the answer to the problem. -----Examples----- Input 1 1 -1 -1 2 0 1 0 1 0 0 Output 2 Input 1 1 -1 -1 3 1 0 0 0 1 0 1 1 -3 Output 2 -----Note----- Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): [Image] [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem. Let [n] denote the set {1, ..., n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y. Now then, you are given a function f: [n] → [n]. Your task is to find a positive integer m, and two functions g: [n] → [m], h: [m] → [n], such that g(h(x)) = x for all $x \in [ m ]$, and h(g(x)) = f(x) for all $x \in [ n ]$, or determine that finding these is impossible. -----Input----- The first line contains an integer n (1 ≤ n ≤ 10^5). The second line contains n space-separated integers — values f(1), ..., f(n) (1 ≤ f(i) ≤ n). -----Output----- If there is no answer, print one integer -1. Otherwise, on the first line print the number m (1 ≤ m ≤ 10^6). On the second line print n numbers g(1), ..., g(n). On the third line print m numbers h(1), ..., h(m). If there are several correct answers, you may output any of them. It is guaranteed that if a valid answer exists, then there is an answer satisfying the above restrictions. -----Examples----- Input 3 1 2 3 Output 3 1 2 3 1 2 3 Input 3 2 2 2 Output 1 1 1 1 2 Input 2 2 1 Output -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2^{n} members and coincidentally Natalia Fan Club also has 2^{n} members. Each member of MDC is assigned a unique id i from 0 to 2^{n} - 1. The same holds for each member of NFC. One of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers (a, b) such that member a from MDC dances with member b from NFC. The complexity of a pairs' assignment is the number of pairs of dancing pairs (a, b) and (c, d) such that a < c and b > d. You are given a binary number of length n named x. We know that member i from MDC dances with member $i \oplus x$ from NFC. Your task is to calculate the complexity of this assignment modulo 1000000007 (10^9 + 7). Expression $x \oplus y$ denotes applying «XOR» to numbers x and y. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as «^», in Pascal — «xor». -----Input----- The first line of input contains a binary number x of lenght n, (1 ≤ n ≤ 100). This number may contain leading zeros. -----Output----- Print the complexity of the given dance assignent modulo 1000000007 (10^9 + 7). -----Examples----- Input 11 Output 6 Input 01 Output 2 Input 1 Output 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal. The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal. Determine if it is possible for the islanders to arrange the statues in the desired order. -----Input----- The first line contains a single integer n (2 ≤ n ≤ 200 000) — the total number of islands. The second line contains n space-separated integers a_{i} (0 ≤ a_{i} ≤ n - 1) — the statue currently placed on the i-th island. If a_{i} = 0, then the island has no statue. It is guaranteed that the a_{i} are distinct. The third line contains n space-separated integers b_{i} (0 ≤ b_{i} ≤ n - 1) — the desired statues of the ith island. Once again, b_{i} = 0 indicates the island desires no statue. It is guaranteed that the b_{i} are distinct. -----Output----- Print "YES" (without quotes) if the rearrangement can be done in the existing network, and "NO" otherwise. -----Examples----- Input 3 1 0 2 2 0 1 Output YES Input 2 1 0 0 1 Output YES Input 4 1 2 3 0 0 3 2 1 Output NO -----Note----- In the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3. In the second sample, the islanders can simply move statue 1 from island 1 to island 2. In the third sample, no sequence of movements results in the desired position. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume. You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned. If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible. Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 50) — the number of tasks. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^8), where a_{i} represents the amount of power required for the i-th task. The third line contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 100), where b_{i} is the number of processors that i-th task will utilize. -----Output----- Print a single integer value — the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up. -----Examples----- Input 6 8 10 9 9 8 10 1 1 1 1 1 1 Output 9000 Input 6 8 10 9 9 8 10 1 10 5 5 1 10 Output 1160 -----Note----- In the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9. In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!' The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least p of n coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects? Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting. -----Input----- The first line contains integers n and p (3 ≤ n ≤ 3·10^5; 0 ≤ p ≤ n) — the number of coders in the F company and the minimum number of agreed people. Each of the next n lines contains two integers x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ n) — the numbers of coders named by the i-th coder. It is guaranteed that x_{i} ≠ i,  y_{i} ≠ i,  x_{i} ≠ y_{i}. -----Output----- Print a single integer –– the number of possible two-suspect sets. Note that the order of the suspects doesn't matter, that is, sets (1, 2) и (2, 1) are considered identical. -----Examples----- Input 4 2 2 3 1 4 1 4 2 1 Output 6 Input 8 6 5 6 5 7 5 8 6 2 2 1 7 3 1 3 1 4 Output 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the greatest common divisor. What is the minimum number of operations you need to make all of the elements equal to 1? -----Input----- The first line of the input contains one integer n (1 ≤ n ≤ 2000) — the number of elements in the array. The second line contains n space separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the elements of the array. -----Output----- Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1. -----Examples----- Input 5 2 2 3 4 6 Output 5 Input 4 2 4 6 8 Output -1 Input 3 2 6 9 Output 4 -----Note----- In the first sample you can turn all numbers to 1 using the following 5 moves: [2, 2, 3, 4, 6]. [2, 1, 3, 4, 6] [2, 1, 3, 1, 6] [2, 1, 1, 1, 6] [1, 1, 1, 1, 6] [1, 1, 1, 1, 1] We can prove that in this case it is not possible to make all numbers one using less than 5 moves. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word — some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction — it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: [Image], where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. -----Input----- The only line contains a string s (5 ≤ |s| ≤ 10^4) consisting of lowercase English letters. -----Output----- On the first line print integer k — a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. -----Examples----- Input abacabaca Output 3 aca ba ca Input abaca Output 0 -----Note----- The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State. Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable. Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells. It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it. -----Input----- The first line of the input contains the dimensions of the map n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns respectively. Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell. -----Output----- Print a single integer — the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1. -----Examples----- Input 4 5 11..2 #..22 #.323 .#333 Output 2 Input 1 5 1#2#3 Output -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know. Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation. The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $l$ nanoseconds, where $l$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take $2$ nanoseconds). Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 10^6$) — the length of Dima's sequence. The second line contains string of length $n$, consisting of characters "(" and ")" only. -----Output----- Print a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so. -----Examples----- Input 8 ))((())( Output 6 Input 3 (() Output -1 -----Note----- In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is $4 + 2 = 6$ nanoseconds. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. BigData Inc. is a corporation that has n data centers indexed from 1 to n that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!). Main feature of services offered by BigData Inc. is the access availability guarantee even under the circumstances of any data center having an outage. Such a guarantee is ensured by using the two-way replication. Two-way replication is such an approach for data storage that any piece of data is represented by two identical copies that are stored in two different data centers. For each of m company clients, let us denote indices of two different data centers storing this client data as c_{i}, 1 and c_{i}, 2. In order to keep data centers operational and safe, the software running on data center computers is being updated regularly. Release cycle of BigData Inc. is one day meaning that the new version of software is being deployed to the data center computers each day. Data center software update is a non-trivial long process, that is why there is a special hour-long time frame that is dedicated for data center maintenance. During the maintenance period, data center computers are installing software updates, and thus they may be unavailable. Consider the day to be exactly h hours long. For each data center there is an integer u_{j} (0 ≤ u_{j} ≤ h - 1) defining the index of an hour of day, such that during this hour data center j is unavailable due to maintenance. Summing up everything above, the condition u_{c}_{i}, 1 ≠ u_{c}_{i}, 2 should hold for each client, or otherwise his data may be unaccessible while data centers that store it are under maintenance. Due to occasional timezone change in different cities all over the world, the maintenance time in some of the data centers may change by one hour sometimes. Company should be prepared for such situation, that is why they decided to conduct an experiment, choosing some non-empty subset of data centers, and shifting the maintenance time for them by an hour later (i.e. if u_{j} = h - 1, then the new maintenance hour would become 0, otherwise it would become u_{j} + 1). Nonetheless, such an experiment should not break the accessibility guarantees, meaning that data of any client should be still available during any hour of a day after the data center maintenance times are changed. Such an experiment would provide useful insights, but changing update time is quite an expensive procedure, that is why the company asked you to find out the minimum number of data centers that have to be included in an experiment in order to keep the data accessibility guarantees. -----Input----- The first line of input contains three integers n, m and h (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000, 2 ≤ h ≤ 100 000), the number of company data centers, number of clients and the day length of day measured in hours. The second line of input contains n integers u_1, u_2, ..., u_{n} (0 ≤ u_{j} < h), j-th of these numbers is an index of a maintenance hour for data center j. Each of the next m lines contains two integers c_{i}, 1 and c_{i}, 2 (1 ≤ c_{i}, 1, c_{i}, 2 ≤ n, c_{i}, 1 ≠ c_{i}, 2), defining the data center indices containing the data of client i. It is guaranteed that the given maintenance schedule allows each client to access at least one copy of his data at any moment of day. -----Output----- In the first line print the minimum possible number of data centers k (1 ≤ k ≤ n) that have to be included in an experiment in order to keep the data available for any client. In the second line print k distinct integers x_1, x_2, ..., x_{k} (1 ≤ x_{i} ≤ n), the indices of data centers whose maintenance time will be shifted by one hour later. Data center indices may be printed in any order. If there are several possible answers, it is allowed to print any of them. It is guaranteed that at there is at least one valid choice of data centers. -----Examples----- Input 3 3 5 4 4 0 1 3 3 2 3 1 Output 1 3 Input 4 5 4 2 1 0 3 4 3 3 2 1 2 1 4 1 3 Output 4 1 2 3 4 -----Note----- Consider the first sample test. The given answer is the only way to conduct an experiment involving the only data center. In such a scenario the third data center has a maintenance during the hour 1, and no two data centers storing the information of the same client have maintenance at the same hour. On the other hand, for example, if we shift the maintenance time on hour later for the first data center, then the data of clients 1 and 3 will be unavailable during the hour 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. Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area. To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of $n$ rows and $m$ columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side. Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo $10^9 + 7$. -----Input----- The only line contains two integers $n$ and $m$ ($1 \le n, m \le 100\,000$), the number of rows and the number of columns of the field. -----Output----- Print one integer, the number of random pictures modulo $10^9 + 7$. -----Example----- Input 2 3 Output 8 -----Note----- The picture below shows all possible random pictures of size $2$ by $3$. [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's call an array consisting of n integer numbers a_1, a_2, ..., a_{n}, beautiful if it has the following property: consider all pairs of numbers x, y (x ≠ y), such that number x occurs in the array a and number y occurs in the array a; for each pair x, y must exist some position j (1 ≤ j < n), such that at least one of the two conditions are met, either a_{j} = x, a_{j} + 1 = y, or a_{j} = y, a_{j} + 1 = x. Sereja wants to build a beautiful array a, consisting of n integers. But not everything is so easy, Sereja's friend Dima has m coupons, each contains two integers q_{i}, w_{i}. Coupon i costs w_{i} and allows you to use as many numbers q_{i} as you want when constructing the array a. Values q_{i} are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array a of n elements. After that he takes w_{i} rubles from Sereja for each q_{i}, which occurs in the array a. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay. Help Sereja, find the maximum amount of money he can pay to Dima. -----Input----- The first line contains two integers n and m (1 ≤ n ≤ 2·10^6, 1 ≤ m ≤ 10^5). Next m lines contain pairs of integers. The i-th line contains numbers q_{i}, w_{i} (1 ≤ q_{i}, w_{i} ≤ 10^5). It is guaranteed that all q_{i} are distinct. -----Output----- In a single line print maximum amount of money (in rubles) Sereja can pay. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 5 2 1 2 2 3 Output 5 Input 100 3 1 2 2 1 3 1 Output 4 Input 1 2 1 1 2 100 Output 100 -----Note----- In the first sample Sereja can pay 5 rubles, for example, if Dima constructs the following array: [1, 2, 1, 2, 2]. There are another optimal arrays for this test. In the third sample Sereja can pay 100 rubles, if Dima constructs the following array: [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. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string $s$ of lowercase Latin letters. She considers a string $t$ as hidden in string $s$ if $t$ exists as a subsequence of $s$ whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices $1$, $3$, and $5$, which form an arithmetic progression with a common difference of $2$. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of $S$ are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden $3$ times, b is hidden $2$ times, ab is hidden $6$ times, aa is hidden $3$ times, bb is hidden $1$ time, aab is hidden $2$ times, aaa is hidden $1$ time, abb is hidden $1$ time, aaab is hidden $1$ time, aabb is hidden $1$ time, and aaabb is hidden $1$ time. The number of occurrences of the secret message is $6$. -----Input----- The first line contains a string $s$ of lowercase Latin letters ($1 \le |s| \le 10^5$) — the text that Bessie intercepted. -----Output----- Output a single integer  — the number of occurrences of the secret message. -----Examples----- Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 -----Note----- In the first example, these are all the hidden strings and their indice sets: a occurs at $(1)$, $(2)$, $(3)$ b occurs at $(4)$, $(5)$ ab occurs at $(1,4)$, $(1,5)$, $(2,4)$, $(2,5)$, $(3,4)$, $(3,5)$ aa occurs at $(1,2)$, $(1,3)$, $(2,3)$ bb occurs at $(4,5)$ aab occurs at $(1,3,5)$, $(2,3,4)$ aaa occurs at $(1,2,3)$ abb occurs at $(3,4,5)$ aaab occurs at $(1,2,3,4)$ aabb occurs at $(2,3,4,5)$ aaabb occurs at $(1,2,3,4,5)$ Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen. One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get? The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of n marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least n marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want. -----Input----- The single line contains a single integer n (1 ≤ n ≤ 10^17). Please, do not use the %lld specifier to read or write 64 bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Output----- In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with. -----Examples----- Input 1 Output 1 Input 4 Output 2 -----Note----- In the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change. In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Note that girls in Arpa’s land are really attractive. Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the a_{i}-th chair, and his girlfriend, sitting on the b_{i}-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair. [Image] There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that: Each person had exactly one type of food, No boy had the same type of food as his girlfriend, Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive. Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions. -----Input----- The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of pairs of guests. The i-th of the next n lines contains a pair of integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 2n) — the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair. -----Output----- If there is no solution, print -1. Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2. If there are multiple solutions, print any of them. -----Example----- Input 3 1 4 2 5 3 6 Output 1 2 2 1 1 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Your friend recently gave you some slimes for your birthday. You have n slimes all initially with value 1. You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other n - 1 slimes one by one. When you add a slime, you place it at the right of all already placed slimes. Then, while the last two slimes in the row have the same value v, you combine them together to create a slime with value v + 1. You would like to see what the final state of the row is after you've added all n slimes. Please print the values of the slimes in the row from left to right. -----Input----- The first line of the input will contain a single integer, n (1 ≤ n ≤ 100 000). -----Output----- Output a single line with k integers, where k is the number of slimes in the row after you've finished the procedure described in the problem statement. The i-th of these numbers should be the value of the i-th slime from the left. -----Examples----- Input 1 Output 1 Input 2 Output 2 Input 3 Output 2 1 Input 8 Output 4 -----Note----- In the first sample, we only have a single slime with value 1. The final state of the board is just a single slime with value 1. In the second sample, we perform the following steps: Initially we place a single slime in a row by itself. Thus, row is initially 1. Then, we will add another slime. The row is now 1 1. Since two rightmost slimes have the same values, we should replace these slimes with one with value 2. Thus, the final state of the board is 2. In the third sample, after adding the first two slimes, our row is 2. After adding one more slime, the row becomes 2 1. In the last sample, the steps look as follows: 1 2 2 1 3 3 1 3 2 3 2 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. Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits. He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar. Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings. -----Input----- The first line contains an integer n (1 ≤ n ≤ 4·10^5) — the length of string s. The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits. -----Output----- Print to the first line an integer k — minimum number of palindromes into which you can cut a given string. Print to the second line k strings — the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length. -----Examples----- Input 6 aabaac Output 2 aba aca Input 8 0rTrT022 Output 1 02TrrT20 Input 2 aA Output 2 a A Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden. The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1). Polycarpus knows m words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these m words. At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed. It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed. Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters. -----Input----- The first line contains one integer n (1 ≤ n ≤ 50) — the length of the hidden word. The following line describes already revealed letters. It contains the string of length n, which consists of lowercase Latin letters and symbols "*". If there is a letter at some position, then this letter was already revealed. If the position contains symbol "*", then the letter at this position has not been revealed yet. It is guaranteed, that at least one letter is still closed. The third line contains an integer m (1 ≤ m ≤ 1000) — the number of words of length n, which Polycarpus knows. The following m lines contain the words themselves — n-letter strings of lowercase Latin letters. All words are distinct. It is guaranteed that the hidden word appears as one of the given m words. Before the current move Polycarp has told exactly the letters which are currently revealed. -----Output----- Output the single integer — the number of letters Polycarpus can tell so that the TV show host definitely reveals at least one more letter. It is possible that this number is zero. -----Examples----- Input 4 a**d 2 abcd acbd Output 2 Input 5 lo*er 2 lover loser Output 0 Input 3 a*a 2 aaa aba Output 1 -----Note----- In the first example Polycarpus can tell letters "b" and "c", which assuredly will be revealed. The second example contains no letters which can be told as it is not clear, which of the letters "v" or "s" is located at the third position of the hidden word. In the third example Polycarpus exactly knows that the hidden word is "aba", because in case it was "aaa", then the second letter "a" would have already been revealed in one of previous turns. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Instructors of Some Informatics School make students go to bed. The house contains n rooms, in each room exactly b students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to n. Initially, in i-th room there are a_{i} students. All students are currently somewhere in the house, therefore a_1 + a_2 + ... + a_{n} = nb. Also 2 instructors live in this house. The process of curfew enforcement is the following. One instructor starts near room 1 and moves toward room n, while the second instructor starts near room n and moves toward room 1. After processing current room, each instructor moves on to the next one. Both instructors enter rooms and move simultaneously, if n is odd, then only the first instructor processes the middle room. When all rooms are processed, the process ends. When an instructor processes a room, she counts the number of students in the room, then turns off the light, and locks the room. Also, if the number of students inside the processed room is not equal to b, the instructor writes down the number of this room into her notebook (and turns off the light, and locks the room). Instructors are in a hurry (to prepare the study plan for the next day), so they don't care about who is in the room, but only about the number of students. While instructors are inside the rooms, students can run between rooms that are not locked and not being processed. A student can run by at most d rooms, that is she can move to a room with number that differs my at most d. Also, after (or instead of) running each student can hide under a bed in a room she is in. In this case the instructor will not count her during the processing. In each room any number of students can hide simultaneously. Formally, here is what's happening: A curfew is announced, at this point in room i there are a_{i} students. Each student can run to another room but not further than d rooms away from her initial room, or stay in place. After that each student can optionally hide under a bed. Instructors enter room 1 and room n, they count students there and lock the room (after it no one can enter or leave this room). Each student from rooms with numbers from 2 to n - 1 can run to another room but not further than d rooms away from her current room, or stay in place. Each student can optionally hide under a bed. Instructors move from room 1 to room 2 and from room n to room n - 1. This process continues until all rooms are processed. Let x_1 denote the number of rooms in which the first instructor counted the number of non-hidden students different from b, and x_2 be the same number for the second instructor. Students know that the principal will only listen to one complaint, therefore they want to minimize the maximum of numbers x_{i}. Help them find this value if they use the optimal strategy. -----Input----- The first line contains three integers n, d and b (2 ≤ n ≤ 100 000, 1 ≤ d ≤ n - 1, 1 ≤ b ≤ 10 000), number of rooms in the house, running distance of a student, official number of students in a room. The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9), i-th of which stands for the number of students in the i-th room before curfew announcement. It is guaranteed that a_1 + a_2 + ... + a_{n} = nb. -----Output----- Output one integer, the minimal possible value of the maximum of x_{i}. -----Examples----- Input 5 1 1 1 0 0 0 4 Output 1 Input 6 1 2 3 8 0 1 0 0 Output 2 -----Note----- In the first sample the first three rooms are processed by the first instructor, and the last two are processed by the second instructor. One of the optimal strategies is the following: firstly three students run from room 5 to room 4, on the next stage two of them run to room 3, and one of those two hides under a bed. This way, the first instructor writes down room 2, and the second writes down nothing. In the second sample one of the optimal strategies is the following: firstly all students in room 1 hide, all students from room 2 run to room 3. On the next stage one student runs from room 3 to room 4, and 5 students hide. This way, the first instructor writes down rooms 1 and 2, the second instructor writes down rooms 5 and 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. Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this! Let us remind you that a number is called prime if it is integer larger than one, and is not divisible by any positive integer other than itself and one. Rikhail calls a number a palindromic if it is integer, positive, and its decimal representation without leading zeros is a palindrome, i.e. reads the same from left to right and right to left. One problem with prime numbers is that there are too many of them. Let's introduce the following notation: π(n) — the number of primes no larger than n, rub(n) — the number of palindromic numbers no larger than n. Rikhail wants to prove that there are a lot more primes than palindromic ones. He asked you to solve the following problem: for a given value of the coefficient A find the maximum n, such that π(n) ≤ A·rub(n). -----Input----- The input consists of two positive integers p, q, the numerator and denominator of the fraction that is the value of A ($A = \frac{p}{q}$, $p, q \leq 10^{4}, \frac{1}{42} \leq \frac{p}{q} \leq 42$). -----Output----- If such maximum number exists, then print it. Otherwise, print "Palindromic tree is better than splay tree" (without the quotes). -----Examples----- Input 1 1 Output 40 Input 1 42 Output 1 Input 6 4 Output 172 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Æsir - CHAOS Æsir - V. "Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect. The time right now...... 00:01:12...... It's time." The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa. The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers ($1, 2, 3, \ldots$). The node with a number $x$ ($x > 1$), is directly connected with a node with number $\frac{x}{f(x)}$, with $f(x)$ being the lowest prime divisor of $x$. Vanessa's mind is divided into $n$ fragments. Due to more than 500 years of coma, the fragments have been scattered: the $i$-th fragment is now located at the node with a number $k_i!$ (a factorial of $k_i$). To maximize the chance of successful awakening, Ivy decides to place the samples in a node $P$, so that the total length of paths from each fragment to $P$ is smallest possible. If there are multiple fragments located at the same node, the path from that node to $P$ needs to be counted multiple times. In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node. But for a mere human like you, is this still possible? For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node $P$. -----Input----- The first line contains an integer $n$ ($1 \le n \le 10^6$) — number of fragments of Vanessa's mind. The second line contains $n$ integers: $k_1, k_2, \ldots, k_n$ ($0 \le k_i \le 5000$), denoting the nodes where fragments of Vanessa's mind are located: the $i$-th fragment is at the node with a number $k_i!$. -----Output----- Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node $P$). As a reminder, if there are multiple fragments at the same node, the distance from that node to $P$ needs to be counted multiple times as well. -----Examples----- Input 3 2 1 4 Output 5 Input 4 3 1 4 4 Output 6 Input 4 3 1 4 1 Output 6 Input 5 3 1 4 1 5 Output 11 -----Note----- Considering the first $24$ nodes of the system, the node network will look as follows (the nodes $1!$, $2!$, $3!$, $4!$ are drawn bold): [Image] For the first example, Ivy will place the emotion samples at the node $1$. From here: The distance from Vanessa's first fragment to the node $1$ is $1$. The distance from Vanessa's second fragment to the node $1$ is $0$. The distance from Vanessa's third fragment to the node $1$ is $4$. The total length is $5$. For the second example, the assembly node will be $6$. From here: The distance from Vanessa's first fragment to the node $6$ is $0$. The distance from Vanessa's second fragment to the node $6$ is $2$. The distance from Vanessa's third fragment to the node $6$ is $2$. The distance from Vanessa's fourth fragment to the node $6$ is again $2$. The total path length is $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.