question
large_stringlengths
265
13.2k
Solve the programming task below in a Python markdown code block. Wherever the destination is, whoever we meet, let's render this song together. On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage. On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups: Vertical: stands at (x_{i}, 0), moves in positive y direction (upwards); Horizontal: stands at (0, y_{i}), moves in positive x direction (rightwards). [Image] According to choreography, the i-th dancer should stand still for the first t_{i} milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time. When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on. [Image] Dancers stop when a border of the stage is reached. Find out every dancer's stopping position. -----Input----- The first line of input contains three space-separated positive integers n, w and h (1 ≤ n ≤ 100 000, 2 ≤ w, h ≤ 100 000) — the number of dancers and the width and height of the stage, respectively. The following n lines each describes a dancer: the i-th among them contains three space-separated integers g_{i}, p_{i}, and t_{i} (1 ≤ g_{i} ≤ 2, 1 ≤ p_{i} ≤ 99 999, 0 ≤ t_{i} ≤ 100 000), describing a dancer's group g_{i} (g_{i} = 1 — vertical, g_{i} = 2 — horizontal), position, and waiting time. If g_{i} = 1 then p_{i} = x_{i}; otherwise p_{i} = y_{i}. It's guaranteed that 1 ≤ x_{i} ≤ w - 1 and 1 ≤ y_{i} ≤ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time. -----Output----- Output n lines, the i-th of which contains two space-separated integers (x_{i}, y_{i}) — the stopping position of the i-th dancer in the input. -----Examples----- Input 8 10 8 1 1 10 1 4 13 1 7 1 1 8 2 2 2 0 2 5 14 2 6 0 2 6 1 Output 4 8 10 5 8 8 10 6 10 2 1 8 7 8 10 6 Input 3 2 3 1 1 2 2 1 1 1 1 5 Output 1 3 2 1 1 3 -----Note----- The first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure. [Image] In the second example, no dancers collide. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the multiset of positive integers $s=\{s_1,s_2,\dots,s_k\}$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $s$ as follow: $\gcd(s)$ is the maximum positive integer $x$, such that all integers in $s$ are divisible on $x$. $\textrm{lcm}(s)$ is the minimum positive integer $x$, that divisible on all integers from $s$. For example, $\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$ and $\textrm{lcm}(\{4,6\})=12$. Note that for any positive integer $x$, $\gcd(\{x\})=\textrm{lcm}(\{x\})=x$. Orac has a sequence $a$ with length $n$. He come up with the multiset $t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}$, and asked you to find the value of $\gcd(t)$ for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence. -----Input----- The first line contains one integer $n\ (2\le n\le 100\,000)$. The second line contains $n$ integers, $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 200\,000$). -----Output----- Print one integer: $\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\})$. -----Examples----- Input 2 1 1 Output 1 Input 4 10 24 40 80 Output 40 Input 10 540 648 810 648 720 540 594 864 972 648 Output 54 -----Note----- For the first example, $t=\{\textrm{lcm}(\{1,1\})\}=\{1\}$, so $\gcd(t)=1$. For the second example, $t=\{120,40,80,120,240,80\}$, and it's not hard to see that $\gcd(t)=40$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state). You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A). You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007. -----Input----- The first line of input will contain two integers n, m (3 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000). The next m lines will contain the description of the known relationships. The i-th line will contain three integers a_{i}, b_{i}, c_{i}. If c_{i} is 1, then a_{i} and b_{i} are in love, otherwise, they hate each other (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}, $c_{i} \in \{0,1 \}$). Each pair of people will be described no more than once. -----Output----- Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007. -----Examples----- Input 3 0 Output 4 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 0 Output 1 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 1 Output 0 -----Note----- In the first sample, the four ways are to: Make everyone love each other Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk). Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost. -----Input----- The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a_1, a_2, ..., a_{n}, where a_{i} is 0 if the cow number i is facing left, and 1 if it is facing right. -----Output----- Print a single integer, the minimum amount of lost milk. Please, do not write 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 4 0 0 1 0 Output 1 Input 5 1 0 1 0 1 Output 3 -----Note----- In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Alice 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 5\,000$; $1 \leq m \leq 20\,000$) — 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. Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen. -----Input----- The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain c_{i}, the number of balls of the i-th color (1 ≤ c_{i} ≤ 1000). The total number of balls doesn't exceed 1000. -----Output----- A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007. -----Examples----- Input 3 2 2 1 Output 3 Input 4 1 2 3 4 Output 1680 -----Note----- In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are: 1 2 1 2 3 1 1 2 2 3 2 1 1 2 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are $n$ startups. Startups can be active or acquired. If a startup is acquired, then that means it has exactly one active startup that it is following. An active startup can have arbitrarily many acquired startups that are following it. An active startup cannot follow any other startup. The following steps happen until there is exactly one active startup. The following sequence of steps takes exactly 1 day. Two distinct active startups $A$, $B$, are chosen uniformly at random. A fair coin is flipped, and with equal probability, $A$ acquires $B$ or $B$ acquires $A$ (i.e. if $A$ acquires $B$, then that means $B$'s state changes from active to acquired, and its starts following $A$). When a startup changes from active to acquired, all of its previously acquired startups become active. For example, the following scenario can happen: Let's say $A$, $B$ are active startups. $C$, $D$, $E$ are acquired startups under $A$, and $F$, $G$ are acquired startups under $B$: [Image] Active startups are shown in red. If $A$ acquires $B$, then the state will be $A$, $F$, $G$ are active startups. $C$, $D$, $E$, $B$ are acquired startups under $A$. $F$ and $G$ have no acquired startups: $G$ If instead, $B$ acquires $A$, then the state will be $B$, $C$, $D$, $E$ are active startups. $F$, $G$, $A$ are acquired startups under $B$. $C$, $D$, $E$ have no acquired startups: [Image] You are given the initial state of the startups. For each startup, you are told if it is either acquired or active. If it is acquired, you are also given the index of the active startup that it is following. You're now wondering, what is the expected number of days needed for this process to finish with exactly one active startup at the end. It can be shown the expected number of days can be written as a rational number $P/Q$, where $P$ and $Q$ are co-prime integers, and $Q \not= 0 \pmod{10^9+7}$. Return the value of $P \cdot Q^{-1}$ modulo $10^9+7$. -----Input----- The first line contains a single integer $n$ ($2 \leq n \leq 500$), the number of startups. The next line will contain $n$ space-separated integers $a_1, a_2, \ldots, a_n$ ($a_i = -1$ or $1 \leq a_i \leq n$). If $a_i = -1$, then that means startup $i$ is active. Otherwise, if $1 \leq a_i \leq n$, then startup $i$ is acquired, and it is currently following startup $a_i$. It is guaranteed if $a_i \not= -1$, then $a_{a_i} =-1$ (that is, all startups that are being followed are active). -----Output----- Print a single integer, the expected number of days needed for the process to end with exactly one active startup, modulo $10^9+7$. -----Examples----- Input 3 -1 -1 -1 Output 3 Input 2 2 -1 Output 0 Input 40 3 3 -1 -1 4 4 -1 -1 -1 -1 -1 10 10 10 10 10 10 4 20 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 3 3 3 3 3 3 3 3 Output 755808950 -----Note----- In the first sample, there are three active startups labeled $1$, $2$ and $3$, and zero acquired startups. Here's an example of how one scenario can happen Startup $1$ acquires startup $2$ (This state can be represented by the array $[-1, 1, -1]$) Startup $3$ acquires startup $1$ (This state can be represented by the array $[3, -1, -1]$) Startup $2$ acquires startup $3$ (This state can be represented by the array $[-1, -1, 2]$). Startup $2$ acquires startup $1$ (This state can be represented by the array $[2, -1, 2]$). At this point, there is only one active startup, and this sequence of steps took $4$ days. It can be shown the expected number of days is $3$. For the second sample, there is only one active startup, so we need zero days. For the last sample, remember to take the answer modulo $10^9+7$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of $n$ nodes and $n-1$ edges. The nodes are numbered from $1$ to $n$. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in $n$ distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of $n$ elements. A permutation of $n$ elements is a sequence of integers $p_1,p_2,\ldots,p_n$ in which every integer from $1$ to $n$ appears exactly once. After a permutation is chosen Nauuo draws the $i$-th node in the $p_i$-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo $998244353$, can you help her? It is obvious that whether a permutation is valid or not does not depend on which $n$ points on the circle are chosen. -----Input----- The first line contains a single integer $n$ ($2\le n\le 2\cdot 10^5$) — the number of nodes in the tree. Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1\le u,v\le n$), denoting there is an edge between $u$ and $v$. It is guaranteed that the given edges form a tree. -----Output----- The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo $998244353$. -----Examples----- Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 -----Note----- Example 1 All valid permutations and their spanning trees are as follows. [Image] Here is an example of invalid permutation: the edges $(1,3)$ and $(2,4)$ are crossed. [Image] Example 2 Every permutation leads to a valid tree, so the answer is $4! = 24$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Mitya has a rooted tree with $n$ vertices indexed from $1$ to $n$, where the root has index $1$. Each vertex $v$ initially had an integer number $a_v \ge 0$ written on it. For every vertex $v$ Mitya has computed $s_v$: the sum of all values written on the vertices on the path from vertex $v$ to the root, as well as $h_v$ — the depth of vertex $v$, which denotes the number of vertices on the path from vertex $v$ to the root. Clearly, $s_1=a_1$ and $h_1=1$. Then Mitya erased all numbers $a_v$, and by accident he also erased all values $s_v$ for vertices with even depth (vertices with even $h_v$). Your task is to restore the values $a_v$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $a_v$ for all vertices in the tree. -----Input----- The first line contains one integer $n$ — the number of vertices in the tree ($2 \le n \le 10^5$). The following line contains integers $p_2$, $p_3$, ... $p_n$, where $p_i$ stands for the parent of vertex with index $i$ in the tree ($1 \le p_i < i$). The last line contains integer values $s_1$, $s_2$, ..., $s_n$ ($-1 \le s_v \le 10^9$), where erased values are replaced by $-1$. -----Output----- Output one integer — the minimum total sum of all values $a_v$ in the original tree, or $-1$ if such tree does not exist. -----Examples----- Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side. One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections. Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares. To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path. One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east. Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it. Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths. -----Input----- The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths. The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW". The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path. -----Output----- Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive. -----Examples----- Input 7 NNESWW SWSWSW Output YES Input 3 NN SS Output NO -----Note----- In the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW. In the second sample, no sequence of moves can get both marbles to the end. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an array $a$ of length $2n$. Consider a partition of array $a$ into two subsequences $p$ and $q$ of length $n$ each (each element of array $a$ should be in exactly one subsequence: either in $p$ or in $q$). Let's sort $p$ in non-decreasing order, and $q$ in non-increasing order, we can denote the sorted versions by $x$ and $y$, respectively. Then the cost of a partition is defined as $f(p, q) = \sum_{i = 1}^n |x_i - y_i|$. Find the sum of $f(p, q)$ over all correct partitions of array $a$. Since the answer might be too big, print its remainder modulo $998244353$. -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 150\,000$). The second line contains $2n$ integers $a_1, a_2, \ldots, a_{2n}$ ($1 \leq a_i \leq 10^9$) — elements of array $a$. -----Output----- Print one integer — the answer to the problem, modulo $998244353$. -----Examples----- Input 1 1 4 Output 6 Input 2 2 1 2 1 Output 12 Input 3 2 2 2 2 2 2 Output 0 Input 5 13 8 35 94 9284 34 54 69 123 846 Output 2588544 -----Note----- Two partitions of an array are considered different if the sets of indices of elements included in the subsequence $p$ are different. In the first example, there are two correct partitions of the array $a$: $p = [1]$, $q = [4]$, then $x = [1]$, $y = [4]$, $f(p, q) = |1 - 4| = 3$; $p = [4]$, $q = [1]$, then $x = [4]$, $y = [1]$, $f(p, q) = |4 - 1| = 3$. In the second example, there are six valid partitions of the array $a$: $p = [2, 1]$, $q = [2, 1]$ (elements with indices $1$ and $2$ in the original array are selected in the subsequence $p$); $p = [2, 2]$, $q = [1, 1]$; $p = [2, 1]$, $q = [1, 2]$ (elements with indices $1$ and $4$ are selected in the subsequence $p$); $p = [1, 2]$, $q = [2, 1]$; $p = [1, 1]$, $q = [2, 2]$; $p = [2, 1]$, $q = [2, 1]$ (elements with indices $3$ and $4$ are selected in the subsequence $p$). Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. While discussing a proper problem A for a Codeforces Round, Kostya created a cyclic array of positive integers $a_1, a_2, \ldots, a_n$. Since the talk was long and not promising, Kostya created a new cyclic array $b_1, b_2, \ldots, b_{n}$ so that $b_i = (a_i \mod a_{i + 1})$, where we take $a_{n+1} = a_1$. Here $mod$ is the modulo operation. When the talk became interesting, Kostya completely forgot how array $a$ had looked like. Suddenly, he thought that restoring array $a$ from array $b$ would be an interesting problem (unfortunately, not A). -----Input----- The first line contains a single integer $n$ ($2 \le n \le 140582$) — the length of the array $a$. The second line contains $n$ integers $b_1, b_2, \ldots, b_{n}$ ($0 \le b_i \le 187126$). -----Output----- If it is possible to restore some array $a$ of length $n$ so that $b_i = a_i \mod a_{(i \mod n) + 1}$ holds for all $i = 1, 2, \ldots, n$, print «YES» in the first line and the integers $a_1, a_2, \ldots, a_n$ in the second line. All $a_i$ should satisfy $1 \le a_i \le 10^{18}$. We can show that if an answer exists, then an answer with such constraint exists as well. It it impossible to restore any valid $a$, print «NO» in one line. You can print each letter in any case (upper or lower). -----Examples----- Input 4 1 3 1 0 Output YES 1 3 5 2 Input 2 4 4 Output NO -----Note----- In the first example: $1 \mod 3 = 1$ $3 \mod 5 = 3$ $5 \mod 2 = 1$ $2 \mod 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. Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from $1$ to $n$. Each of its vertices also has an integer $a_i$ written on it. For each vertex $i$, Evlampiy calculated $c_i$ — the number of vertices $j$ in the subtree of vertex $i$, such that $a_j < a_i$. [Image]Illustration for the second example, the first integer is $a_i$ and the integer in parentheses is $c_i$ After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of $c_i$, but he completely forgot which integers $a_i$ were written on the vertices. Help him to restore initial integers! -----Input----- The first line contains an integer $n$ $(1 \leq n \leq 2000)$ — the number of vertices in the tree. The next $n$ lines contain descriptions of vertices: the $i$-th line contains two integers $p_i$ and $c_i$ ($0 \leq p_i \leq n$; $0 \leq c_i \leq n-1$), where $p_i$ is the parent of vertex $i$ or $0$ if vertex $i$ is root, and $c_i$ is the number of vertices $j$ in the subtree of vertex $i$, such that $a_j < a_i$. It is guaranteed that the values of $p_i$ describe a rooted tree with $n$ vertices. -----Output----- If a solution exists, in the first line print "YES", and in the second line output $n$ integers $a_i$ $(1 \leq a_i \leq {10}^{9})$. If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all $a_i$ are between $1$ and $10^9$. If there are no solutions, print "NO". -----Examples----- Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 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. Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation. For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers a_1, a_2, ..., a_{n}. He also wrote a square matrix b of size n × n. The element of matrix b that sits in the i-th row in the j-th column (we'll denote it as b_{ij}) equals: the "bitwise AND" of numbers a_{i} and a_{j} (that is, b_{ij} = a_{i} & a_{j}), if i ≠ j; -1, if i = j. Having written out matrix b, Polycarpus got very happy and wiped a off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly. Help Polycarpus, given matrix b, restore the sequence of numbers a_1, a_2, ..., a_{n}, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed 10^9. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 100) — the size of square matrix b. Next n lines contain matrix b. The i-th of these lines contains n space-separated integers: the j-th number represents the element of matrix b_{ij}. It is guaranteed, that for all i (1 ≤ i ≤ n) the following condition fulfills: b_{ii} = -1. It is guaranteed that for all i, j (1 ≤ i, j ≤ n; i ≠ j) the following condition fulfills: 0 ≤ b_{ij} ≤ 10^9, b_{ij} = b_{ji}. -----Output----- Print n non-negative integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — the sequence that Polycarpus wiped off the board. Separate the numbers by whitespaces. It is guaranteed that there is sequence a that satisfies the problem conditions. If there are multiple such sequences, you are allowed to print any of them. -----Examples----- Input 1 -1 Output 0 Input 3 -1 18 0 18 -1 0 0 0 -1 Output 18 18 0 Input 4 -1 128 128 128 128 -1 148 160 128 148 -1 128 128 160 128 -1 Output 128 180 148 160 -----Note----- If you do not know what is the "bitwise AND" operation please read: http://en.wikipedia.org/wiki/Bitwise_operation. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allowed. Help Arkady to find two fountains with maximum total beauty so that he can buy both at the same time. -----Input----- The first line contains three integers n, c and d (2 ≤ n ≤ 100 000, 0 ≤ c, d ≤ 100 000) — the number of fountains, the number of coins and diamonds Arkady has. The next n lines describe fountains. Each of these lines contain two integers b_{i} and p_{i} (1 ≤ b_{i}, p_{i} ≤ 100 000) — the beauty and the cost of the i-th fountain, and then a letter "C" or "D", describing in which type of money is the cost of fountain i: in coins or in diamonds, respectively. -----Output----- Print the maximum total beauty of exactly two fountains Arkady can build. If he can't build two fountains, print 0. -----Examples----- Input 3 7 6 10 8 C 4 3 C 5 6 D Output 9 Input 2 4 5 2 5 C 2 1 D Output 0 Input 3 10 10 5 5 C 5 5 C 10 11 D Output 10 -----Note----- In the first example Arkady should build the second fountain with beauty 4, which costs 3 coins. The first fountain he can't build because he don't have enough coins. Also Arkady should build the third fountain with beauty 5 which costs 6 diamonds. Thus the total beauty of built fountains is 9. In the second example there are two fountains, but Arkady can't build both of them, because he needs 5 coins for the first fountain, and Arkady has only 4 coins. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers. There are $k$ boxes numbered from $1$ to $k$. The $i$-th box contains $n_i$ integer numbers. The integers can be negative. All of the integers are distinct. Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, $k$ integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box. Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be? -----Input----- The first line contains a single integer $k$ ($1 \leq k \leq 15$), the number of boxes. The $i$-th of the next $k$ lines first contains a single integer $n_i$ ($1 \leq n_i \leq 5\,000$), the number of integers in box $i$. Then the same line contains $n_i$ integers $a_{i,1}, \ldots, a_{i,n_i}$ ($|a_{i,j}| \leq 10^9$), the integers in the $i$-th box. It is guaranteed that all $a_{i,j}$ are distinct. -----Output----- If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output $k$ lines. The $i$-th of these lines should contain two integers $c_i$ and $p_i$. This means that Ujan should pick the integer $c_i$ from the $i$-th box and place it in the $p_i$-th box afterwards. If there are multiple solutions, output any of those. You can print each letter in any case (upper or lower). -----Examples----- Input 4 3 1 7 4 2 3 2 2 8 5 1 10 Output Yes 7 2 2 3 5 1 10 4 Input 2 2 3 -2 2 -1 5 Output No Input 2 2 -10 10 2 0 -20 Output Yes -10 2 -20 1 -----Note----- In the first sample, Ujan can put the number $7$ in the $2$nd box, the number $2$ in the $3$rd box, the number $5$ in the $1$st box and keep the number $10$ in the same $4$th box. Then the boxes will contain numbers $\{1,5,4\}$, $\{3, 7\}$, $\{8,2\}$ and $\{10\}$. The sum in each box then is equal to $10$. In the second sample, it is not possible to pick and redistribute the numbers in the required way. In the third sample, one can swap the numbers $-20$ and $-10$, making the sum in each box equal to $-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. Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract k ≥ 1 non-overlapping substrings from it such that each of them contains string t as a substring? More formally, you need to calculate the number of ways to choose two sequences a_1, a_2, ..., a_{k} and b_1, b_2, ..., b_{k} satisfying the following requirements: k ≥ 1 $\forall i(1 \leq i \leq k) 1 \leq a_{i}, b_{i} \leq|s|$ $\forall i(1 \leq i \leq k) b_{i} \geq a_{i}$ $\forall i(2 \leq i \leq k) a_{i} > b_{i - 1}$ $\forall i(1 \leq i \leq k)$  t is a substring of string s_{a}_{i}s_{a}_{i} + 1... s_{b}_{i} (string s is considered as 1-indexed). As the number of ways can be rather large print it modulo 10^9 + 7. -----Input----- Input consists of two lines containing strings s and t (1 ≤ |s|, |t| ≤ 10^5). Each string consists of lowercase Latin letters. -----Output----- Print the answer in a single line. -----Examples----- Input ababa aba Output 5 Input welcometoroundtwohundredandeightytwo d Output 274201 Input ddd d Output 12 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for $n$ days. On the $i$-th day: If Du can speak, he'll make fun of Boboniu with fun factor $a_i$. But after that, he may be muzzled depending on Boboniu's mood. Otherwise, Du won't do anything. Boboniu's mood is a constant $m$. On the $i$-th day: If Du can speak and $a_i>m$, then Boboniu will be angry and muzzle him for $d$ days, which means that Du won't be able to speak on the $i+1, i+2, \cdots, \min(i+d,n)$-th days. Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of $a$. -----Input----- The first line contains three integers $n$, $d$ and $m$ ($1\le d\le n\le 10^5,0\le m\le 10^9$). The next line contains $n$ integers $a_1, a_2, \ldots,a_n$ ($0\le a_i\le 10^9$). -----Output----- Print one integer: the maximum total fun factor among all permutations of $a$. -----Examples----- Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 -----Note----- In the first example, you can set $a'=[15, 5, 8, 10, 23]$. Then Du's chatting record will be: Make fun of Boboniu with fun factor $15$. Be muzzled. Be muzzled. Make fun of Boboniu with fun factor $10$. Make fun of Boboniu with fun factor $23$. Thus the total fun factor is $48$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Ziota found a video game called "Monster Invaders". Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns. For the sake of simplicity, we only consider two different types of monsters and three different types of guns. Namely, the two types of monsters are: a normal monster with $1$ hp. a boss with $2$ hp. And the three types of guns are: Pistol, deals $1$ hp in damage to one monster, $r_1$ reloading time Laser gun, deals $1$ hp in damage to all the monsters in the current level (including the boss), $r_2$ reloading time AWP, instantly kills any monster, $r_3$ reloading time The guns are initially not loaded, and the Ziota can only reload 1 gun at a time. The levels of the game can be considered as an array $a_1, a_2, \ldots, a_n$, in which the $i$-th stage has $a_i$ normal monsters and 1 boss. Due to the nature of the game, Ziota cannot use the Pistol (the first type of gun) or AWP (the third type of gun) to shoot the boss before killing all of the $a_i$ normal monsters. If Ziota damages the boss but does not kill it immediately, he is forced to move out of the current level to an arbitrary adjacent level (adjacent levels of level $i$ $(1 < i < n)$ are levels $i - 1$ and $i + 1$, the only adjacent level of level $1$ is level $2$, the only adjacent level of level $n$ is level $n - 1$). Ziota can also choose to move to an adjacent level at any time. Each move between adjacent levels are managed by portals with $d$ teleportation time. In order not to disrupt the space-time continuum within the game, it is strictly forbidden to reload or shoot monsters during teleportation. Ziota starts the game at level 1. The objective of the game is rather simple, to kill all the bosses in all the levels. He is curious about the minimum time to finish the game (assuming it takes no time to shoot the monsters with a loaded gun and Ziota has infinite ammo on all the three guns). Please help him find this value. -----Input----- The first line of the input contains five integers separated by single spaces: $n$ $(2 \le n \le 10^6)$ — the number of stages, $r_1, r_2, r_3$ $(1 \le r_1 \le r_2 \le r_3 \le 10^9)$ — the reload time of the three guns respectively, $d$ $(1 \le d \le 10^9)$ — the time of moving between adjacent levels. The second line of the input contains $n$ integers separated by single spaces $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^6, 1 \le i \le n)$. -----Output----- Print one integer, the minimum time to finish the game. -----Examples----- Input 4 1 3 4 3 3 2 5 1 Output 34 Input 4 2 4 4 1 4 5 1 2 Output 31 -----Note----- In the first test case, the optimal strategy is: Use the pistol to kill three normal monsters and AWP to kill the boss (Total time $1\cdot3+4=7$) Move to stage two (Total time $7+3=10$) Use the pistol twice and AWP to kill the boss (Total time $10+1\cdot2+4=16$) Move to stage three (Total time $16+3=19$) Use the laser gun and forced to move to either stage four or two, here we move to stage four (Total time $19+3+3=25$) Use the pistol once, use AWP to kill the boss (Total time $25+1\cdot1+4=30$) Move back to stage three (Total time $30+3=33$) Kill the boss at stage three with the pistol (Total time $33+1=34$) Note that here, we do not finish at level $n$, but when all the bosses are killed. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 several queries. Each query consists of three integers $p$, $q$ and $b$. You need to answer whether the result of $p/q$ in notation with base $b$ is a finite fraction. A fraction in notation with base $b$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of queries. Next $n$ lines contain queries, one per line. Each line contains three integers $p$, $q$, and $b$ ($0 \le p \le 10^{18}$, $1 \le q \le 10^{18}$, $2 \le b \le 10^{18}$). All numbers are given in notation with base $10$. -----Output----- For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise. -----Examples----- Input 2 6 12 10 4 3 10 Output Finite Infinite Input 4 1 1 2 9 36 2 4 12 3 3 5 4 Output Finite Finite Finite Infinite -----Note----- $\frac{6}{12} = \frac{1}{2} = 0,5_{10}$ $\frac{4}{3} = 1,(3)_{10}$ $\frac{9}{36} = \frac{1}{4} = 0,01_2$ $\frac{4}{12} = \frac{1}{3} = 0,1_3$ Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a set of size $m$ with integer elements between $0$ and $2^{n}-1$ inclusive. Let's build an undirected graph on these integers in the following way: connect two integers $x$ and $y$ with an edge if and only if $x \& y = 0$. Here $\&$ is the bitwise AND operation. Count the number of connected components in that graph. -----Input----- In the first line of input there are two integers $n$ and $m$ ($0 \le n \le 22$, $1 \le m \le 2^{n}$). In the second line there are $m$ integers $a_1, a_2, \ldots, a_m$ ($0 \le a_{i} < 2^{n}$) — the elements of the set. All $a_{i}$ are distinct. -----Output----- Print the number of connected components. -----Examples----- Input 2 3 1 2 3 Output 2 Input 5 5 5 19 10 20 12 Output 2 -----Note----- Graph from first sample: $0$ Graph from second sample: [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. In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $s$ starting from the $l$-th character and ending with the $r$-th character as $s[l \dots r]$. The characters of each string are numbered from $1$. We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011. Binary string $a$ is considered reachable from binary string $b$ if there exists a sequence $s_1$, $s_2$, ..., $s_k$ such that $s_1 = a$, $s_k = b$, and for every $i \in [1, k - 1]$, $s_i$ can be transformed into $s_{i + 1}$ using exactly one operation. Note that $k$ can be equal to $1$, i. e., every string is reachable from itself. You are given a string $t$ and $q$ queries to it. Each query consists of three integers $l_1$, $l_2$ and $len$. To answer each query, you have to determine whether $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$. -----Input----- The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of string $t$. The second line contains one string $t$ ($|t| = n$). Each character of $t$ is either 0 or 1. The third line contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries. Then $q$ lines follow, each line represents a query. The $i$-th line contains three integers $l_1$, $l_2$ and $len$ ($1 \le l_1, l_2 \le |t|$, $1 \le len \le |t| - \max(l_1, l_2) + 1$) for the $i$-th query. -----Output----- For each query, print either YES if $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$, or NO otherwise. You may print each letter in any register. -----Example----- Input 5 11011 3 1 3 3 1 4 2 1 2 3 Output Yes Yes No Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an array $a$ of $n$ integers and an integer $s$. It is guaranteed that $n$ is odd. In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $s$. The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array $6, 5, 8$ is equal to $6$, since if we sort this array we will get $5, 6, 8$, and $6$ is located on the middle position. -----Input----- The first line contains two integers $n$ and $s$ ($1\le n\le 2\cdot 10^5-1$, $1\le s\le 10^9$) — the length of the array and the required value of median. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1\le a_i \le 10^9$) — the elements of the array $a$. It is guaranteed that $n$ is odd. -----Output----- In a single line output the minimum number of operations to make the median being equal to $s$. -----Examples----- Input 3 8 6 5 8 Output 2 Input 7 20 21 15 12 11 20 19 12 Output 6 -----Note----- In the first sample, $6$ can be increased twice. The array will transform to $8, 5, 8$, which becomes $5, 8, 8$ after sorting, hence the median is equal to $8$. In the second sample, $19$ can be increased once and $15$ can be increased five times. The array will become equal to $21, 20, 12, 11, 20, 20, 12$. If we sort this array we get $11, 12, 12, 20, 20, 20, 21$, this way the median is $20$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. In order to fly to the Moon Mister B just needs to solve the following problem. There is a complete indirected graph with n vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles. We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you? -----Input----- The only line contains single integer n (3 ≤ n ≤ 300). -----Output----- If there is no answer, print -1. Otherwise, in the first line print k (1 ≤ k ≤ n^2) — the number of cycles in your solution. In each of the next k lines print description of one cycle in the following format: first print integer m (3 ≤ m ≤ 4) — the length of the cycle, then print m integers v_1, v_2, ..., v_{m} (1 ≤ v_{i} ≤ n) — the vertices in the cycle in the traverse order. Each edge should be in exactly two cycles. -----Examples----- Input 3 Output 2 3 1 2 3 3 1 2 3 Input 5 Output 6 3 5 4 2 3 3 1 5 4 4 5 2 3 4 4 3 2 1 3 4 2 1 3 3 1 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. Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least $\frac{p_{i} - \epsilon}{2000}$, where ε < 10^{ - 7}. To better prepare himself, he wants to know the answer for q different values of p_{i}. Since he is busy designing the battle strategy with Sam, he asks you for your help. -----Input----- First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer p_{i} (1 ≤ p_{i} ≤ 1000) — i-th query. -----Output----- Output q lines. On i-th of them output single integer — answer for i-th query. -----Examples----- Input 1 1 1 Output 1 Input 2 2 1 2 Output 2 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column. Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j]. There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout. If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs. -----Input----- The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 ≤ a[i][j] ≤ 10^5). -----Output----- The output contains a single number — the maximum total gain possible. -----Examples----- Input 3 3 100 100 100 100 1 100 100 100 100 Output 800 -----Note----- Iahub will choose exercises a[1][1] → a[1][2] → a[2][2] → a[3][2] → a[3][3]. Iahubina will choose exercises a[3][1] → a[2][1] → a[2][2] → a[2][3] → a[1][3]. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length [Image] The picture corresponds to the first example -----Input----- The first line contains single integer n (1 ≤ n ≤ 5·10^5) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x_1, y_1, x_2 and y_2 ( - 10^9 ≤ x_1 < x_2 ≤ 10^9, - 10^9 ≤ y_1 < y_2 ≤ 10^9), that means that points (x_1, y_1) and (x_2, y_2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. -----Output----- Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer c_{i} (1 ≤ c_{i} ≤ 4) — the color of i-th rectangle. -----Example----- Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a set Y of n distinct positive integers y_1, y_2, ..., y_{n}. Set X of n distinct positive integers x_1, x_2, ..., x_{n} is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: Take any integer x_{i} and multiply it by two, i.e. replace x_{i} with 2·x_{i}. Take any integer x_{i}, multiply it by two and add one, i.e. replace x_{i} with 2·x_{i} + 1. Note that integers in X are not required to be distinct after each operation. Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal. Note, that any set of integers (or its permutation) generates itself. You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y_1, ..., y_{n} (1 ≤ y_{i} ≤ 10^9), that are guaranteed to be distinct. -----Output----- Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. -----Examples----- Input 5 1 2 3 4 5 Output 4 5 2 3 1 Input 6 15 14 3 13 1 12 Output 12 13 14 7 3 1 Input 6 9 7 13 17 5 11 Output 4 5 2 6 3 1 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Consider a sequence [a_1, a_2, ... , a_{n}]. Define its prefix product sequence $[ a_{1} \operatorname{mod} n,(a_{1} a_{2}) \operatorname{mod} n, \cdots,(a_{1} a_{2} \cdots a_{n}) \operatorname{mod} n ]$. Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1]. -----Input----- The only input line contains an integer n (1 ≤ n ≤ 10^5). -----Output----- In the first output line, print "YES" if such sequence exists, or print "NO" if no such sequence exists. If any solution exists, you should output n more lines. i-th line contains only an integer a_{i}. The elements of the sequence should be different positive integers no larger than n. If there are multiple solutions, you are allowed to print any of them. -----Examples----- Input 7 Output YES 1 4 3 6 5 2 7 Input 6 Output NO -----Note----- For the second sample, there are no valid sequences. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 took $n$ videos, the duration of the $i$-th video is $a_i$ seconds. The videos are listed in the chronological order, i.e. the $1$-st video is the earliest, the $2$-nd video is the next, ..., the $n$-th video is the last. Now Polycarp wants to publish exactly $k$ ($1 \le k \le n$) posts in Instabram. Each video should be a part of a single post. The posts should preserve the chronological order, it means that the first post should contain one or more of the earliest videos, the second post should contain a block (one or more videos) going next and so on. In other words, if the number of videos in the $j$-th post is $s_j$ then: $s_1+s_2+\dots+s_k=n$ ($s_i>0$), the first post contains the videos: $1, 2, \dots, s_1$; the second post contains the videos: $s_1+1, s_1+2, \dots, s_1+s_2$; the third post contains the videos: $s_1+s_2+1, s_1+s_2+2, \dots, s_1+s_2+s_3$; ... the $k$-th post contains videos: $n-s_k+1,n-s_k+2,\dots,n$. Polycarp is a perfectionist, he wants the total duration of videos in each post to be the same. Help Polycarp to find such positive integer values $s_1, s_2, \dots, s_k$ that satisfy all the conditions above. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 10^5$). The next line contains $n$ positive integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^4$), where $a_i$ is the duration of the $i$-th video. -----Output----- If solution exists, print "Yes" in the first line. Print $k$ positive integers $s_1, s_2, \dots, s_k$ ($s_1+s_2+\dots+s_k=n$) in the second line. The total duration of videos in each post should be the same. It can be easily proven that the answer is unique (if it exists). If there is no solution, print a single line "No". -----Examples----- Input 6 3 3 3 1 4 1 6 Output Yes 2 3 1 Input 3 3 1 1 1 Output Yes 1 1 1 Input 3 3 1 1 2 Output No Input 3 1 1 10 100 Output Yes 3 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight w_{i} and some beauty b_{i}. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a_1, a_2, ..., a_{k} such that a_{i} and a_{i} + 1 are friends for each 1 ≤ i < k, and a_1 = x and a_{k} = y. [Image] Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. -----Input----- The first line contains integers n, m and w (1 ≤ n ≤ 1000, $0 \leq m \leq \operatorname{min}(\frac{n \cdot(n - 1)}{2}, 10^{5})$, 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w_1, w_2, ..., w_{n} (1 ≤ w_{i} ≤ 1000) — the weights of the Hoses. The third line contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^6) — the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ n, x_{i} ≠ y_{i}), meaning that Hoses x_{i} and y_{i} are friends. Note that friendship is bidirectional. All pairs (x_{i}, y_{i}) are distinct. -----Output----- Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. -----Examples----- Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 -----Note----- In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Consider a tree $T$ (that is, a connected graph without cycles) with $n$ vertices labelled $1$ through $n$. We start the following process with $T$: while $T$ has more than one vertex, do the following: choose a random edge of $T$ equiprobably; shrink the chosen edge: if the edge was connecting vertices $v$ and $u$, erase both $v$ and $u$ and create a new vertex adjacent to all vertices previously adjacent to either $v$ or $u$. The new vertex is labelled either $v$ or $u$ equiprobably. At the end of the process, $T$ consists of a single vertex labelled with one of the numbers $1, \ldots, n$. For each of the numbers, what is the probability of this number becoming the label of the final vertex? -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 50$). The following $n - 1$ lines describe the tree edges. Each of these lines contains two integers $u_i, v_i$ — labels of vertices connected by the respective edge ($1 \leq u_i, v_i \leq n$, $u_i \neq v_i$). It is guaranteed that the given graph is a tree. -----Output----- Print $n$ floating numbers — the desired probabilities for labels $1, \ldots, n$ respectively. All numbers should be correct up to $10^{-6}$ relative or absolute precision. -----Examples----- Input 4 1 2 1 3 1 4 Output 0.1250000000 0.2916666667 0.2916666667 0.2916666667 Input 7 1 2 1 3 2 4 2 5 3 6 3 7 Output 0.0850694444 0.0664062500 0.0664062500 0.1955295139 0.1955295139 0.1955295139 0.1955295139 -----Note----- In the first sample, the resulting vertex has label 1 if and only if for all three edges the label 1 survives, hence the probability is $1/2^3 = 1/8$. All other labels have equal probability due to symmetry, hence each of them has probability $(1 - 1/8) / 3 = 7/24$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Koa the Koala has a binary string $s$ of length $n$. Koa can perform no more than $n-1$ (possibly zero) operations of the following form: In one operation Koa selects positions $i$ and $i+1$ for some $i$ with $1 \le i < |s|$ and sets $s_i$ to $max(s_i, s_{i+1})$. Then Koa deletes position $i+1$ from $s$ (after the removal, the remaining parts are concatenated). Note that after every operation the length of $s$ decreases by $1$. How many different binary strings can Koa obtain by doing no more than $n-1$ (possibly zero) operations modulo $10^9+7$ ($1000000007$)? -----Input----- The only line of input contains binary string $s$ ($1 \le |s| \le 10^6$). For all $i$ ($1 \le i \le |s|$) $s_i = 0$ or $s_i = 1$. -----Output----- On a single line print the answer to the problem modulo $10^9+7$ ($1000000007$). -----Examples----- Input 000 Output 3 Input 0101 Output 6 Input 0001111 Output 16 Input 00101100011100 Output 477 -----Note----- In the first sample Koa can obtain binary strings: $0$, $00$ and $000$. In the second sample Koa can obtain binary strings: $1$, $01$, $11$, $011$, $101$ and $0101$. For example: to obtain $01$ from $0101$ Koa can operate as follows: $0101 \rightarrow 0(10)1 \rightarrow 011 \rightarrow 0(11) \rightarrow 01$. to obtain $11$ from $0101$ Koa can operate as follows: $0101 \rightarrow (01)01 \rightarrow 101 \rightarrow 1(01) \rightarrow 11$. Parentheses denote the two positions Koa selected in each operation. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is $\{0,1,…,M-1\}$, for some positive integer $M$. Ajs draws a number from the first bag and a number from the second bag, and then sums them modulo $M$. What are the residues modulo $M$ that Ajs cannot obtain with this action? -----Input----- The first line contains two positive integer $N$ ($1 \leq N \leq 200\,000$) and $M$ ($N+1 \leq M \leq 10^{9}$), denoting the number of the elements in the first bag and the modulus, respectively. The second line contains $N$ nonnegative integers $a_1,a_2,\ldots,a_N$ ($0 \leq a_1<a_2< \ldots< a_N<M$), the contents of the first bag. -----Output----- In the first line, output the cardinality $K$ of the set of residues modulo $M$ which Ajs cannot obtain. In the second line of the output, print $K$ space-separated integers greater or equal than zero and less than $M$, which represent the residues Ajs cannot obtain. The outputs should be sorted in increasing order of magnitude. If $K$=0, do not output the second line. -----Examples----- Input 2 5 3 4 Output 1 2 Input 4 1000000000 5 25 125 625 Output 0 Input 2 4 1 3 Output 2 0 2 -----Note----- In the first sample, the first bag and the second bag contain $\{3,4\}$ and $\{0,1,2\}$, respectively. Ajs can obtain every residue modulo $5$ except the residue $2$: $ 4+1 \equiv 0, \, 4+2 \equiv 1, \, 3+0 \equiv 3, \, 3+1 \equiv 4 $ modulo $5$. One can check that there is no choice of elements from the first and the second bag which sum to $2$ modulo $5$. In the second sample, the contents of the first bag are $\{5,25,125,625\}$, while the second bag contains all other nonnegative integers with at most $9$ decimal digits. Every residue modulo $1\,000\,000\,000$ can be obtained as a sum of an element in the first bag and an element in the second bag. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win? The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process. -----Input----- The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 10^5, 1 ≤ n ≤ 2000). Next n lines contain the description of black cells. The i-th of these lines contains numbers r_{i}, c_{i} (1 ≤ r_{i} ≤ h, 1 ≤ c_{i} ≤ w) — the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct. -----Output----- Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 10^9 + 7. -----Examples----- Input 3 4 2 2 2 2 3 Output 2 Input 100 100 3 15 16 16 15 99 88 Output 545732279 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer. In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario. [Image] Each one of them has a set of numbers between 1 and n - 1 (inclusive). Rick's set is s_1 with k_1 elements and Morty's is s_2 with k_2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins. Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game. -----Input----- The first line of input contains a single integer n (2 ≤ n ≤ 7000) — number of objects in game. The second line contains integer k_1 followed by k_1 distinct integers s_{1, 1}, s_{1, 2}, ..., s_{1, }k_1 — Rick's set. The third line contains integer k_2 followed by k_2 distinct integers s_{2, 1}, s_{2, 2}, ..., s_{2, }k_2 — Morty's set 1 ≤ k_{i} ≤ n - 1 and 1 ≤ s_{i}, 1, s_{i}, 2, ..., s_{i}, k_{i} ≤ n - 1 for 1 ≤ i ≤ 2. -----Output----- In the first line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end. Similarly, in the second line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Morty plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end. -----Examples----- Input 5 2 3 2 3 1 2 3 Output Lose Win Win Loop Loop Win Win Win Input 8 4 6 2 3 4 2 3 6 Output Win Win Win Win Win Win Win Lose Win Lose Lose Win Lose Lose Read the inputs from stdin solve the problem and write the answer to stdout (do 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 function $f : R \rightarrow R$ is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| ≤ K·|x - y| holds for all $x, y \in R$. We'll deal with a more... discrete version of this term. For an array $h [ 1 . . n ]$, we define it's Lipschitz constant $L(h)$ as follows: if n < 2, $L(h) = 0$ if n ≥ 2, $L(h) = \operatorname{max} [ \frac{|h [ j ] - h [ i ]|}{j - i} ]$ over all 1 ≤ i < j ≤ n In other words, $L = L(h)$ is the smallest non-negative integer such that |h[i] - h[j]| ≤ L·|i - j| holds for all 1 ≤ i, j ≤ n. You are given an array [Image] of size n and q queries of the form [l, r]. For each query, consider the subarray $s = a [ l . . r ]$; determine the sum of Lipschitz constants of all subarrays of $S$. -----Input----- The first line of the input contains two space-separated integers n and q (2 ≤ n ≤ 100 000 and 1 ≤ q ≤ 100) — the number of elements in array [Image] and the number of queries respectively. The second line contains n space-separated integers $a [ 1 . . n ]$ ($0 \leq a [ i ] \leq 10^{8}$). The following q lines describe queries. The i-th of those lines contains two space-separated integers l_{i} and r_{i} (1 ≤ l_{i} < r_{i} ≤ n). -----Output----- Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer — the sum of Lipschitz constants of all subarrays of [Image]. -----Examples----- Input 10 4 1 5 2 9 1 3 4 2 1 7 2 4 3 8 7 10 1 9 Output 17 82 23 210 Input 7 6 5 7 7 4 6 6 2 1 2 2 3 2 6 1 7 4 7 3 5 Output 2 0 22 59 16 8 -----Note----- In the first query of the first sample, the Lipschitz constants of subarrays of $[ 5,2,9 ]$ with length at least 2 are: $L([ 5,2 ]) = 3$ $L([ 2,9 ]) = 7$ $L([ 5,2,9 ]) = 7$ The answer to the query is their sum. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a prime number $p$, $n$ integers $a_1, a_2, \ldots, a_n$, and an integer $k$. Find the number of pairs of indexes $(i, j)$ ($1 \le i < j \le n$) for which $(a_i + a_j)(a_i^2 + a_j^2) \equiv k \bmod p$. -----Input----- The first line contains integers $n, p, k$ ($2 \le n \le 3 \cdot 10^5$, $2 \le p \le 10^9$, $0 \le k \le p-1$). $p$ is guaranteed to be prime. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le p-1$). It is guaranteed that all elements are different. -----Output----- Output a single integer — answer to the problem. -----Examples----- Input 3 3 0 0 1 2 Output 1 Input 6 7 2 1 2 3 4 5 6 Output 3 -----Note----- In the first example: $(0+1)(0^2 + 1^2) = 1 \equiv 1 \bmod 3$. $(0+2)(0^2 + 2^2) = 8 \equiv 2 \bmod 3$. $(1+2)(1^2 + 2^2) = 15 \equiv 0 \bmod 3$. So only $1$ pair satisfies the condition. In the second example, there are $3$ such pairs: $(1, 5)$, $(2, 3)$, $(4, 6)$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought $n$ carrots with lengths $a_1, a_2, a_3, \ldots, a_n$. However, rabbits are very fertile and multiply very quickly. Zookeeper now has $k$ rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into $k$ pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size $x$ is $x^2$. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. -----Input----- The first line contains two integers $n$ and $k$ $(1 \leq n \leq k \leq 10^5)$: the initial number of carrots and the number of rabbits. The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ $(1 \leq a_i \leq 10^6)$: lengths of carrots. It is guaranteed that the sum of $a_i$ is at least $k$. -----Output----- Output one integer: the minimum sum of time taken for rabbits to eat carrots. -----Examples----- Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 -----Note----- For the first test, the optimal sizes of carrots are $\{1,1,1,2,2,2\}$. The time taken is $1^2+1^2+1^2+2^2+2^2+2^2=15$ For the second test, the optimal sizes of carrots are $\{4,5,5,5\}$. The time taken is $4^2+5^2+5^2+5^2=91$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's assume that v(n) is the largest prime number, that does not exceed n; u(n) is the smallest prime number strictly greater than n. Find $\sum_{i = 2}^{n} \frac{1}{v(i) u(i)}$. -----Input----- The first line contains integer t (1 ≤ t ≤ 500) — the number of testscases. Each of the following t lines of the input contains integer n (2 ≤ n ≤ 10^9). -----Output----- Print t lines: the i-th of them must contain the answer to the i-th test as an irreducible fraction "p/q", where p, q are integers, q > 0. -----Examples----- Input 2 2 3 Output 1/6 7/30 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types: Fold the sheet of paper at position p_{i}. After this query the leftmost part of the paper with dimensions 1 × p_{i} must be above the rightmost part of the paper with dimensions 1 × ([current width of sheet] - p_{i}). Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance l_{i} from the left border of the current sheet of paper and the other at distance r_{i} from the left border of the current sheet of paper. Please look at the explanation of the first test example for better understanding of the problem. -----Input----- The first line contains two integers: n and q (1 ≤ n ≤ 10^5; 1 ≤ q ≤ 10^5) — the width of the paper and the number of queries. Each of the following q lines contains one of the described queries in the following format: "1 p_{i}" (1 ≤ p_{i} < [current width of sheet]) — the first type query. "2 l_{i} r_{i}" (0 ≤ l_{i} < r_{i} ≤ [current width of sheet]) — the second type query. -----Output----- For each query of the second type, output the answer. -----Examples----- Input 7 4 1 3 1 2 2 0 1 2 1 2 Output 4 3 Input 10 9 2 2 9 1 1 2 0 1 1 8 2 0 8 1 2 2 1 3 1 4 2 2 4 Output 7 2 10 4 5 -----Note----- The pictures below show the shapes of the paper during the queries of the first example: [Image] After the first fold operation the sheet has width equal to 4, after the second one the width of the sheet equals to 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Polycarpus has a sequence, consisting of n non-negative integers: a_1, a_2, ..., a_{n}. Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = a_{l} | a_{l} + 1 | ...  | a_{r}. Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end. Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a. Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or". -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the number of elements of sequence a. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^6) — the elements of sequence a. -----Output----- Print a single integer — the number of distinct values of function f(l, r) for the given sequence a. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. -----Examples----- Input 3 1 2 0 Output 4 Input 10 1 2 3 4 5 6 1 2 9 10 Output 11 -----Note----- In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price. At every moment of time, every SELL offer has higher price than every BUY offer. In this problem no two ever existed orders will have the same price. The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below. [Image] The presented order book says that someone wants to sell the product at price $12$ and it's the best SELL offer because the other two have higher prices. The best BUY offer has price $10$. There are two possible actions in this orderbook: Somebody adds a new order of some direction with some price. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever. It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL $20$" if there is already an offer "BUY $20$" or "BUY $25$" — in this case you just accept the best BUY offer. You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types: "ADD $p$" denotes adding a new order with price $p$ and unknown direction. The order must not contradict with orders still not removed from the order book. "ACCEPT $p$" denotes accepting an existing best offer with price $p$ and unknown direction. The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo $10^9 + 7$. If it is impossible to correctly restore directions, then output $0$. -----Input----- The first line contains an integer $n$ ($1 \le n \le 363\,304$) — the number of actions in the log. Each of the next $n$ lines contains a string "ACCEPT" or "ADD" and an integer $p$ ($1 \le p \le 308\,983\,066$), describing an action type and price. All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet. -----Output----- Output the number of ways to restore directions of ADD actions modulo $10^9 + 7$. -----Examples----- Input 6 ADD 1 ACCEPT 1 ADD 2 ACCEPT 2 ADD 3 ACCEPT 3 Output 8 Input 4 ADD 1 ADD 2 ADD 3 ACCEPT 2 Output 2 Input 7 ADD 1 ADD 2 ADD 3 ADD 4 ADD 5 ACCEPT 3 ACCEPT 5 Output 0 -----Note----- In the first example each of orders may be BUY or SELL. In the second example the order with price $1$ has to be BUY order, the order with the price $3$ has to be SELL 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. Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them. Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is. You are to determine the total number of times Vasily takes the top card from the deck. -----Input----- The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of cards in the deck. The second line contains a sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100 000), where a_{i} is the number written on the i-th from top card in the deck. -----Output----- Print the total number of times Vasily takes the top card from the deck. -----Examples----- Input 4 6 3 1 2 Output 7 Input 1 1000 Output 1 Input 7 3 3 3 3 3 3 3 Output 7 -----Note----- In the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Little Elephant loves permutations of integers from 1 to n very much. But most of all he loves sorting them. To sort a permutation, the Little Elephant repeatedly swaps some elements. As a result, he must receive a permutation 1, 2, 3, ..., n. This time the Little Elephant has permutation p_1, p_2, ..., p_{n}. Its sorting program needs to make exactly m moves, during the i-th move it swaps elements that are at that moment located at the a_{i}-th and the b_{i}-th positions. But the Little Elephant's sorting program happened to break down and now on every step it can equiprobably either do nothing or swap the required elements. Now the Little Elephant doesn't even hope that the program will sort the permutation, but he still wonders: if he runs the program and gets some permutation, how much will the result of sorting resemble the sorted one? For that help the Little Elephant find the mathematical expectation of the number of permutation inversions after all moves of the program are completed. We'll call a pair of integers i, j (1 ≤ i < j ≤ n) an inversion in permutatuon p_1, p_2, ..., p_{n}, if the following inequality holds: p_{i} > p_{j}. -----Input----- The first line contains two integers n and m (1 ≤ n, m ≤ 1000, n > 1) — the permutation size and the number of moves. The second line contains n distinct integers, not exceeding n — the initial permutation. Next m lines each contain two integers: the i-th line contains integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}) — the positions of elements that were changed during the i-th move. -----Output----- In the only line print a single real number — the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10^{ - 6}. -----Examples----- Input 2 1 1 2 1 2 Output 0.500000000 Input 4 3 1 3 2 4 1 2 2 3 1 4 Output 3.000000000 Read the inputs from stdin solve the problem and write the answer to stdout (do 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 robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes. Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe x_{i}. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg. The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather. -----Input----- The first line of input contains three space-separated integers, a, b and c (1 ≤ b < a < c ≤ 10^9), denoting the positions of Oleg, the first security guard and the second security guard, respectively. The next line of input contains a single integer n (1 ≤ n ≤ 10^5), denoting the number of banknotes. The next line of input contains n space-separated integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^9), denoting that the i-th banknote is located in the x_{i}-th safe. Note that x_{i} are not guaranteed to be distinct. -----Output----- Output a single integer: the maximum number of banknotes Oleg can take. -----Examples----- Input 5 3 7 8 4 7 5 5 3 6 2 8 Output 4 Input 6 5 7 5 1 5 7 92 3 Output 0 -----Note----- In the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes. For the second sample, Oleg can't take any banknotes without bumping into any of the security guards. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is an automatic door at the entrance of a factory. The door works in the following way: when one or several people come to the door and it is closed, the door immediately opens automatically and all people immediately come inside, when one or several people come to the door and it is open, all people immediately come inside, opened door immediately closes in d seconds after its opening, if the door is closing and one or several people are coming to the door at the same moment, then all of them will have enough time to enter and only after that the door will close. For example, if d = 3 and four people are coming at four different moments of time t_1 = 4, t_2 = 7, t_3 = 9 and t_4 = 13 then the door will open three times: at moments 4, 9 and 13. It will close at moments 7 and 12. It is known that n employees will enter at moments a, 2·a, 3·a, ..., n·a (the value a is positive integer). Also m clients will enter at moments t_1, t_2, ..., t_{m}. Write program to find the number of times the automatic door will open. Assume that the door is initially closed. -----Input----- The first line contains four integers n, m, a and d (1 ≤ n, a ≤ 10^9, 1 ≤ m ≤ 10^5, 1 ≤ d ≤ 10^18) — the number of the employees, the number of the clients, the moment of time when the first employee will come and the period of time in which the door closes. The second line contains integer sequence t_1, t_2, ..., t_{m} (1 ≤ t_{i} ≤ 10^18) — moments of time when clients will come. The values t_{i} are given in non-decreasing order. -----Output----- Print the number of times the door will open. -----Examples----- Input 1 1 3 4 7 Output 1 Input 4 3 4 2 7 9 11 Output 4 -----Note----- In the first example the only employee will come at moment 3. At this moment the door will open and will stay open until the moment 7. At the same moment of time the client will come, so at first he will enter and only after it the door will close. Thus the door will open one time. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last n minutes and in the i-th minute friends will send a_{i} requests. Polycarp plans to test Fakebook under a special kind of load. In case the information about Fakebook gets into the mass media, Polycarp hopes for a monotone increase of the load, followed by a monotone decrease of the interest to the service. Polycarp wants to test this form of load. Your task is to determine how many requests Polycarp must add so that before some moment the load on the server strictly increases and after that moment strictly decreases. Both the increasing part and the decreasing part can be empty (i. e. absent). The decrease should immediately follow the increase. In particular, the load with two equal neigbouring values is unacceptable. For example, if the load is described with one of the arrays [1, 2, 8, 4, 3], [1, 3, 5] or [10], then such load satisfies Polycarp (in each of the cases there is an increasing part, immediately followed with a decreasing part). If the load is described with one of the arrays [1, 2, 2, 1], [2, 1, 2] or [10, 10], then such load does not satisfy Polycarp. Help Polycarp to make the minimum number of additional requests, so that the resulting load satisfies Polycarp. He can make any number of additional requests at any minute from 1 to n. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 100 000) — the duration of the load testing. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is the number of requests from friends in the i-th minute of the load testing. -----Output----- Print the minimum number of additional requests from Polycarp that would make the load strictly increasing in the beginning and then strictly decreasing afterwards. -----Examples----- Input 5 1 4 3 2 5 Output 6 Input 5 1 2 2 2 1 Output 1 Input 7 10 20 40 50 70 90 30 Output 0 -----Note----- In the first example Polycarp must make two additional requests in the third minute and four additional requests in the fourth minute. So the resulting load will look like: [1, 4, 5, 6, 5]. In total, Polycarp will make 6 additional requests. In the second example it is enough to make one additional request in the third minute, so the answer is 1. In the third example the load already satisfies all conditions described in the statement, so the answer is 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. Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company. To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter. For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows : Initially, the company name is ???. Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}. Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}. Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}. In the end, the company name is oio. Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally? A string s = s_1s_2...s_{m} is called lexicographically smaller than a string t = t_1t_2...t_{m} (where s ≠ t) if s_{i} < t_{i} where i is the smallest index such that s_{i} ≠ t_{i}. (so s_{j} = t_{j} for all j < i) -----Input----- The first line of input contains a string s of length n (1 ≤ n ≤ 3·10^5). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. -----Output----- The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. -----Examples----- Input tinkoff zscoder Output fzfsirk Input xxxxxx xxxxxx Output xxxxxx Input ioi imo Output ioi -----Note----- One way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk. For the second sample, no matter how they play, the company name will always be xxxxxx. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 start with a string $s$ consisting only of the digits $1$, $2$, or $3$. The length of $s$ is denoted by $|s|$. For each $i$ from $1$ to $|s|$, the $i$-th character of $s$ is denoted by $s_i$. There is one cursor. The cursor's location $\ell$ is denoted by an integer in $\{0, \ldots, |s|\}$, with the following meaning: If $\ell = 0$, then the cursor is located before the first character of $s$. If $\ell = |s|$, then the cursor is located right after the last character of $s$. If $0 < \ell < |s|$, then the cursor is located between $s_\ell$ and $s_{\ell+1}$. We denote by $s_\text{left}$ the string to the left of the cursor and $s_\text{right}$ the string to the right of the cursor. We also have a string $c$, which we call our clipboard, which starts out as empty. There are three types of actions: The Move action. Move the cursor one step to the right. This increments $\ell$ once. The Cut action. Set $c \leftarrow s_\text{right}$, then set $s \leftarrow s_\text{left}$. The Paste action. Append the value of $c$ to the end of the string $s$. Note that this doesn't modify $c$. The cursor initially starts at $\ell = 0$. Then, we perform the following procedure: Perform the Move action once. Perform the Cut action once. Perform the Paste action $s_\ell$ times. If $\ell = x$, stop. Otherwise, return to step 1. You're given the initial string $s$ and the integer $x$. What is the length of $s$ when the procedure stops? Since this value may be very large, only find it modulo $10^9 + 7$. It is guaranteed that $\ell \le |s|$ at any time. -----Input----- The first line of input contains a single integer $t$ ($1 \le t \le 1000$) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer $x$ ($1 \le x \le 10^6$). The second line of each test case consists of the initial string $s$ ($1 \le |s| \le 500$). It is guaranteed, that $s$ consists of the characters "1", "2", "3". It is guaranteed that the sum of $x$ in a single file is at most $10^6$. It is guaranteed that in each test case before the procedure will stop it will be true that $\ell \le |s|$ at any time. -----Output----- For each test case, output a single line containing a single integer denoting the answer for that test case modulo $10^9 + 7$. -----Example----- Input 4 5 231 7 2323 6 333 24 133321333 Output 25 1438 1101 686531475 -----Note----- Let's illustrate what happens with the first test case. Initially, we have $s = $ 231. Initially, $\ell = 0$ and $c = \varepsilon$ (the empty string). The following things happen if we follow the procedure above: Step 1, Move once: we get $\ell = 1$. Step 2, Cut once: we get $s = $ 2 and $c = $ 31. Step 3, Paste $s_\ell = $ 2 times: we get $s = $ 23131. Step 4: $\ell = 1 \not= x = 5$, so we return to step 1. Step 1, Move once: we get $\ell = 2$. Step 2, Cut once: we get $s = $ 23 and $c = $ 131. Step 3, Paste $s_\ell = $ 3 times: we get $s = $ 23131131131. Step 4: $\ell = 2 \not= x = 5$, so we return to step 1. Step 1, Move once: we get $\ell = 3$. Step 2, Cut once: we get $s = $ 231 and $c = $ 31131131. Step 3, Paste $s_\ell = $ 1 time: we get $s = $ 23131131131. Step 4: $\ell = 3 \not= x = 5$, so we return to step 1. Step 1, Move once: we get $\ell = 4$. Step 2, Cut once: we get $s = $ 2313 and $c = $ 1131131. Step 3, Paste $s_\ell = $ 3 times: we get $s = $ 2313113113111311311131131. Step 4: $\ell = 4 \not= x = 5$, so we return to step 1. Step 1, Move once: we get $\ell = 5$. Step 2, Cut once: we get $s = $ 23131 and $c = $ 13113111311311131131. Step 3, Paste $s_\ell = $ 1 times: we get $s = $ 2313113113111311311131131. Step 4: $\ell = 5 = x$, so we stop. At the end of the procedure, $s$ has length $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. This is an easier version of the next problem. In this version, $q = 0$. A sequence of integers is called nice if its elements are arranged in blocks like in $[3, 3, 3, 4, 1, 1]$. Formally, if two elements are equal, everything in between must also be equal. Let's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value $x$ to value $y$, you must also change all other elements of value $x$ into $y$ as well. For example, for $[3, 3, 1, 3, 2, 1, 2]$ it isn't allowed to change first $1$ to $3$ and second $1$ to $2$. You need to leave $1$'s untouched or change them to the same value. You are given a sequence of integers $a_1, a_2, \ldots, a_n$ and $q$ updates. Each update is of form "$i$ $x$" — change $a_i$ to $x$. Updates are not independent (the change stays for the future). Print the difficulty of the initial sequence and of the sequence after every update. -----Input----- The first line contains integers $n$ and $q$ ($1 \le n \le 200\,000$, $q = 0$), the length of the sequence and the number of the updates. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 200\,000$), the initial sequence. Each of the following $q$ lines contains integers $i_t$ and $x_t$ ($1 \le i_t \le n$, $1 \le x_t \le 200\,000$), the position and the new value for this position. -----Output----- Print $q+1$ integers, the answer for the initial sequence and the answer after every update. -----Examples----- Input 5 0 3 7 3 7 3 Output 2 Input 10 0 1 2 1 2 3 1 1 1 50 1 Output 4 Input 6 0 6 6 3 3 4 4 Output 0 Input 7 0 3 3 1 3 2 1 2 Output 4 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. [Image] The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. -----Input----- The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}), which means that there is an edge between vertices a_{i} and b_{i}. It is guaranteed that there is at most one edge between each pair of vertexes. -----Output----- If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. -----Examples----- Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 -----Note----- In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? -----Input----- A single integer n (1 ≤ n ≤ 10^5), the number of the apples. -----Output----- The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. -----Examples----- Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 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. Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type: + a_{i} — add non-negative integer a_{i} to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer. - a_{i} — delete a single occurrence of non-negative integer a_{i} from the multiset. It's guaranteed, that there is at least one a_{i} in the multiset. ? s — count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not. -----Input----- The first line of the input contains an integer t (1 ≤ t ≤ 100 000) — the number of operation Sonya has to perform. Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character c_{i} — the type of the corresponding operation. If c_{i} is equal to '+' or '-' then it's followed by a space and an integer a_{i} (0 ≤ a_{i} < 10^18) given without leading zeroes (unless it's 0). If c_{i} equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18. It's guaranteed that there will be at least one query of type '?'. It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it. -----Output----- For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time. -----Examples----- Input 12 + 1 + 241 ? 1 + 361 - 241 ? 0101 + 101 ? 101 - 101 ? 101 + 4000 ? 0 Output 2 1 2 1 1 Input 4 + 200 + 200 - 200 ? 0 Output 1 -----Note----- Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a sequence a consisting of n integers. Find the maximum possible value of $a_{i} \operatorname{mod} a_{j}$ (integer remainder of a_{i} divided by a_{j}), where 1 ≤ i, j ≤ n and a_{i} ≥ a_{j}. -----Input----- The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·10^5). The second line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 10^6). -----Output----- Print the answer to the problem. -----Examples----- Input 3 3 4 5 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are n beacons located at distinct positions on a number line. The i-th beacon has position a_{i} and power level b_{i}. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance b_{i} inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated. Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. -----Input----- The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers a_{i} and b_{i} (0 ≤ a_{i} ≤ 1 000 000, 1 ≤ b_{i} ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so a_{i} ≠ a_{j} if i ≠ j. -----Output----- Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. -----Examples----- Input 4 1 9 3 1 6 1 7 4 Output 1 Input 7 1 1 2 1 3 1 4 1 5 1 6 1 7 1 Output 3 -----Note----- For the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2. For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 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. John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed. There are $n$ students, each of them has a unique id (from $1$ to $n$). Thomas's id is $1$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids. In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 1000$) — the number of students. Each of the next $n$ lines contains four integers $a_i$, $b_i$, $c_i$, and $d_i$ ($0\leq a_i, b_i, c_i, d_i\leq 100$) — the grades of the $i$-th student on English, German, Math, and History. The id of the $i$-th student is equal to $i$. -----Output----- Print the rank of Thomas Smith. Thomas's id is $1$. -----Examples----- Input 5 100 98 100 100 100 100 100 100 100 100 99 99 90 99 90 100 100 98 60 99 Output 2 Input 6 100 80 90 99 60 60 60 60 90 60 100 60 60 100 60 80 100 100 0 100 0 0 0 0 Output 1 -----Note----- In the first sample, the students got total scores: $398$, $400$, $398$, $379$, and $357$. Among the $5$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $2$. In the second sample, the students got total scores: $369$, $240$, $310$, $300$, $300$, and $0$. Among the $6$ students, Thomas got the highest score, so his rank is $1$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads. [Image] Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows: let starting_time be an array of length n current_time = 0 dfs(v): current_time = current_time + 1 starting_time[v] = current_time shuffle children[v] randomly (each permutation with equal possibility) // children[v] is vector of children cities of city v for u in children[v]: dfs(u) As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)). Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help. -----Input----- The first line of input contains a single integer n (1 ≤ n ≤ 10^5) — the number of cities in USC. The second line contains n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_{i} < i), where p_{i} is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered p_{i} and i in USC. -----Output----- In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i]. Your answer for each city will be considered correct if its absolute or relative error does not exceed 10^{ - 6}. -----Examples----- Input 7 1 2 1 1 4 4 Output 1.0 4.0 5.0 3.5 4.5 5.0 5.0 Input 12 1 1 2 2 4 4 3 3 1 10 8 Output 1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.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 an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case. Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal. -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the length of the array. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the elements of the array. -----Output----- Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array. -----Examples----- Input 7 10 1 1 1 5 5 3 Output 4 Input 5 1 1 1 1 1 Output 0 -----Note----- In the first sample, one of the best permutations is $[1, 5, 5, 3, 10, 1, 1]$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4. In the second sample, there is no way to increase any element with a permutation, so the answer is 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 a string S of length n with each character being one of the first m lowercase English letters. Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1. Recall that LCS of two strings S and T is the longest string C such that C both in S and T as a subsequence. -----Input----- The first line contains two numbers n and m denoting the length of string S and number of first English lowercase characters forming the character set for strings (1 ≤ n ≤ 100 000, 2 ≤ m ≤ 26). The second line contains string S. -----Output----- Print the only line containing the answer. -----Examples----- Input 3 3 aaa Output 6 Input 3 3 aab Output 11 Input 1 2 a Output 1 Input 10 9 abacadefgh Output 789 -----Note----- For the first sample, the 6 possible strings T are: aab, aac, aba, aca, baa, caa. For the second sample, the 11 possible strings T are: aaa, aac, aba, abb, abc, aca, acb, baa, bab, caa, cab. For the third sample, the only possible string T is 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. There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name. There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account? Formally, we assume that two words denote the same name, if using the replacements "u" [Image] "oo" and "h" [Image] "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements. For example, the following pairs of words denote the same name: "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" $\rightarrow$ "kuuper" and "kuooper" $\rightarrow$ "kuuper". "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" $\rightarrow$ "khoon" and "kkkhoon" $\rightarrow$ "kkhoon" $\rightarrow$ "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name. -----Input----- The first line contains integer number n (2 ≤ n ≤ 400) — number of the words in the list. The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive. -----Output----- Print the minimal number of groups where the words in each group denote the same name. -----Examples----- Input 10 mihail oolyana kooooper hoon ulyana koouper mikhail khun kuooper kkkhoon Output 4 Input 9 hariton hkariton buoi kkkhariton boooi bui khariton boui boi Output 5 Input 2 alex alex Output 1 -----Note----- There are four groups of words in the first example. Words in each group denote same name: "mihail", "mikhail" "oolyana", "ulyana" "kooooper", "koouper" "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name: "hariton", "kkkhariton", "khariton" "hkariton" "buoi", "boooi", "boui" "bui" "boi" In the third example the words are equal, so they denote the same name. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it. [Image]  There are $n$ cities and $n-1$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $1$ to $n$, and the city $1$ is the capital of the kingdom. So, the kingdom has a tree structure. As the queen, Linova plans to choose exactly $k$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city. A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique). Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path. In order to be a queen loved by people, Linova wants to choose $k$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her? -----Input----- The first line contains two integers $n$ and $k$ ($2\le n\le 2 \cdot 10^5$, $1\le k< n$)  — the number of cities and industry cities respectively. Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1\le u,v\le n$), denoting there is a road connecting city $u$ and city $v$. It is guaranteed that from any city, you can reach any other city by the roads. -----Output----- Print the only line containing a single integer  — the maximum possible sum of happinesses of all envoys. -----Examples----- Input 7 4 1 2 1 3 1 4 3 5 3 6 4 7 Output 7 Input 4 1 1 2 1 3 2 4 Output 2 Input 8 5 7 5 1 7 6 1 3 7 8 3 2 1 4 5 Output 9 -----Note----- [Image] In the first example, Linova can choose cities $2$, $5$, $6$, $7$ to develop industry, then the happiness of the envoy from city $2$ is $1$, the happiness of envoys from cities $5$, $6$, $7$ is $2$. The sum of happinesses is $7$, and it can be proved to be the maximum one. [Image] In the second example, choosing cities $3$, $4$ developing industry can reach a sum of $3$, but remember that Linova plans to choose exactly $k$ cities developing industry, then the maximum sum is $2$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given a sequence of n integers a_1, a_2, ..., a_{n}. Determine a real number x such that the weakness of the sequence a_1 - x, a_2 - x, ..., a_{n} - x is as small as possible. The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence. The poorness of a segment is defined as the absolute value of sum of the elements of segment. -----Input----- The first line contains one integer n (1 ≤ n ≤ 200 000), the length of a sequence. The second line contains n integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 10 000). -----Output----- Output a real number denoting the minimum possible weakness of a_1 - x, a_2 - x, ..., a_{n} - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10^{ - 6}. -----Examples----- Input 3 1 2 3 Output 1.000000000000000 Input 4 1 2 3 4 Output 2.000000000000000 Input 10 1 10 2 9 3 8 4 7 5 6 Output 4.500000000000000 -----Note----- For the first case, the optimal value of x is 2 so the sequence becomes - 1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case. For the second sample the optimal value of x is 2.5 so the sequence becomes - 1.5, - 0.5, 0.5, 1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. An array of integers $p_{1},p_{2}, \ldots,p_{n}$ is called a permutation if it contains each number from $1$ to $n$ exactly once. For example, the following arrays are permutations: $[3,1,2], [1], [1,2,3,4,5]$ and $[4,3,1,2]$. The following arrays are not permutations: $[2], [1,1], [2,3,4]$. There is a hidden permutation of length $n$. For each index $i$, you are given $s_{i}$, which equals to the sum of all $p_{j}$ such that $j < i$ and $p_{j} < p_{i}$. In other words, $s_i$ is the sum of elements before the $i$-th element that are smaller than the $i$-th element. Your task is to restore the permutation. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{5}$) — the size of the permutation. The second line contains $n$ integers $s_{1}, s_{2}, \ldots, s_{n}$ ($0 \le s_{i} \le \frac{n(n-1)}{2}$). It is guaranteed that the array $s$ corresponds to a valid permutation of length $n$. -----Output----- Print $n$ integers $p_{1}, p_{2}, \ldots, p_{n}$ — the elements of the restored permutation. We can show that the answer is always unique. -----Examples----- Input 3 0 0 0 Output 3 2 1 Input 2 0 1 Output 1 2 Input 5 0 1 1 1 10 Output 1 4 3 2 5 -----Note----- In the first example for each $i$ there is no index $j$ satisfying both conditions, hence $s_i$ are always $0$. In the second example for $i = 2$ it happens that $j = 1$ satisfies the conditions, so $s_2 = p_1$. In the third example for $i = 2, 3, 4$ only $j = 1$ satisfies the conditions, so $s_2 = s_3 = s_4 = 1$. For $i = 5$ all $j = 1, 2, 3, 4$ are possible, so $s_5 = p_1 + p_2 + p_3 + p_4 = 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. Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as p_{i}. For all pairs of distinct integers i, j between 1 and n, he wrote the number a_{i}, j = min(p_{i}, p_{j}). He writes a_{i}, i = 0 for all integer i from 1 to n. Bob gave you all the values of a_{i}, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given. -----Input----- The first line of the input will contain a single integer n (2 ≤ n ≤ 50). The next n lines will contain the values of a_{i}, j. The j-th number on the i-th line will represent a_{i}, j. The i-th number on the i-th line will be 0. It's guaranteed that a_{i}, j = a_{j}, i and there is at least one solution consistent with the information given. -----Output----- Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them. -----Examples----- Input 2 0 1 1 0 Output 2 1 Input 5 0 2 2 1 2 2 0 4 1 3 2 4 0 1 3 1 1 1 0 1 2 3 3 1 0 Output 2 5 4 1 3 -----Note----- In the first case, the answer can be {1, 2} or {2, 1}. In the second case, another possible answer is {2, 4, 5, 1, 3}. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one. Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task. -----Input----- The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p_1, then coin located at position p_2 and so on. Coins are numbered from left to right. -----Output----- Print n + 1 numbers a_0, a_1, ..., a_{n}, where a_0 is a hardness of ordering at the beginning, a_1 is a hardness of ordering after the first replacement and so on. -----Examples----- Input 4 1 3 4 2 Output 1 2 3 2 1 Input 8 6 8 3 4 7 2 1 5 Output 1 2 2 3 4 3 4 5 1 -----Note----- Let's denote as O coin out of circulation, and as X — coin is circulation. At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges. After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process. XOOO → OOOX After replacement of the third coin, Dima's actions look this way: XOXO → OXOX → OOXX After replacement of the fourth coin, Dima's actions look this way: XOXX → OXXX Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost. Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network. Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results. -----Input----- The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers t_{i}, x_{i}, y_{i} (1 ≤ t_{i} ≤ 2; x_{i}, y_{i} ≥ 0; x_{i} + y_{i} = 10). If t_{i} = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers x_{i}, y_{i} represent the result of executing this command, that is, x_{i} packets reached the corresponding server successfully and y_{i} packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command. -----Output----- In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server b in the similar format. -----Examples----- Input 2 1 5 5 2 6 4 Output LIVE LIVE Input 3 1 0 10 2 0 10 1 10 0 Output LIVE DEAD -----Note----- Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network. Read the inputs from stdin solve the problem and write the answer to stdout (do 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 legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo! There are $n$ snacks flavors, numbered with integers $1, 2, \ldots, n$. Bessie has $n$ snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows: First, Bessie will line up the guests in some way. Then in this order, guests will approach the snacks one by one. Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad. Help Bessie to minimize the number of sad guests by lining the guests in an optimal way. -----Input----- The first line contains integers $n$ and $k$ ($2 \le n \le 10^5$, $1 \le k \le 10^5$), the number of snacks and the number of guests. The $i$-th of the following $k$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$), favorite snack flavors of the $i$-th guest. -----Output----- Output one integer, the smallest possible number of sad guests. -----Examples----- Input 5 4 1 2 4 3 1 4 3 4 Output 1 Input 6 5 2 3 2 1 3 4 6 5 4 5 Output 0 -----Note----- In the first example, Bessie can order the guests like this: $3, 1, 2, 4$. Guest $3$ goes first and eats snacks $1$ and $4$. Then the guest $1$ goes and eats the snack $2$ only, because the snack $1$ has already been eaten. Similarly, the guest $2$ goes up and eats the snack $3$ only. All the snacks are gone, so the guest $4$ will be sad. In the second example, one optimal ordering is $2, 1, 3, 5, 4$. All the guests will be 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. You are given a sequence a = \{a_1, ..., a_N\} with all zeros, and a sequence b = \{b_1, ..., b_N\} consisting of 0 and 1. The length of both is N. You can perform Q kinds of operations. The i-th operation is as follows: - Replace each of a_{l_i}, a_{l_i + 1}, ..., a_{r_i} with 1. Minimize the hamming distance between a and b, that is, the number of i such that a_i \neq b_i, by performing some of the Q operations. -----Constraints----- - 1 \leq N \leq 200,000 - b consists of 0 and 1. - 1 \leq Q \leq 200,000 - 1 \leq l_i \leq r_i \leq N - If i \neq j, either l_i \neq l_j or r_i \neq r_j. -----Input----- Input is given from Standard Input in the following format: N b_1 b_2 ... b_N Q l_1 r_1 l_2 r_2 : l_Q r_Q -----Output----- Print the minimum possible hamming distance. -----Sample Input----- 3 1 0 1 1 1 3 -----Sample Output----- 1 If you choose to perform the operation, a will become \{1, 1, 1\}, for a hamming distance of 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. Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm. Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows: [Image] You have to write a program that allows you to determine what number will be in the cell with index x (1 ≤ x ≤ n) after Dima's algorithm finishes. -----Input----- The first line contains two integers n and q (1 ≤ n ≤ 10^18, 1 ≤ q ≤ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer. Next q lines contain integers x_{i} (1 ≤ x_{i} ≤ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes. -----Output----- For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes. -----Examples----- Input 4 3 2 3 4 Output 3 2 4 Input 13 4 10 5 4 8 Output 13 3 8 9 -----Note----- The first example is shown in the picture. In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7]. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: $f(0) = a$; $f(1) = b$; $f(n) = f(n-1) \oplus f(n-2)$ when $n > 1$, where $\oplus$ denotes the bitwise XOR operation. You are given three integers $a$, $b$, and $n$, calculate $f(n)$. You have to answer for $T$ independent test cases. -----Input----- The input contains one or more independent test cases. The first line of input contains a single integer $T$ ($1 \le T \le 10^3$), the number of test cases. Each of the $T$ following lines contains three space-separated integers $a$, $b$, and $n$ ($0 \le a, b, n \le 10^9$) respectively. -----Output----- For each test case, output $f(n)$. -----Example----- Input 3 3 4 2 4 5 0 325 265 1231232 Output 7 4 76 -----Note----- In the first example, $f(2) = f(0) \oplus f(1) = 3 \oplus 4 = 7$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive. All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road. Your task is — for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (10^9 + 7). -----Input----- The first line of the input contains a single integer n (2 ≤ n ≤ 2·10^5) — the number of cities in the country. Next line contains n - 1 positive integers p_2, p_3, p_4, ..., p_{n} (1 ≤ p_{i} ≤ i - 1) — the description of the roads in the country. Number p_{i} means that the country has a road connecting city p_{i} and city i. -----Output----- Print n integers a_1, a_2, ..., a_{n}, where a_{i} is the sought number of ways to improve the quality of the roads modulo 1 000 000 007 (10^9 + 7), if the capital of the country is at city number i. -----Examples----- Input 3 1 1 Output 4 3 3 Input 5 1 2 3 4 Output 5 8 9 8 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. Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city u_{i} to v_{i} (and vise versa) using the i-th road, the length of this road is x_{i}. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city s_{i} (and vise versa), the length of this route is y_{i}. Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. -----Input----- The first line contains three integers n, m, k (2 ≤ n ≤ 10^5; 1 ≤ m ≤ 3·10^5; 1 ≤ k ≤ 10^5). Each of the next m lines contains three integers u_{i}, v_{i}, x_{i} (1 ≤ u_{i}, v_{i} ≤ n; u_{i} ≠ v_{i}; 1 ≤ x_{i} ≤ 10^9). Each of the next k lines contains two integers s_{i} and y_{i} (2 ≤ s_{i} ≤ n; 1 ≤ y_{i} ≤ 10^9). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. -----Output----- Output a single integer representing the maximum number of the train routes which can be closed. -----Examples----- Input 5 5 3 1 2 1 2 3 2 1 3 3 3 4 4 1 5 5 3 5 4 5 5 5 Output 2 Input 2 2 3 1 2 2 2 1 3 2 1 2 2 2 3 Output 2 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q_1q_2... q_{k}. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string. Sereja wants to test his algorithm. For that, he has string s = s_1s_2... s_{n}, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring s_{l}_{i}s_{l}_{i} + 1... s_{r}_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (l_{i}, r_{i}) determine if the algorithm works correctly on this test or not. -----Input----- The first line contains non-empty string s, its length (n) doesn't exceed 10^5. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 10^5) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). -----Output----- For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. -----Examples----- Input zyxxxxxxyyz 5 5 5 1 3 1 11 1 4 3 6 Output YES YES NO YES NO -----Note----- In the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There is a country with $n$ citizens. The $i$-th of them initially has $a_{i}$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have. Sometimes the government makes payouts to the poor: all citizens who have strictly less money than $x$ are paid accordingly so that after the payout they have exactly $x$ money. In this case the citizens don't send a receipt. You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{5}$) — the numer of citizens. The next line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_{i} \le 10^{9}$) — the initial balances of citizens. The next line contains a single integer $q$ ($1 \le q \le 2 \cdot 10^{5}$) — the number of events. Each of the next $q$ lines contains a single event. The events are given in chronological order. Each event is described as either 1 p x ($1 \le p \le n$, $0 \le x \le 10^{9}$), or 2 x ($0 \le x \le 10^{9}$). In the first case we have a receipt that the balance of the $p$-th person becomes equal to $x$. In the second case we have a payoff with parameter $x$. -----Output----- Print $n$ integers — the balances of all citizens after all events. -----Examples----- Input 4 1 2 3 4 3 2 3 1 2 2 2 1 Output 3 2 3 4 Input 5 3 50 2 1 10 3 1 2 0 2 8 1 3 20 Output 8 8 20 8 10 -----Note----- In the first example the balances change as follows: 1 2 3 4 $\rightarrow$ 3 3 3 4 $\rightarrow$ 3 2 3 4 $\rightarrow$ 3 2 3 4 In the second example the balances change as follows: 3 50 2 1 10 $\rightarrow$ 3 0 2 1 10 $\rightarrow$ 8 8 8 8 10 $\rightarrow$ 8 8 20 8 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. During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace. The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters. The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: $1$, $2$, $3$, so that each character is painted in at most one color, and the description of the $i$-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color $i$. The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace. -----Input----- The first line of the input contains two integers $n, q$ ($1 \leq n \leq 100\,000$, $1 \leq q \leq 1000$) — the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe — a string of length $n$ consisting of lowercase English characters. Each of the following line describes a single evolution and is in one of the following formats: + $i$ $c$ ($i \in \{1, 2, 3\}$, $c \in \{\mathtt{a}, \mathtt{b}, \dots, \mathtt{z}\}$: append the character $c$ to the end of $i$-th religion description. - $i$ ($i \in \{1, 2, 3\}$) – remove the last character from the $i$-th religion description. You can assume that the pattern is non-empty. You can assume that no religion will have description longer than $250$ characters. -----Output----- Write $q$ lines. The $i$-th of them should be YES if the religions could coexist in peace after the $i$-th evolution, or NO otherwise. You can print each character in any case (either upper or lower). -----Examples----- Input 6 8 abdabc + 1 a + 1 d + 2 b + 2 c + 3 a + 3 b + 1 c - 2 Output YES YES YES YES YES YES NO YES Input 6 8 abbaab + 1 a + 2 a + 3 a + 1 b + 2 b + 3 b - 1 + 2 z Output YES YES YES YES YES NO YES NO -----Note----- In the first example, after the 6th evolution the religion descriptions are: ad, bc, and ab. The following figure shows how these descriptions form three disjoint subsequences of the Word of Universe: $\left. \begin{array}{|c|c|c|c|c|c|c|} \hline \text{Word} & {a} & {b} & {d} & {a} & {b} & {c} \\ \hline ad & {a} & {} & {d} & {} & {} & {} \\ \hline bc & {} & {b} & {} & {} & {} & {c} \\ \hline ab & {} & {} & {} & {a} & {b} & {} \\ \hline \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. Serge came to the school dining room and discovered that there is a big queue here. There are $m$ pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him. Initially there are $n$ dishes with costs $a_1, a_2, \ldots, a_n$. As you already know, there are the queue of $m$ pupils who have $b_1, \ldots, b_m$ togrogs respectively (pupils are enumerated by queue order, i.e the first pupil in the queue has $b_1$ togrogs and the last one has $b_m$ togrogs) Pupils think that the most expensive dish is the most delicious one, so every pupil just buys the most expensive dish for which he has money (every dish has a single copy, so when a pupil has bought it nobody can buy it later), and if a pupil doesn't have money for any dish, he just leaves the queue (so brutal capitalism...) But money isn't a problem at all for Serge, so Serge is buying the most expensive dish if there is at least one remaining. Moreover, Serge's school has a very unstable economic situation and the costs of some dishes or number of togrogs of some pupils can change. More formally, you must process $q$ queries: change $a_i$ to $x$. It means that the price of the $i$-th dish becomes $x$ togrogs. change $b_i$ to $x$. It means that the $i$-th pupil in the queue has $x$ togrogs now. Nobody leaves the queue during those queries because a saleswoman is late. After every query, you must tell Serge price of the dish which he will buy if he has waited until the queue is clear, or $-1$ if there are no dishes at this point, according to rules described above. -----Input----- The first line contains integers $n$ and $m$ ($1 \leq n, m \leq 300\ 000$) — number of dishes and pupils respectively. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^{6}$) — elements of array $a$. The third line contains $m$ integers $b_1, b_2, \ldots, b_{m}$ ($1 \leq b_i \leq 10^{6}$) — elements of array $b$. The fourth line conatins integer $q$ ($1 \leq q \leq 300\ 000$) — number of queries. Each of the following $q$ lines contains as follows: if a query changes price of some dish, it contains $1$, and two integers $i$ and $x$ ($1 \leq i \leq n$, $1 \leq x \leq 10^{6}$), what means $a_i$ becomes $x$. if a query changes number of togrogs of some pupil, it contains $2$, and two integers $i$ and $x$ ($1 \leq i \leq m$, $1 \leq x \leq 10^{6}$), what means $b_i$ becomes $x$. -----Output----- For each of $q$ queries prints the answer as the statement describes, the answer of the $i$-th query in the $i$-th line (the price of the dish which Serge will buy or $-1$ if nothing remains) -----Examples----- Input 1 1 1 1 1 1 1 100 Output 100 Input 1 1 1 1 1 2 1 100 Output -1 Input 4 6 1 8 2 4 3 3 6 1 5 2 3 1 1 1 2 5 10 1 1 6 Output 8 -1 4 -----Note----- In the first sample after the first query, there is one dish with price $100$ togrogs and one pupil with one togrog, so Serge will buy the dish with price $100$ togrogs. In the second sample after the first query, there is one dish with price one togrog and one pupil with $100$ togrogs, so Serge will get nothing. In the third sample after the first query, nobody can buy the dish with price $8$, so Serge will take it. After the second query, all dishes will be bought, after the third one the third and fifth pupils will by the first and the second dishes respectively and nobody will by the fourth 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. Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a_1, a_2, ..., a_{n}, then after we apply the described operation, the sequence transforms into a_1, a_2, ..., a_{n}[, a_1, a_2, ..., a_{l}] (the block in the square brackets must be repeated c times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja. -----Input----- The first line contains integer m (1 ≤ m ≤ 10^5) — the number of stages to build a sequence. Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer x_{i} (1 ≤ x_{i} ≤ 10^5) — the number to add. Type 2 means copying a prefix of length l_{i} to the end c_{i} times, in this case the line further contains two integers l_{i}, c_{i} (1 ≤ l_{i} ≤ 10^5, 1 ≤ c_{i} ≤ 10^4), l_{i} is the length of the prefix, c_{i} is the number of copyings. It is guaranteed that the length of prefix l_{i} is never larger than the current length of the sequence. The next line contains integer n (1 ≤ n ≤ 10^5) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. 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----- Print the elements that Sereja is interested in, in the order in which their numbers occur in the input. -----Examples----- Input 6 1 1 1 2 2 2 1 1 3 2 5 2 1 4 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output 1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The mobile application store has a new game called "Subway Roller". The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field. All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel. Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column. [Image] -----Input----- Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 ≤ t ≤ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) — the number of sets. Then follows the description of t sets of the input data. The first line of the description of each set contains two integers n, k (2 ≤ n ≤ 100, 1 ≤ k ≤ 26) — the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains. -----Output----- For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise. -----Examples----- Input 2 16 4 ...AAAAA........ s.BBB......CCCCC ........DDDDD... 16 4 ...AAAAA........ s.BBB....CCCCC.. .......DDDDD.... Output YES NO Input 2 10 4 s.ZZ...... .....AAABB .YYYYYY... 10 4 s.ZZ...... ....AAAABB .YYYYYY... Output YES NO -----Note----- In the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel. Note that in this problem the challenges are restricted to tests that contain only one testset. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You've got a list of program warning logs. Each record of a log stream is a string in this format: "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format. The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description). Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m. -----Input----- The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 10000). The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program. It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·10^6 (in particular, this means that the length of some line does not exceed 5·10^6 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty. -----Output----- If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) — the first moment of time when the number of warnings for the last n seconds got no less than m. -----Examples----- Input 60 3 2012-03-16 16:15:25: Disk size is 2012-03-16 16:15:25: Network failute 2012-03-16 16:16:29: Cant write varlog 2012-03-16 16:16:42: Unable to start process 2012-03-16 16:16:43: Disk size is too small 2012-03-16 16:16:53: Timeout detected Output 2012-03-16 16:16:43 Input 1 2 2012-03-16 23:59:59:Disk size 2012-03-17 00:00:00: Network 2012-03-17 00:00:01:Cant write varlog Output -1 Input 2 2 2012-03-16 23:59:59:Disk size is too sm 2012-03-17 00:00:00:Network failute dete 2012-03-17 00:00:01:Cant write varlogmysq Output 2012-03-17 00:00:00 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question: Given two binary numbers $a$ and $b$ of length $n$. How many different ways of swapping two digits in $a$ (only in $a$, not $b$) so that bitwise OR of these two numbers will be changed? In other words, let $c$ be the bitwise OR of $a$ and $b$, you need to find the number of ways of swapping two bits in $a$ so that bitwise OR will not be equal to $c$. Note that binary numbers can contain leading zeros so that length of each number is exactly $n$. Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $01010_2$ OR $10011_2$ = $11011_2$. Well, to your surprise, you are not Rudolf, and you don't need to help him$\ldots$ You are the security staff! Please find the number of ways of swapping two bits in $a$ so that bitwise OR will be changed. -----Input----- The first line contains one integer $n$ ($2\leq n\leq 10^5$) — the number of bits in each number. The second line contains a binary number $a$ of length $n$. The third line contains a binary number $b$ of length $n$. -----Output----- Print the number of ways to swap two bits in $a$ so that bitwise OR will be changed. -----Examples----- Input 5 01011 11001 Output 4 Input 6 011000 010011 Output 6 -----Note----- In the first sample, you can swap bits that have indexes $(1, 4)$, $(2, 3)$, $(3, 4)$, and $(3, 5)$. In the second example, you can swap bits that have indexes $(1, 2)$, $(1, 3)$, $(2, 4)$, $(3, 4)$, $(3, 5)$, and $(3, 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. For strings s and t, we will say that s and t are prefix-free when neither is a prefix of the other. Let L be a positive integer. A set of strings S is a good string set when the following conditions hold true: - Each string in S has a length between 1 and L (inclusive) and consists of the characters 0 and 1. - Any two distinct strings in S are prefix-free. We have a good string set S = \{ s_1, s_2, ..., s_N \}. Alice and Bob will play a game against each other. They will alternately perform the following operation, starting from Alice: - Add a new string to S. After addition, S must still be a good string set. The first player who becomes unable to perform the operation loses the game. Determine the winner of the game when both players play optimally. -----Constraints----- - 1 \leq N \leq 10^5 - 1 \leq L \leq 10^{18} - s_1, s_2, ..., s_N are all distinct. - { s_1, s_2, ..., s_N } is a good string set. - |s_1| + |s_2| + ... + |s_N| \leq 10^5 -----Input----- Input is given from Standard Input in the following format: N L s_1 s_2 : s_N -----Output----- If Alice will win, print Alice; if Bob will win, print Bob. -----Sample Input----- 2 2 00 01 -----Sample Output----- Alice If Alice adds 1, Bob will be unable to add a new string. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string $s_1s_2\ldots s_n$ of length $n$. $1$ represents an apple and $0$ represents an orange. Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguous sequence of apples. Let $f(l,r)$ be the longest contiguous sequence of apples in the substring $s_{l}s_{l+1}\ldots s_{r}$. Help Zookeeper find $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$, or the sum of $f$ across all substrings. -----Input----- The first line contains a single integer $n$ $(1 \leq n \leq 5 \cdot 10^5)$. The next line contains a binary string $s$ of length $n$ $(s_i \in \{0,1\})$ -----Output----- Print a single integer: $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$. -----Examples----- Input 4 0110 Output 12 Input 7 1101001 Output 30 Input 12 011100011100 Output 156 -----Note----- In the first test, there are ten substrings. The list of them (we let $[l,r]$ be the substring $s_l s_{l+1} \ldots s_r$): $[1,1]$: 0 $[1,2]$: 01 $[1,3]$: 011 $[1,4]$: 0110 $[2,2]$: 1 $[2,3]$: 11 $[2,4]$: 110 $[3,3]$: 1 $[3,4]$: 10 $[4,4]$: 0 The lengths of the longest contiguous sequence of ones in each of these ten substrings are $0,1,2,2,1,2,2,1,1,0$ respectively. Hence, the answer is $0+1+2+2+1+2+2+1+1+0 = 12$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You are given a regular bracket sequence $s$ and an integer number $k$. Your task is to find a regular bracket sequence of length exactly $k$ such that it is also a subsequence of $s$. It is guaranteed that such sequence always exists. -----Input----- The first line contains two integers $n$ and $k$ ($2 \le k \le n \le 2 \cdot 10^5$, both $n$ and $k$ are even) — the length of $s$ and the length of the sequence you are asked to find. The second line is a string $s$ — regular bracket sequence of length $n$. -----Output----- Print a single string — a regular bracket sequence of length exactly $k$ such that it is also a subsequence of $s$. It is guaranteed that such sequence always exists. -----Examples----- Input 6 4 ()(()) Output ()() Input 8 8 (()(())) 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. There are $n$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends. We want to plan a trip for every evening of $m$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: Either this person does not go on the trip, Or at least $k$ of his friends also go on the trip. Note that the friendship is not transitive. That is, if $a$ and $b$ are friends and $b$ and $c$ are friends, it does not necessarily imply that $a$ and $c$ are friends. For each day, find the maximum number of people that can go on the trip on that day. -----Input----- The first line contains three integers $n$, $m$, and $k$ ($2 \leq n \leq 2 \cdot 10^5, 1 \leq m \leq 2 \cdot 10^5$, $1 \le k < n$) — the number of people, the number of days and the number of friends each person on the trip should have in the group. The $i$-th ($1 \leq i \leq m$) of the next $m$ lines contains two integers $x$ and $y$ ($1\leq x, y\leq n$, $x\ne y$), meaning that persons $x$ and $y$ become friends on the morning of day $i$. It is guaranteed that $x$ and $y$ were not friends before. -----Output----- Print exactly $m$ lines, where the $i$-th of them ($1\leq i\leq m$) contains the maximum number of people that can go on the trip on the evening of the day $i$. -----Examples----- Input 4 4 2 2 3 1 2 1 3 1 4 Output 0 0 3 3 Input 5 8 2 2 1 4 2 5 4 5 2 4 3 5 1 4 1 3 2 Output 0 0 0 3 3 4 4 5 Input 5 7 2 1 5 3 2 2 5 3 4 1 2 5 3 1 3 Output 0 0 0 0 3 4 4 -----Note----- In the first example, $1,2,3$ can go on day $3$ and $4$. In the second example, $2,4,5$ can go on day $4$ and $5$. $1,2,4,5$ can go on day $6$ and $7$. $1,2,3,4,5$ can go on day $8$. In the third example, $1,2,5$ can go on day $5$. $1,2,3,5$ can go on day $6$ and $7$. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her. Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a_1... a_{|}t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya". Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey. It is guaranteed that the word p can be obtained by removing the letters from word t. -----Input----- The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| < |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a_1, a_2, ..., a_{|}t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ a_{i} ≤ |t|, all a_{i} are distinct). -----Output----- Print a single integer number, the maximum number of letters that Nastya can remove. -----Examples----- Input ababcba abb 5 3 4 1 7 6 2 Output 3 Input bbbabb bb 1 6 3 4 2 5 Output 4 -----Note----- In the first sample test sequence of removing made by Nastya looks like this: "ababcba" $\rightarrow$ "ababcba" $\rightarrow$ "ababcba" $\rightarrow$ "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba". So, Nastya will remove only three letters. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers p_{i}, a_{i} and b_{i}, where p_{i} is the price of the i-th t-shirt, a_{i} is front color of the i-th t-shirt and b_{i} is back color of the i-th t-shirt. All values p_{i} are distinct, and values a_{i} and b_{i} are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color c_{j}. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. -----Input----- The first line contains single integer n (1 ≤ n ≤ 200 000) — the number of t-shirts. The following line contains sequence of integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 1 000 000 000), where p_{i} equals to the price of the i-th t-shirt. The following line contains sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 3), where a_{i} equals to the front color of the i-th t-shirt. The following line contains sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 3), where b_{i} equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≤ m ≤ 200 000) — the number of buyers. The following line contains sequence c_1, c_2, ..., c_{m} (1 ≤ c_{j} ≤ 3), where c_{j} equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. -----Output----- Print to the first line m integers — the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. -----Examples----- Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $r \times c$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $a$, passes by another country $b$, they change the dominant religion of country $b$ to the dominant religion of country $a$. In particular, a single use of your power is this: You choose a horizontal $1 \times x$ subgrid or a vertical $x \times 1$ subgrid. That value of $x$ is up to you; You choose a direction $d$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $s$ of steps; You command each country in the subgrid to send a missionary group that will travel $s$ steps towards direction $d$. In each step, they will visit (and in effect convert the dominant religion of) all $s$ countries they pass through, as detailed above. The parameters $x$, $d$, $s$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $1 \times 4$ subgrid, the direction NORTH, and $s = 2$ steps. [Image] You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. -----Input----- The first line of input contains a single integer $t$ ($1 \le t \le 2\cdot 10^4$) denoting the number of test cases. The first line of each test case contains two space-separated integers $r$ and $c$ denoting the dimensions of the grid ($1 \le r, c \le 60$). The next $r$ lines each contains $c$ characters describing the dominant religions in the countries. In particular, the $j$-th character in the $i$-th line describes the dominant religion in the country at the cell with row $i$ and column $j$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $r \cdot c$ in a single file is at most $3 \cdot 10^6$. -----Output----- For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. -----Example----- Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 -----Note----- In the first test case, it can be done in two usages, as follows: Usage 1: [Image] Usage 2: [Image] In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '$\sqrt{}$' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1. When ZS the Coder is at level k, he can : Press the ' + ' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes x + k. Press the '$\sqrt{}$' button. Let the number on the screen be x. After pressing this button, the number becomes $\sqrt{x}$. After that, ZS the Coder levels up, so his current level becomes k + 1. This button can only be pressed when x is a perfect square, i.e. x = m^2 for some positive integer m. Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '$\sqrt{}$' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5. ZS the Coder needs your help in beating the game — he wants to reach level n + 1. In other words, he needs to press the '$\sqrt{}$' button n times. Help him determine the number of times he should press the ' + ' button before pressing the '$\sqrt{}$' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level n + 1, but not necessarily a sequence minimizing the number of presses. -----Input----- The first and only line of the input contains a single integer n (1 ≤ n ≤ 100 000), denoting that ZS the Coder wants to reach level n + 1. -----Output----- Print n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the ' + ' button before pressing the '$\sqrt{}$' button at level i. Each number in the output should not exceed 10^18. However, the number on the screen can be greater than 10^18. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them. -----Examples----- Input 3 Output 14 16 46 Input 2 Output 999999999999999998 44500000000 Input 4 Output 2 17 46 97 -----Note----- In the first sample case: On the first level, ZS the Coder pressed the ' + ' button 14 times (and the number on screen is initially 2), so the number became 2 + 14·1 = 16. Then, ZS the Coder pressed the '$\sqrt{}$' button, and the number became $\sqrt{16} = 4$. After that, on the second level, ZS pressed the ' + ' button 16 times, so the number becomes 4 + 16·2 = 36. Then, ZS pressed the '$\sqrt{}$' button, levelling up and changing the number into $\sqrt{36} = 6$. After that, on the third level, ZS pressed the ' + ' button 46 times, so the number becomes 6 + 46·3 = 144. Then, ZS pressed the '$\sqrt{}$' button, levelling up and changing the number into $\sqrt{144} = 12$. Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4. Also, note that pressing the ' + ' button 10 times on the third level before levelling up does not work, because the number becomes 6 + 10·3 = 36, and when the '$\sqrt{}$' button is pressed, the number becomes $\sqrt{36} = 6$ and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution. In the second sample case: On the first level, ZS the Coder pressed the ' + ' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2 + 999999999999999998·1 = 10^18. Then, ZS the Coder pressed the '$\sqrt{}$' button, and the number became $\sqrt{10^{18}} = 10^{9}$. After that, on the second level, ZS pressed the ' + ' button 44500000000 times, so the number becomes 10^9 + 44500000000·2 = 9·10^10. Then, ZS pressed the '$\sqrt{}$' button, levelling up and changing the number into $\sqrt{9 \cdot 10^{10}} = 300000$. Note that 300000 is a multiple of 3, so ZS the Coder can reach level 3. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. The Bubble Cup hypothesis stood unsolved for $130$ years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem: Given a number $m$, how many polynomials $P$ with coefficients in set ${\{0,1,2,3,4,5,6,7\}}$ have: $P(2)=m$? Help Jerry Mao solve the long standing problem! -----Input----- The first line contains a single integer $t$ $(1 \leq t \leq 5\cdot 10^5)$ - number of test cases. On next line there are $t$ numbers, $m_i$ $(1 \leq m_i \leq 10^{18})$ - meaning that in case $i$ you should solve for number $m_i$. -----Output----- For each test case $i$, print the answer on separate lines: number of polynomials $P$ as described in statement such that $P(2)=m_i$, modulo $10^9 + 7$. -----Example----- Input 2 2 4 Output 2 4 -----Note----- In first case, for $m=2$, polynomials that satisfy the constraint are $x$ and $2$. In second case, for $m=4$, polynomials that satisfy the constraint are $x^2$, $x + 2$, $2x$ and $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. Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible. The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities. What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan. Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city. Help the King to calculate this characteristic for each of his plan. -----Input----- The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cities in the kingdom. Each of the next n - 1 lines contains two distinct integers u_{i}, v_{i} (1 ≤ u_{i}, v_{i} ≤ n) — the indices of the cities connected by the i-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads. The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of King's plans. Each of the next q lines looks as follows: first goes number k_{i} — the number of important cities in the King's plan, (1 ≤ k_{i} ≤ n), then follow exactly k_{i} space-separated pairwise distinct numbers from 1 to n — the numbers of important cities in this plan. The sum of all k_{i}'s does't exceed 100 000. -----Output----- For each plan print a single integer — the minimum number of cities that the barbarians need to capture, or print - 1 if all the barbarians' attempts to isolate important cities will not be effective. -----Examples----- Input 4 1 3 2 3 4 3 4 2 1 2 3 2 3 4 3 1 2 4 4 1 2 3 4 Output 1 -1 1 -1 Input 7 1 2 2 3 3 4 1 5 5 6 5 7 1 4 2 4 6 7 Output 2 -----Note----- In the first sample, in the first and the third King's plan barbarians can capture the city 3, and that will be enough. In the second and the fourth plans all their attempts will not be effective. In the second sample the cities to capture are 3 and 5. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements. Right now he has a map of some imaginary city with $n$ subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once. One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them. Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations $u$ and $v$ that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station $w$ that the original map has a tunnel between $u$ and $w$ and a tunnel between $w$ and $v$. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map. -----Input----- The first line of the input contains a single integer $n$ ($2 \leq n \leq 200\,000$) — the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following $n - 1$ lines contains two integers $u_i$ and $v_i$ ($1 \leq u_i, v_i \leq n$, $u_i \ne v_i$), meaning the station with these indices are connected with a direct tunnel. It is guaranteed that these $n$ stations and $n - 1$ tunnels form a tree. -----Output----- Print one integer that is equal to the sum of distances between all pairs of stations after Sergey Semyonovich draws new tunnels between all pairs of stations that share a common neighbor in the original map. -----Examples----- Input 4 1 2 1 3 1 4 Output 6 Input 4 1 2 2 3 3 4 Output 7 -----Note----- In the first sample, in the new map all pairs of stations share a direct connection, so the sum of distances is $6$. In the second sample, the new map has a direct tunnel between all pairs of stations except for the pair $(1, 4)$. For these two stations the distance 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. Let's denote as $\text{popcount}(x)$ the number of bits set ('1' bits) in the binary representation of the non-negative integer x. You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and $\text{popcount}(x)$ is maximum possible. If there are multiple such numbers find the smallest of them. -----Input----- The first line contains integer n — the number of queries (1 ≤ n ≤ 10000). Each of the following n lines contain two integers l_{i}, r_{i} — the arguments for the corresponding query (0 ≤ l_{i} ≤ r_{i} ≤ 10^18). -----Output----- For each query print the answer in a separate line. -----Examples----- Input 3 1 2 2 4 1 10 Output 1 3 7 -----Note----- The binary representations of numbers from 1 to 10 are listed below: 1_10 = 1_2 2_10 = 10_2 3_10 = 11_2 4_10 = 100_2 5_10 = 101_2 6_10 = 110_2 7_10 = 111_2 8_10 = 1000_2 9_10 = 1001_2 10_10 = 1010_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. As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter. [Image] Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time. Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game? You have to determine the winner of the game for all initial positions of the marbles. -----Input----- The first line of input contains two integers n and m (2 ≤ n ≤ 100, $1 \leq m \leq \frac{n(n - 1)}{2}$). The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≤ v, u ≤ n, v ≠ u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic. -----Output----- Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise. -----Examples----- Input 4 4 1 2 b 1 3 a 2 4 c 3 4 b Output BAAA ABAA BBBA BBBB Input 5 8 5 3 h 1 2 c 3 1 c 3 2 r 5 1 r 4 3 z 5 4 r 5 2 h Output BABBB BBBBB AABBB AAABA AAAAB -----Note----- Here's the graph in the first sample test case: [Image] Here's the graph in the second sample test case: [Image] Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. There are 2N balls in the xy-plane. The coordinates of the i-th of them is (x_i, y_i). Here, x_i and y_i are integers between 1 and N (inclusive) for all i, and no two balls occupy the same coordinates. In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B. Then, he placed the type-A robots at coordinates (1, 0), (2, 0), ..., (N, 0), and the type-B robots at coordinates (0, 1), (0, 2), ..., (0, N), one at each position. When activated, each type of robot will operate as follows. - When a type-A robot is activated at coordinates (a, 0), it will move to the position of the ball with the lowest y-coordinate among the balls on the line x = a, collect the ball and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything. - When a type-B robot is activated at coordinates (0, b), it will move to the position of the ball with the lowest x-coordinate among the balls on the line y = b, collect the ball and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything. Once deactivated, a robot cannot be activated again. Also, while a robot is operating, no new robot can be activated until the operating robot is deactivated. When Snuke was about to activate a robot, he noticed that he may fail to collect all the balls, depending on the order of activating the robots. Among the (2N)! possible orders of activating the robots, find the number of the ones such that all the balls can be collected, modulo 1 000 000 007. -----Constraints----- - 2 \leq N \leq 10^5 - 1 \leq x_i \leq N - 1 \leq y_i \leq N - If i ≠ j, either x_i ≠ x_j or y_i ≠ y_j. -----Inputs----- Input is given from Standard Input in the following format: N x_1 y_1 ... x_{2N} y_{2N} -----Outputs----- Print the number of the orders of activating the robots such that all the balls can be collected, modulo 1 000 000 007. -----Sample Input----- 2 1 1 1 2 2 1 2 2 -----Sample Output----- 8 We will refer to the robots placed at (1, 0) and (2, 0) as A1 and A2, respectively, and the robots placed at (0, 1) and (0, 2) as B1 and B2, respectively. There are eight orders of activation that satisfy the condition, as follows: - A1, B1, A2, B2 - A1, B1, B2, A2 - A1, B2, B1, A2 - A2, B1, A1, B2 - B1, A1, B2, A2 - B1, A1, A2, B2 - B1, A2, A1, B2 - B2, A1, B1, A2 Thus, the output should be 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. There are N robots and M exits on a number line. The N + M coordinates of these are all integers and all distinct. For each i (1 \leq i \leq N), the coordinate of the i-th robot from the left is x_i. Also, for each j (1 \leq j \leq M), the coordinate of the j-th exit from the left is y_j. Snuke can repeatedly perform the following two kinds of operations in any order to move all the robots simultaneously: - Increment the coordinates of all the robots on the number line by 1. - Decrement the coordinates of all the robots on the number line by 1. Each robot will disappear from the number line when its position coincides with that of an exit, going through that exit. Snuke will continue performing operations until all the robots disappear. When all the robots disappear, how many combinations of exits can be used by the robots? Find the count modulo 10^9 + 7. Here, two combinations of exits are considered different when there is a robot that used different exits in those two combinations. -----Constraints----- - 1 \leq N, M \leq 10^5 - 1 \leq x_1 < x_2 < ... < x_N \leq 10^9 - 1 \leq y_1 < y_2 < ... < y_M \leq 10^9 - All given coordinates are integers. - All given coordinates are distinct. -----Input----- Input is given from Standard Input in the following format: N M x_1 x_2 ... x_N y_1 y_2 ... y_M -----Output----- Print the number of the combinations of exits that can be used by the robots when all the robots disappear, modulo 10^9 + 7. -----Sample Input----- 2 2 2 3 1 4 -----Sample Output----- 3 The i-th robot from the left will be called Robot i, and the j-th exit from the left will be called Exit j. There are three possible combinations of exits (the exit used by Robot 1, the exit used by Robot 2) as follows: - (Exit 1, Exit 1) - (Exit 1, Exit 2) - (Exit 2, Exit 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. AtCoDeer the deer found N rectangle lying on the table, each with height 1. If we consider the surface of the desk as a two-dimensional plane, the i-th rectangle i(1≤i≤N) covers the vertical range of [i-1,i] and the horizontal range of [l_i,r_i], as shown in the following figure: AtCoDeer will move these rectangles horizontally so that all the rectangles are connected. For each rectangle, the cost to move it horizontally by a distance of x, is x. Find the minimum cost to achieve connectivity. It can be proved that this value is always an integer under the constraints of the problem. -----Constraints----- - All input values are integers. - 1≤N≤10^5 - 1≤l_i<r_i≤10^9 -----Partial Score----- - 300 points will be awarded for passing the test set satisfying 1≤N≤400 and 1≤l_i<r_i≤400. -----Input----- The input is given from Standard Input in the following format: N l_1 r_1 l_2 r_2 : l_N r_N -----Output----- Print the minimum cost to achieve connectivity. -----Sample Input----- 3 1 3 5 7 1 3 -----Sample Output----- 2 The second rectangle should be moved to the left by a distance of 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. In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks. More precisely, two different numbers $a$ and $b$ are friends if $gcd(a,b)$, $\frac{a}{gcd(a,b)}$, $\frac{b}{gcd(a,b)}$ can form sides of a triangle. Three numbers $a$, $b$ and $c$ can form sides of a triangle if $a + b > c$, $b + c > a$ and $c + a > b$. In a group of numbers, a number is lonely if it doesn't have any friends in that group. Given a group of numbers containing all numbers from $1, 2, 3, ..., n$, how many numbers in that group are lonely? -----Input----- The first line contains a single integer $t$ $(1 \leq t \leq 10^6)$ - number of test cases. On next line there are $t$ numbers, $n_i$ $(1 \leq n_i \leq 10^6)$ - meaning that in case $i$ you should solve for numbers $1, 2, 3, ..., n_i$. -----Output----- For each test case, print the answer on separate lines: number of lonely numbers in group $1, 2, 3, ..., n_i$. -----Example----- Input 3 1 5 10 Output 1 3 3 -----Note----- For first test case, $1$ is the only number and therefore lonely. For second test case where $n=5$, numbers $1$, $3$ and $5$ are lonely. For third test case where $n=10$, numbers $1$, $5$ and $7$ are lonely. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>] where: <protocol> can equal either "http" (without the quotes) or "ftp" (without the quotes), <domain> is a non-empty string, consisting of lowercase English letters, the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters. If string <context> isn't present in the address, then the additional character "/" isn't written. Thus, the address has either two characters "/" (the ones that go before the domain), or three (an extra one in front of the context). When the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters ":", "/", ".". Help Vasya to restore the possible address of the recorded Internet resource. -----Input----- The first line contains a non-empty string that Vasya wrote out in his notebook. This line consists of lowercase English letters only. It is guaranteed that the given string contains at most 50 letters. It is guaranteed that the given string can be obtained from some correct Internet resource address, described above. -----Output----- Print a single line — the address of the Internet resource that Vasya liked. If there are several addresses that meet the problem limitations, you are allowed to print any of them. -----Examples----- Input httpsunrux Output http://sun.ru/x Input ftphttprururu Output ftp://http.ru/ruru -----Note----- In the second sample there are two more possible answers: "ftp://httpruru.ru" and "ftp://httpru.ru/ru". Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
Solve the programming task below in a Python markdown code block. You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x_1, x_2, ..., x_{k}} (1 ≤ x_{i} ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. $\sum_{i = 1}^{k} a_{x_{i}} \neq \sum_{i = 1}^{k} b_{x_{i}}$ -----Input----- The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — the elements of the array. -----Output----- If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b_1, b_2, ..., b_{n}. Note that b must be a permutation of a. If there are multiple answers, print any of them. -----Examples----- Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 -----Note----- An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.