name
stringlengths
9
61
tags
sequencelengths
1
11
rating
int64
800
3.5k
description
stringlengths
145
7.05k
editorial
stringlengths
28
7.79k
1000_A. Codehorses T-shirts
[ "greedy", "implementation" ]
1,200
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners. The valid sizes of T-shirts are either "M" or from 0 to 3 "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not. There are n winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words. What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one? The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists. Input The first line contains one integer n (1 ≤ n ≤ 100) — the number of T-shirts. The i-th of the next n lines contains a_i — the size of the i-th T-shirt of the list for the previous year. The i-th of the next n lines contains b_i — the size of the i-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list b from the list a. Output Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0. Examples Input 3 XS XS M XL S XS Output 2 Input 2 XXXL XXL XXL XXXS Output 1 Input 2 M XS XS M Output 0 Note In the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L". In the second example Ksenia should replace "L" in "XXXL" with "S". In the third example lists are equal.
First, let us remove all coinciding entries of both lists. The most convenient way to do this is to use a `map` or `hashmap`, but it is not the only option. Now divide the entries into categories based on their length. You will notice that it takes exactly one second to remove an entry in each category (to make it equal to an entry of the opposing list). Thus, the answer is $n - (\text{number of coinciding entries})$. Overall complexity: $O(n \log n)$ or $O(n)$.
1000_B. Light It Up
[ "greedy" ]
1,500
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment 0 and turn power off at moment M. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp. The lamp allows only good programs. Good program can be represented as a non-empty array a, where 0 < a_1 < a_2 < ... < a_{|a|} < M. All a_i must be integers. Of course, preinstalled program is a good program. The lamp follows program a in next manner: at moment 0 turns power and light on. Then at moment a_i the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment 1 and then do nothing, the total time when the lamp is lit will be 1. Finally, at moment M the lamp is turning its power off regardless of its state. Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program a, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of a, or even at the begining or at the end of a. Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from x till moment y, then its lit for y - x units of time. Segments of time when the lamp is lit are summed up. Input First line contains two space separated integers n and M (1 ≤ n ≤ 10^5, 2 ≤ M ≤ 10^9) — the length of program a and the moment when power turns off. Second line contains n space separated integers a_1, a_2, ..., a_n (0 < a_1 < a_2 < ... < a_n < M) — initially installed program a. Output Print the only integer — maximum possible total time when the lamp is lit. Examples Input 3 10 4 6 7 Output 8 Input 2 12 1 10 Output 9 Input 2 7 3 4 Output 6 Note In the first example, one of possible optimal solutions is to insert value x = 3 before a_1, so program will be [3, 4, 6, 7] and time of lamp being lit equals (3 - 0) + (6 - 4) + (10 - 7) = 8. Other possible solution is to insert x = 5 in appropriate place. In the second example, there is only one optimal solution: to insert x = 2 between a_1 and a_2. Program will become [1, 2, 10], and answer will be (1 - 0) + (10 - 2) = 9. In the third example, optimal answer is to leave program untouched, so answer will be (3 - 0) + (7 - 4) = 6.
First, let's insert $0$ and $M$ into array $a$, so all possible positions for inserting will always belong to $(a_i, a_{i + 1})$. Second, let $x$ be the value to insert and $a_i < x < a_{i + 1}$. It can be proven that it is always optimal to move $x$ to $a_i$ or to $a_{i + 1}$. So, for each $(a_i, a_{i + 1})$ we need to check only $x = a_i + 1$ and $x = a_{i + 1} - 1$. To check this fast enough, we need to know the total time the lamp is lit for each prefix and precalculate for each $i$, the total time the lamp is lit if starting from $a_i$ the light is on or off. The resulting complexity is $O(n)$.
1000_C. Covered Points Count
[ "data structures", "implementation", "sortings" ]
1,700
You are given n segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. Your task is the following: for every k ∈ [1..n], calculate the number of points with integer coordinates such that the number of segments that cover these points equals k. A segment with endpoints l_i and r_i covers point x if and only if l_i ≤ x ≤ r_i. Input The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of segments. The next n lines contain segments. The i-th line contains a pair of integers l_i, r_i (0 ≤ l_i ≤ r_i ≤ 10^{18}) — the endpoints of the i-th segment. Output Print n space separated integers cnt_1, cnt_2, ..., cnt_n, where cnt_i is equal to the number of points such that the number of segments that cover these points equals to i. Examples Input 3 0 3 1 3 3 8 Output 6 2 1 Input 3 1 3 2 4 5 7 Output 5 2 0 Note The picture describing the first example: <image> Points with coordinates [0, 4, 5, 6, 7, 8] are covered by one segment, points [1, 2] are covered by two segments and point [3] is covered by three segments. The picture describing the second example: <image> Points [1, 4, 5, 6, 7] are covered by one segment, points [2, 3] are covered by two segments and there are no points covered by three segments.
This problem with small coordinates can be solved using partial sums and some simple counting. Let us maintain an array $cnt$, where $cnt_i$ will be equal to the number of segments that cover the point with coordinate $i$. How can we calculate $cnt$ in $O(n + maxX)$ time? For each segment $(l_i, r_i)$, let us add $+1$ to $cnt_{l_i}$ and $-1$ to $cnt_{r_i + 1}$. Now, we can build prefix sums on this array and observe that $cnt_i$ equals the number of segments that cover the point with coordinate $i$. Then, $ans_i$ will be equal to $\sum_{j = 0}^{maxX} cnt_j = i$. All the answers can be calculated in $O(maxX)$ time in total. Therefore, the total complexity of this solution is $O(n + maxX)$. However, in our problem, it is too slow to build the entire array $cnt$. So, what should we do? It is obvious that if any coordinate $j$ is not equal to some $l_i$ or some $r_i + 1$, then $cnt_i = cnt_{i - 1}$. Therefore, we do not need to explicitly maintain all the positions. Let us maintain all $l_i$ and $r_i + 1$ in some logarithmic data structure or let us use the coordinate compression method. The coordinate compression method allows us to transform the set of big sparse objects to the set of small compressed objects while maintaining the relative order. In our problem, let us do the following: push all $l_i$ and $r_i + 1$ into vector $cval$, sort this vector, keep only unique values, and then use the position of elements in vector $cval$ instead of the original value (any position can be found in $O(\log n)$ time using binary search or standard methods such as `lower_bound` in C++). Therefore, the first part of the solution works in $O(n \log n)$ time. The answer can be calculated using almost the same approach as in the solution to this problem with small coordinates. However, now we know that between two adjacent elements $cval_i$ and $cval_{i + 1}$, there are exactly $cval_{i + 1} - cval_{i}$ points with answer equal to $cnt_i$. Therefore, if we iterate over all pairs of the adjacent elements $cval_i$ and $cval_{i + 1}$ and add $cval_{i + 1} - cval_i$ to the $ans_{cnt_i}$, we will calculate all the answers in $O(n)$ time. Therefore, the total complexity of the solution is $O(n \log n)$.
1000_D. Yet Another Problem On a Subsequence
[ "combinatorics", "dp" ]
1,900
The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] — are not. A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] — are not. For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353. Input The first line contains the number n~(1 ≤ n ≤ 10^3) — the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 ≤ a_i ≤ 10^9) — the sequence itself. Output In the single line output one integer — the number of subsequences of the original sequence that are good sequences, taken modulo 998244353. Examples Input 3 2 1 1 Output 2 Input 4 1 1 1 1 Output 7 Note In the first test case, two good subsequences — [a_1, a_2, a_3] and [a_2, a_3]. In the second test case, seven good subsequences — [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4].
The problem is solved using dynamic programming. Let $dp_i$ be the answer for the prefix of the array starting at $i$ (it contains the indices $i, i + 1, ..., n$). If $a_i \le 0$, then $dp_i = 0$. Otherwise, let's iterate over the positions $j$, with which the next good array begins. Then we need to select $a_i$ positions among $j-i-1$ positions, which will be elements of the array. The number of ways to choose an unordered set of $k$ items from $n$ of different objects is calculated using the formula $C_n^k = \dfrac{n!}{k!(n - k)!}$. Thus, the dynamics is as follows: $dp_i = \sum_{j = i + a_i + 1}^{n + 1} {C_{j - i - 1}^{a_i} \times dp_j}$. The base of dynamics is the value $dp_{n + 1} = 1$.
1000_E. We Need More Bosses
[ "dfs and similar", "graphs", "trees" ]
2,100
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location. Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses. The game will start in location s and end in location t, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from s to t without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as s or as t. Input The first line contains two integers n and m (2 ≤ n ≤ 3 ⋅ 10^5, n - 1 ≤ m ≤ 3 ⋅ 10^5) — the number of locations and passages, respectively. Then m lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) describing the endpoints of one of the passages. It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location. Output Print one integer — the maximum number of bosses your friend can place, considering all possible choices for s and t. Examples Input 5 5 1 2 2 3 3 1 4 1 5 2 Output 2 Input 4 3 1 2 4 3 3 2 Output 3
It is quite obvious that we can place bosses only on the bridges of the given graph. If an edge is not a bridge, then removing it does not make the graph disconnected, so there still exists a path between any pair of vertices. And if we fix two vertices $s$ and $t$, and then find some simple path between them, then we will place the bosses on all bridges belonging to this path (since the set of bridges would stay the same no matter which simple path between $s$ and $t$ we choose). If we find bridges in the given graph and compress all 2-edge-connected components (two vertices belong to the same 2-edge-connected component if and only if there exists a path between these vertices such that there are no bridges on this path) into single vertices, we will obtain a special tree called bridge tree. Every edge of a bridge tree corresponds to a bridge in the original graph (and vice versa). Since we want to find the path with maximum possible number of bridges, we only need to find the diameter of the bridge tree, and this will be the answer to the problem.
1000_F. One Occurrence
[ "data structures", "divide and conquer" ]
2,400
You are given an array a consisting of n integers, and q queries to it. i-th query is denoted by two integers l_i and r_i. For each query, you have to find any integer that occurs exactly once in the subarray of a from index l_i to index r_i (a subarray is a contiguous subsegment of an array). For example, if a = [1, 1, 2, 3, 2, 4], then for query (l_i = 2, r_i = 6) the subarray we are interested in is [1, 2, 3, 2, 4], and possible answers are 1, 3 and 4; for query (l_i = 1, r_i = 2) the subarray we are interested in is [1, 1], and there is no such element that occurs exactly once. Can you answer all of the queries? Input The first line contains one integer n (1 ≤ n ≤ 5 ⋅ 10^5). The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 5 ⋅ 10^5). The third line contains one integer q (1 ≤ q ≤ 5 ⋅ 10^5). Then q lines follow, i-th line containing two integers l_i and r_i representing i-th query (1 ≤ l_i ≤ r_i ≤ n). Output Answer the queries as follows: If there is no integer such that it occurs in the subarray from index l_i to index r_i exactly once, print 0. Otherwise print any such integer. Example Input 6 1 1 2 3 2 4 2 2 6 1 2 Output 4 0
Suppose that all queries have the same right border $r$. Then, the answer to the query can be some integer $i$ such that the last occurrence of $i$ in the prefix $[1, r]$ of the array is inside the segment, but the second-to-last occurrence is outside the segment (or even does not exist). More formally, let $f(i)$ be the maximum index $j$ such that $j < i$ and $a_j = a_i$ (or $-1$ if there is no such $j$); the answer to the query is some number $a_k$ such that $l \le k \le r$ and $f(k) < l$ (and $k$ is the rightmost occurrence of $a_k$ in the segment $[1, r]$). For a fixed right border $r$, we can build a segment tree which, for every index $x$ such that $x$ is the rightmost occurrence of $a_x$ on $[1, r]$, stores the value of $f(x)$; and if we query the minimum on the segment $[l, r]$ in such tree, we can try to find the answer. Let the position of the minimum be $m$. If $f(m) < l$, then $a_m$ can be the answer; otherwise, there is no answer. However, this is too slow since we cannot afford to build a segment tree for every possible value of $r$. There are two methods to deal with this problem: we can sort all queries by their right borders and maintain the segment tree while shifting the right border (when going from $r$ to $r + 1$, we have to update the values in the positions $f(r + 1)$ and $r + 1$), or we can use a persistent segment tree and get an online solution. We tried to eliminate solutions using Mo's algorithm, but in fact, it is possible to squeeze some implementations of it into TL. There are two optimizations that might help there. When dividing the elements into blocks, we may sort the first block in the ascending order of right borders, the second block in descending order, the third block in ascending order again, and so on. Additionally, it is possible to obtain a Mo-based solution with worst-case complexity of $O((n + q) \sqrt{n})$ if we maintain the set of possible answers using sqrt decomposition on it.
1000_G. Two-Paths
[ "data structures", "dp", "trees" ]
2,700
You are given a weighted tree (undirected connected graph with no cycles, loops or multiple edges) with n vertices. The edge \\{u_j, v_j\} has weight w_j. Also each vertex i has its own value a_i assigned to it. Let's call a path starting in vertex u and ending in vertex v, where each edge can appear no more than twice (regardless of direction), a 2-path. Vertices can appear in the 2-path multiple times (even start and end vertices). For some 2-path p profit Pr(p) = ∑_{v ∈ distinct vertices in p}{a_v} - ∑_{e ∈ distinct edges in p}{k_e ⋅ w_e}, where k_e is the number of times edge e appears in p. That is, vertices are counted once, but edges are counted the number of times they appear in p. You are about to answer m queries. Each query is a pair of vertices (qu, qv). For each query find 2-path p from qu to qv with maximal profit Pr(p). Input The first line contains two integers n and q (2 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ q ≤ 4 ⋅ 10^5) — the number of vertices in the tree and the number of queries. The second line contains n space-separated integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the values of the vertices. Next n - 1 lines contain descriptions of edges: each line contains three space separated integers u_i, v_i and w_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i, 1 ≤ w_i ≤ 10^9) — there is edge \\{u_i, v_i\} with weight w_i in the tree. Next q lines contain queries (one per line). Each query contains two integers qu_i and qv_i (1 ≤ qu_i, qv_i ≤ n) — endpoints of the 2-path you need to find. Output For each query print one integer per line — maximal profit Pr(p) of the some 2-path p with the corresponding endpoints. Example Input 7 6 6 5 5 3 2 1 2 1 2 2 2 3 2 2 4 1 4 5 1 6 4 2 7 3 25 1 1 4 4 5 6 6 4 3 4 3 7 Output 9 9 9 8 12 -14 Note Explanation of queries: 1. (1, 1) — one of the optimal 2-paths is the following: 1 → 2 → 4 → 5 → 4 → 2 → 3 → 2 → 1. Pr(p) = (a_1 + a_2 + a_3 + a_4 + a_5) - (2 ⋅ w(1,2) + 2 ⋅ w(2,3) + 2 ⋅ w(2,4) + 2 ⋅ w(4,5)) = 21 - 2 ⋅ 12 = 9. 2. (4, 4): 4 → 2 → 1 → 2 → 3 → 2 → 4. Pr(p) = (a_1 + a_2 + a_3 + a_4) - 2 ⋅ (w(1,2) + w(2,3) + w(2,4)) = 19 - 2 ⋅ 10 = 9. 3. (5, 6): 5 → 4 → 2 → 3 → 2 → 1 → 2 → 4 → 6. 4. (6, 4): 6 → 4 → 2 → 1 → 2 → 3 → 2 → 4. 5. (3, 4): 3 → 2 → 1 → 2 → 4. 6. (3, 7): 3 → 2 → 1 → 2 → 4 → 5 → 4 → 2 → 3 → 7.
Let us solve this task in several steps. Step 1. Calculate $dp_i$ for each vertex. Let $dp_i$ be the maximum profit of some 2-path starting at $i$ and finishing at $i$. If vertex $i$ is a root of the tree, then $dp_i$ is equivalent to $d'_i$, where $d'_i$ is the maximum profit of a 2-path $(i, i)$, when we can only go in the subtree of $i$. The $d'_i$ can be calculated with the following approach: $d'_v = a_v + \sum_{to \in \text{Children}(v)}{\max(0, d'_{to} - 2 \times w(v, to))}$. To calculate $dp_i$, we can use the following technique. Let us maintain the following invariant: when processing vertex $v$, all of its neighbors (even its parent) will hold $d'_i$ as if $v$ were its parent. Then $dp_v = a_v + \sum_{to \in Neighbours(v)}{\max(0, d'_{to} - 2 \times w(v, to))}$. After that, we can process each child $to$ of $v$, but before moving to it, we must change the value of $d'_v$ since we must keep the invariant true. To keep it true, it is enough to set $d'_v = dp_v - \max(0, d'_{to} - 2 \times w(v, to))$. Also, let us memorize the value $\max(0, d'_{to} - 2 \times w(v, to))$ as $dto(v, to)$. Step 2. Processing queries. Let simple path $(qu, qv)$ be $qu \to p_1 \to p_2 \to ... \to p_k \to qv$. If $qu = qv$, then the answer is $dp_{qu}$. Otherwise, each edge on this simple path must be used exactly once. But, while traveling from $qu$ to $qv$ using this simple path, at each vertex $v$, we can go somewhere and return to $v$-the only condition is not to use edges from the simple path. And we can do it using the precalculated values $dp_i$ and $dto(v, to)$. So, if we want to find the maximum profit of a 2-path $(v, v)$ with prohibited edges $(v, to_1)$ and $(v, to_2)$, then we can use the value $dp_v - dto(v, to_1) - dto(v, to_2)$. Finally, to process queries, let us find $l = lca(qu, qv)$, divide it into two queries $(qu, l)$ and $(qv, l)$. Now we can handle all queries offline, traveling on the tree in dfs order. Let us maintain some data structure on the current path from the current vertex to the root (this data structure can be based on an array of depths). Then, when we come to vertex $v$, just add the value $dp_v - dto(v, \text{parent}(v))$ to the data structure in position $\text{depth}(v)$ (and erase it before exiting). Each query $(v, l)$ becomes a query of sum to some subsegment in the data structure (do not forget to carefully handle the value in the lca). And, before moving from $v$ to $to$, you need to subtract $dto(v, to)$ from the current value of $v$ (here you can also subtract the weight of the edge $(v, to)$). Do not forget to return each change in the data structure when it is needed. As we can see, the data structure is just a BIT with sum on a segment and change in position. The resulting complexity is $O((n + m) \log{n})$. Fast IO are welcome.
1003_A. Polycarp's Pockets
[ "implementation" ]
800
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two pockets as follows: [1, 2, 3], [2, 3, 4]. Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of coins. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — values of coins. Output Print only one integer — the minimum number of pockets Polycarp needs to distribute all the coins so no two coins with the same value are put into the same pocket. Examples Input 6 1 2 4 3 3 2 Output 2 Input 1 100 Output 1
We need to find the maximum number of elements with the same value (this can be done by counting). This number will be the answer because if there are no more than $k$ elements with the same value in the array, it is obvious that we cannot use less than $k$ pockets, but we also do not need to use more than $k$ pockets because the other values can also be distributed using $k$ pockets. The overall complexity is $O(n + maxAi)$.
1003_B. Binary String Constructing
[ "constructive algorithms" ]
1,300
You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≤ i < n) such that s_i ≠ s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≤ i < n and s_i ≠ s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≤ a, b ≤ 100, 1 ≤ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011.
This problem has several general cases: - If $x$ is even and $a > b$, then the answer is `01` repeated $\dfrac{x}{2}$ times, followed by $b - \dfrac{x}{2}$ ones and $a - \dfrac{x}{2}$ zeroes; - If $x$ is even and $a \le b$, then the answer is `10` repeated $\dfrac{x}{2}$ times, followed by $a - \dfrac{x}{2}$ zeroes and $b - \dfrac{x}{2}$ ones; - If $x$ is odd and $a > b$, then the answer is `01` repeated $\lfloor\dfrac{x}{2}\rfloor$ times, followed by $a - \lfloor\dfrac{x}{2}\rfloor$ zeroes and $b - \lfloor\dfrac{x}{2}\rfloor$ ones; - If $x$ is odd and $a \le b$, then the answer is `10` repeated $\lfloor\dfrac{x}{2}\rfloor$ times, followed by $b - \lfloor\dfrac{x}{2}\rfloor$ ones and $a - \lfloor\dfrac{x}{2}\rfloor$ zeroes. I am sure that there are other more elegant solutions, but for me the easiest way to solve this problem is to extract general cases and handle them. Overall complexity is $O(a + b)$.
1003_C. Intense Heat
[ "brute force", "implementation", "math" ]
1,300
The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are. Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows: Suppose we want to analyze the segment of n consecutive days. We have measured the temperatures during these n days; the temperature during i-th day equals a_i. We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day x to day y, we calculate it as \frac{∑ _{i = x}^{y} a_i}{y - x + 1} (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than k consecutive days. For example, if analyzing the measures [3, 4, 1, 2] and k = 3, we are interested in segments [3, 4, 1], [4, 1, 2] and [3, 4, 1, 2] (we want to find the maximum value of average temperature over these segments). You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task? Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of days in the given period, and the minimum number of days in a segment we consider when calculating heat intensity value, respectively. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 5000) — the temperature measures during given n days. Output Print one real number — the heat intensity value, i. e., the maximum of average temperatures over all segments of not less than k consecutive days. Your answer will be considered correct if the following condition holds: |res - res_0| < 10^{-6}, where res is your answer, and res_0 is the answer given by the jury's solution. Example Input 4 3 3 4 1 2 Output 2.666666666666667
This task is a straightforward implementation problem. We can iterate over all segments of the given array, calculate their sum, and if the length of the current segment is not less than $k$, try to update the answer with the mean of this segment. The overall complexity is $O(n^2)$.
1003_D. Coins and Queries
[ "greedy" ]
1,600
Polycarp has n coins, the value of the i-th coin is a_i. It is guaranteed that all the values are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d). Polycarp wants to know answers on q queries. The j-th query is described as integer number b_j. The answer to the query is the minimum number of coins that is necessary to obtain the value b_j using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value b_j, the answer to the j-th query is -1. The queries are independent (the answer on the query doesn't affect Polycarp's coins). Input The first line of the input contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of coins and the number of queries. The second line of the input contains n integers a_1, a_2, ..., a_n — values of coins (1 ≤ a_i ≤ 2 ⋅ 10^9). It is guaranteed that all a_i are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d). The next q lines contain one integer each. The j-th line contains one integer b_j — the value of the j-th query (1 ≤ b_j ≤ 10^9). Output Print q integers ans_j. The j-th integer must be equal to the answer on the j-th query. If Polycarp can't obtain the value b_j the answer to the j-th query is -1. Example Input 5 4 2 4 8 2 4 8 5 14 10 Output 1 -1 3 2
We can solve the problem in the following way: First, for each power of $2$, let's calculate the number of coins with the value equal to this degree. Let's call this $cnt$. It is obvious that we can obtain the value $b_j$ greedily (because all smaller values of coins are divisors of all greater values of coins). Now, let's iterate over all powers of $2$ from $30$ to $0$. Let $deg$ be the current degree. We can take $min(\lfloor\dfrac{b_j}{2^{deg}}\rfloor, cnt_{deg})$ coins with the value equal to $2^{deg}$. Let this be $cur$. Add $cur$ to the answer and subtract $2^{deg} \times cur$ from $b_j$. If, after iterating over all powers, $b_j$ is still non-zero, print `-1`. Otherwise, print the answer. Overall complexity: $O((n + q) \log maxAi)$.
1003_E. Tree Constructing
[ "constructive algorithms", "graphs" ]
2,100
You are given three integers n, d and k. Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible. An undirected tree is a connected undirected graph with n - 1 edges. Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree. Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree). Input The first line of the input contains three integers n, d and k (1 ≤ n, d, k ≤ 4 ⋅ 10^5). Output If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1 Examples Input 6 3 3 Output YES 3 1 4 1 1 2 5 2 2 6 Input 6 2 3 Output NO Input 10 4 3 Output YES 2 9 2 10 10 3 3 1 6 10 8 2 4 3 5 6 6 7 Input 8 5 3 Output YES 2 5 7 2 3 7 3 1 1 6 8 7 4 3
We construct a tree using the following algorithm: if $d \ge n$, we print `NO` and terminate the program. Otherwise, we maintain an array $deg$ of length $n$ that will represent the degrees of the vertices. The first step is to construct the diameter of the tree. We let the first $d + 1$ vertices form the diameter. We add $d$ edges to the answer, increase the degrees of the vertices corresponding to these edges, and if any vertex has degree greater than $k$, we print `NO` and terminate the program. The second (and final) step is to attach the remaining $n - d - 1$ vertices to the tree. We call a vertex `free` if its degree is less than $k$. We also maintain all `free` vertices forming the diameter in a data structure that allows us to take the vertex with the minimum maximal distance to any other vertex and remove such vertices. This can be done using, for example, a set of pairs ($dist_v, v$), where $dist_v$ is the maximum distance from the vertex $v$ to any other vertex. Now, we add all vertices from starting from the vertex $d + 1$ (0-indexed) to the vertex $n - 1$, let the current vertex be $u$. We find the vertex with the minimum maximal distance to any other vertex, let it be $v$. We then increase the degrees of vertices $u$ and $v$, add the edge between them, and if $v$ is still `free`, we return it to the data structure, otherwise we remove it. We do the same with the vertex $u$ (it is obvious that its maximal distance to any other vertex will be equal to $dist_v + 1$). If at any step, our data structure is empty or the minimum maximal distance is equal to $d$, the answer is `NO`. Otherwise, we can print the answer. Overall complexity: $O(n \log n)$ or $O(n)$ (depending on implementation).
1003_F. Abbreviation
[ "dp", "hashing", "strings" ]
2,200
You are given a text consisting of n space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. w_i is the i-th word of text. All words consist only of lowercase Latin letters. Let's denote a segment of words w[i..j] as a sequence of words w_i, w_{i + 1}, ..., w_j. Two segments of words w[i_1 .. j_1] and w[i_2 .. j_2] are considered equal if j_1 - i_1 = j_2 - i_2, j_1 ≥ i_1, j_2 ≥ i_2, and for every t ∈ [0, j_1 - i_1] w_{i_1 + t} = w_{i_2 + t}. For example, for the text "to be or not to be" the segments w[1..2] and w[5..6] are equal, they correspond to the words "to be". An abbreviation is a replacement of some segments of words with their first uppercase letters. In order to perform an abbreviation, you have to choose at least two non-intersecting equal segments of words, and replace each chosen segment with the string consisting of first letters of the words in the segment (written in uppercase). For example, for the text "a ab a a b ab a a b c" you can replace segments of words w[2..4] and w[6..8] with an abbreviation "AAA" and obtain the text "a AAA b AAA b c", or you can replace segments of words w[2..5] and w[6..9] with an abbreviation "AAAB" and obtain the text "a AAAB AAAB c". What is the minimum length of the text after at most one abbreviation? Input The first line of the input contains one integer n (1 ≤ n ≤ 300) — the number of words in the text. The next line contains n space-separated words of the text w_1, w_2, ..., w_n. Each word consists only of lowercase Latin letters. It is guaranteed that the length of text does not exceed 10^5. Output Print one integer — the minimum length of the text after at most one abbreviation. Examples Input 6 to be or not to be Output 12 Input 10 a ab a a b ab a a b c Output 13 Input 6 aa bb aa aa bb bb Output 11 Note In the first example you can obtain the text "TB or not TB". In the second example you can obtain the text "a AAAB AAAB c". In the third example you can obtain the text "AB aa AB bb".
Let $eq_{i, j}$ be true if words $s_i$ and $s_j$ are equal, otherwise it is false. We can iterate over all pairs of words and compare them using a standard string comparator (the constraints are very small, so we can do this naively). The next step is to calculate the dynamic programming $dp_{i, j}$, which is equal to the maximum length of coinciding segments of words that start in positions $i$ and $j$, respectively. In other words, if $dp_{i, j}$ is equal to $k$, then $s[i..i+k-1] = s[j..j+k-1]$, word by word. We can calculate this dynamic programming in reverse order ($i := n - 1 .. 0, j := n - 1 .. 0$) and $dp_{i, j} := 0$ if $s_i \ne s_j$, otherwise if $i < n - 1$ and $j < n - 1$, then $dp_{i, j} := dp_{i + 1, j + 1} + 1$, otherwise $dp_{i, j} := 1$. Let's store the length of the text in the variable $allsum$. Then iterate over all starting positions of the possible abbreviation and all its possible lengths. Let the current starting position be equal to $i$ (0-indexed) and its length be equal to $j$. Then we need to calculate the number of possible replacements by its abbreviation. Let it be $cnt$ and now it equals $1$. Let's iterate over all positions $pos$, at the beginning $pos = i + j$ (0-indexed). If $dp_{i, pos} \ge j$ then we can replace the segment of words that starts at the position $pos$ with its abbreviation, so $cnt := cnt + 1$ and $pos := pos + j$ (because we cannot replace intersecting segments), otherwise $pos := pos + 1$. After this we need to update the answer. The length of the segment of words $s[i..j]$ can be calculated easily, let it be $seglen$. Also let $segcnt$ be the number of words in the current segment of words. Then we can update the answer with the value $allsum - seglen \times cnt + cnt \times segcnt$. The overall complexity is $O(n^3 + n \times \sum_{i = 0}^{n - 1}|s_i|)$, where $|s_i|$ is the length of the $i$-th word.
1004_A. Sonya and Hotels
[ "implementation" ]
900
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants. The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate x_i. Sonya is a smart girl, so she does not open two or more hotels in the same city. Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to d. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original n hotels to the new one is equal to d. Input The first line contains two integers n and d (1≤ n≤ 100, 1≤ d≤ 10^9) — the number of Sonya's hotels and the needed minimum distance from a new hotel to all others. The second line contains n different integers in strictly increasing order x_1, x_2, …, x_n (-10^9≤ x_i≤ 10^9) — coordinates of Sonya's hotels. Output Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to d. Examples Input 4 3 -3 2 9 16 Output 6 Input 5 2 4 8 11 18 19 Output 5 Note In the first example, there are 6 possible cities where Sonya can build a hotel. These cities have coordinates -6, 5, 6, 12, 13, and 19. In the second example, there are 5 possible cities where Sonya can build a hotel. These cities have coordinates 2, 6, 13, 16, and 21.
A hotel can always be built to the left of the first hotel. Another can be built to the right of the last hotel. Consider each pair of adjacent hotels. If the distance between these two hotels is greater than $2 \times d$, we can build one hotel at a distance of $d$ to the right of the left hotel and another at a distance of $d$ to the left of the right hotel. If the distance between these two hotels is equal to $2 \times d$, we can build only one hotel in the middle of them. Otherwise, we cannot build a hotel between them.
1004_B. Sonya and Exhibition
[ "constructive algorithms", "greedy", "implementation", "math" ]
1,300
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition. There are n flowers in a row in the exhibition. Sonya can put either a rose or a lily in the i-th position. Thus each of n positions should contain exactly one flower: a rose or a lily. She knows that exactly m people will visit this exhibition. The i-th visitor will visit all flowers from l_i to r_i inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies. Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible. Input The first line contains two integers n and m (1≤ n, m≤ 10^3) — the number of flowers and visitors respectively. Each of the next m lines contains two integers l_i and r_i (1≤ l_i≤ r_i≤ n), meaning that i-th visitor will visit all flowers from l_i to r_i inclusive. Output Print the string of n characters. The i-th symbol should be «0» if you want to put a rose in the i-th position, otherwise «1» if you want to put a lily. If there are multiple answers, print any. Examples Input 5 3 1 3 2 4 2 5 Output 01100 Input 6 3 5 6 1 4 4 6 Output 110010 Note In the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions; * in the segment [1…3], there are one rose and two lilies, so the beauty is equal to 1⋅ 2=2; * in the segment [2…4], there are one rose and two lilies, so the beauty is equal to 1⋅ 2=2; * in the segment [2…5], there are two roses and two lilies, so the beauty is equal to 2⋅ 2=4. The total beauty is equal to 2+2+4=8. In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions; * in the segment [5…6], there are one rose and one lily, so the beauty is equal to 1⋅ 1=1; * in the segment [1…4], there are two roses and two lilies, so the beauty is equal to 2⋅ 2=4; * in the segment [4…6], there are two roses and one lily, so the beauty is equal to 2⋅ 1=2. The total beauty is equal to 1+4+2=7.
Note that it is always optimal to use roses in even positions and lilies in odd positions. That is, the string $01010101010...$ is always optimal.
1004_C. Sonya and Robots
[ "constructive algorithms", "implementation" ]
1,400
Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers. Sonya has drawn n numbers in a row, a_i is located in the i-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will give a number to each robot (they can be either same or different) and run them. When a robot is running, it is moving toward to another robot, reading numbers in the row. When a robot is reading a number that is equal to the number that was given to that robot, it will turn off and stay in the same position. Sonya does not want robots to break, so she will give such numbers that robots will stop before they meet. That is, the girl wants them to stop at different positions so that the first robot is to the left of the second one. For example, if the numbers [1, 5, 4, 1, 3] are written, and Sonya gives the number 1 to the first robot and the number 4 to the second one, the first robot will stop in the 1-st position while the second one in the 3-rd position. In that case, robots will not meet each other. As a result, robots will not be broken. But if Sonya gives the number 4 to the first robot and the number 5 to the second one, they will meet since the first robot will stop in the 3-rd position while the second one is in the 2-nd position. Sonya understands that it does not make sense to give a number that is not written in the row because a robot will not find this number and will meet the other robot. Sonya is now interested in finding the number of different pairs that she can give to robots so that they will not meet. In other words, she wants to know the number of pairs (p, q), where she will give p to the first robot and q to the second one. Pairs (p_i, q_i) and (p_j, q_j) are different if p_i≠ p_j or q_i≠ q_j. Unfortunately, Sonya is busy fixing robots that broke after a failed launch. That is why she is asking you to find the number of pairs that she can give to robots so that they will not meet. Input The first line contains a single integer n (1≤ n≤ 10^5) — the number of numbers in a row. The second line contains n integers a_1, a_2, …, a_n (1≤ a_i≤ 10^5) — the numbers in a row. Output Print one number — the number of possible pairs that Sonya can give to robots so that they will not meet. Examples Input 5 1 5 4 1 3 Output 9 Input 7 1 2 1 1 1 3 2 Output 7 Note In the first example, Sonya can give pairs (1, 1), (1, 3), (1, 4), (1, 5), (4, 1), (4, 3), (5, 1), (5, 3), and (5, 4). In the second example, Sonya can give pairs (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), and (3, 2).
Suppose that our left robot is located in the $p$th position. The robot could be there only if the value that is written there did not occur earlier. The number of possible locations of the second robot is equal to the number of distinct numbers on the segment $[(p+1)... n]$. Let $dp_i$ be the number of different numbers on $[(p+1)... n]$. We can find these numbers from right to left. If $a_i$ occurs for the first time, then $dp_i=dp_{i+1} + 1$; otherwise, $dp_i=dp_{i+1}$.
1004_D. Sonya and Matrix
[ "brute force", "constructive algorithms", "implementation" ]
2,300
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit. Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so. The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3. <image> Example of a rhombic matrix. Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero. She drew a n× m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of n⋅ m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal. Write a program that finds such an n× m rhombic matrix whose elements are the same as the elements in the sequence in some order. Input The first line contains a single integer t (1≤ t≤ 10^6) — the number of cells in the matrix. The second line contains t integers a_1, a_2, …, a_t (0≤ a_i< t) — the values in the cells in arbitrary order. Output In the first line, print two positive integers n and m (n × m = t) — the size of the matrix. In the second line, print two integers x and y (1≤ x≤ n, 1≤ y≤ m) — the row number and the column number where the cell with 0 is located. If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1. Examples Input 20 1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4 Output 4 5 2 2 Input 18 2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1 Output 3 6 2 3 Input 6 2 1 0 2 1 2 Output -1 Note You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5× 4 matrix with zero at (4, 2). In the second example, there is a 3× 6 matrix, where the zero is located at (2, 3) there. In the third example, a solution does not exist.
Suppose that a matrix has dimensions $n \times m$, and zero is located at $(x, y)$. Let $a$ be the distance to the cell $(1, 1)$, and let $b$ be the distance to the cell $(n, m)$. It is obvious that the farthest distance from the zero cell will be to a corner cell. The maximum number in the list is equal to the maximum distance to a corner cell (let's assume that it is $b$). We know that: $n \times m = t$; $a = x - 1 + y - 1$; $b = n - x + m - y$; $n + m = a + b + 2$. After some transformation, we get $a = n + m - b - 2$; $x - 1 + y - 1 = n + m - b - 2$; $y = n + m - b - x$. Let's find the minimum $i$ $(i > 0)$ such that the number of occurrences of $i$ in the list is not equal to $4 \times i$. We can notice that $x = i$. Let's look at each pair $(n, m)$ ($n \times m = t$), if we know $n$, $m$, $x$, and $b$, we can find $y$ and restore the matrix. If it could be done, we already found the answer.
1005_A. Tanya and Stairways
[ "implementation" ]
800
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps, she will pronounce the numbers 1, 2, 3, 1, 2, 3, 4. You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways. Input The first line contains n (1 ≤ n ≤ 1000) — the total number of numbers pronounced by Tanya. The second line contains integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1000) — all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with x steps, she will pronounce the numbers 1, 2, ..., x in that order. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways. Output In the first line, output t — the number of stairways that Tanya climbed. In the second line, output t numbers — the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways. Examples Input 7 1 2 3 1 2 3 4 Output 2 3 4 Input 4 1 1 1 1 Output 4 1 1 1 1 Input 5 1 2 3 4 5 Output 1 5 Input 5 1 2 1 2 1 Output 3 2 2 1
The answer contains elements $a_i$ such that $a_{i+1}=1$. Also add the last element $a_n$ to the answer.
1005_B. Delete from the Left
[ "brute force", "implementation", "strings" ]
900
You are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty. For example: * by applying a move to the string "where", the result is the string "here", * by applying a move to the string "a", the result is an empty string "". You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings. Write a program that finds the minimum number of moves to make two given strings s and t equal. Input The first line of the input contains s. In the second line of the input contains t. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and 2⋅10^5, inclusive. Output Output the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings. Examples Input test west Output 2 Input codeforces yes Output 9 Input test yes Output 7 Input b ab Output 1 Note In the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to "est". In the second example, the move should be applied to the string "codeforces" 8 times. As a result, the string becomes "codeforces" → "es". The move should be applied to the string "yes" once. The result is the same string "yes" → "es". In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty. In the fourth example, the first character of the second string should be deleted.
Let us find the value $w$, the length of the longest common suffix of $s$ and $t$. We can easily find it in one linear loop: simply compare the last letters of $s$ and $t$. If they are equal, then compare the letters before the last letters of $s$ and $t$. And so on. The last $w$ letters of $s$ and $t$ are two equal strings which will be the result of after optimal moves. So the answer is $|s| + |t| - 2 \times w$.
1005_C. Summarize to the Power of Two
[ "brute force", "greedy", "implementation" ]
1,300
A sequence a_1, a_2, ..., a_n is called good if, for each element a_i, there exists an element a_j (i ≠ j) such that a_i+a_j is a power of two (that is, 2^d for some non-negative integer d). For example, the following sequences are good: * [5, 3, 11] (for example, for a_1=5 we can choose a_2=3. Note that their sum is a power of two. Similarly, such an element can be found for a_2 and a_3), * [1, 1, 1, 1023], * [7, 39, 89, 25, 89], * []. Note that, by definition, an empty sequence (with a length of 0) is good. For example, the following sequences are not good: * [16] (for a_1=16, it is impossible to find another element a_j such that their sum is a power of two), * [4, 16] (for a_1=4, it is impossible to find another element a_j such that their sum is a power of two), * [1, 3, 2, 8, 8, 8] (for a_3=2, it is impossible to find another element a_j such that their sum is a power of two). You are given a sequence a_1, a_2, ..., a_n. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements. Input The first line contains the integer n (1 ≤ n ≤ 120000) — the length of the given sequence. The second line contains the sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9). Output Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all n elements, make it empty, and thus get a good sequence. Examples Input 6 4 7 1 5 4 9 Output 1 Input 5 1 2 3 4 5 Output 2 Input 1 16 Output 1 Input 4 1 1 1 1023 Output 0 Note In the first example, it is enough to delete one element a_4=5. The remaining elements form the sequence [4, 7, 1, 4, 9], which is good.
You should delete only those $a_i$ for which there is no such $a_j$ ($i \ne j$) that $a_i+a_j$ is a power of $2$. For each value, let's find the number of its occurrences. You can use a simple $map$ standard data structure. Do $c[a[i]] := c[a[i]]+1$ for each element $a[i]$. Now you can easily check that $a_i$ does not have a pair $a_j$. Let's iterate over all possible sums $s=2^0, 2^1, ..., 2^{30}$ and for each $s$ find calculate $s-a[i]$. If for some $s$: $c[s-a[i]] \ge 2$ or $c[s-a[i]] = 1$ and $s-a[i] \ne a[i]$ then a pair $a_j$ exists. Note that in C++ solutions, it is better to first check that $s-a[i]$ is a key in $c$, and only after that calculate $c[s - a[i]]$. This needs to be done, since in C++ when you access a key using the "square brackets" operator, a default mapping key-value is created on the absence of the key. This increases both the running time and the memory consumption.
1005_D. Polycarp and Div 3
[ "dp", "greedy", "number theory" ]
1,500
Polycarp likes numbers that are divisible by 3. He has a huge number s. Polycarp wants to cut from it the maximum number of numbers that are divisible by 3. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after m such cuts, there will be m+1 parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by 3. For example, if the original number is s=3121, then Polycarp can cut it into three parts with two cuts: 3|1|21. As a result, he will get two numbers that are divisible by 3. Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid. What is the maximum number of numbers divisible by 3 that Polycarp can obtain? Input The first line of the input contains a positive integer s. The number of digits of the number s is between 1 and 2⋅10^5, inclusive. The first (leftmost) digit is not equal to 0. Output Print the maximum number of numbers divisible by 3 that Polycarp can get by making vertical cuts in the given number s. Examples Input 3121 Output 2 Input 6 Output 1 Input 1000000000000000000000000000000000 Output 33 Input 201920181 Output 4 Note In the first example, an example set of optimal cuts on the number is 3|1|21. In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by 3. In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and 33 digits 0. Each of the 33 digits 0 forms a number that is divisible by 3. In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers 0, 9, 201 and 81 are divisible by 3.
There are multiple approaches to solve this problem. We will use a dynamic programming approach. Let's calculate the values of the array $z[0 ... n]$, where $z[i]$ is the answer for the prefix of length $i$. Clearly, $z[0] := 0$, since for the empty string (the prefix of length $0$) the answer is $0$. For $i > 0$, we can find $z[i]$ in the following way. Let's look at the last digit of the prefix of length $i$. It has index $i - 1$. Either it does not belong to a segment divisible by $3$, or it does. If it does not belong, it means we cannot use the last digit, so $z[i] = z[i - 1]$. If it belongs, we need to find the shortest $s[j ... i - 1]$ that is divisible by $3$ and try to update $z[i]$ with the value $z[j] + 1$. This means that we "bite off" the shortest divisible by $3$ suffix and reduce the problem to a previous one. A number is divisible by $3$ if and only if the sum of its digits is divisible by $3$. So the task is to find the shortest suffix of $s[0 ... i - 1]$ with sum of digits divisible by $3$. If such suffix is $s[j ... i - 1]$, then $s[0 ... j - 1]$ and $s[0 ... i - 1]$ have the same remainder of the sum of digits modulo $3$. Let's maintain $fin[0 ... 2]$, an array of length $3$, where $fin[r]$ is the length of the longest processed prefix with sum of digits equal to $r$ modulo $3$. Use $fin[r] = -1$ if there is no such prefix. It is easy to see that $j = fin[r]$, where $r$ is the sum of digits on the $i$-th prefix modulo $3$. So, to find the maximal $j \le i - 1$ such that the substring $s[j ... i - 1]$ is divisible by $3$, just check that $fin[r] \ne -1$ and use $j = fin[r]$, where $r$ is the sum of digits on the $i$-th prefix modulo $3$. This means that to handle the case that the last digit belongs to a divisible by $3$ segment, you should try to update $z[i]$ with the value $z[fin[r]] + 1$. In other words, just do `if (fin[r] != -1) z[i] = max(z[i], z[fin[r]] + 1)`. Sequentially calculating the values of $z[0 ... n]$, we obtain a linear $O(n)$ solution.
1005_E1. Median on Segments (Permutations Edition)
[ "sortings" ]
1,800
You are given a permutation p_1, p_2, ..., p_n. A permutation of length n is a sequence such that each integer between 1 and n occurs exactly once in the sequence. Find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of the median of p_l, p_{l+1}, ..., p_r is exactly the given number m. The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used. For example, if a=[4, 2, 7, 5] then its median is 4 since after sorting the sequence, it will look like [2, 4, 5, 7] and the left of two middle elements is equal to 4. The median of [7, 1, 2, 9, 6] equals 6 since after sorting, the value 6 will be in the middle of the sequence. Write a program to find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of the median of p_l, p_{l+1}, ..., p_r is exactly the given number m. Input The first line contains integers n and m (1 ≤ n ≤ 2⋅10^5, 1 ≤ m ≤ n) — the length of the given sequence and the required value of the median. The second line contains a permutation p_1, p_2, ..., p_n (1 ≤ p_i ≤ n). Each integer between 1 and n occurs in p exactly once. Output Print the required number. Examples Input 5 4 2 4 5 3 1 Output 4 Input 5 5 1 2 3 4 5 Output 1 Input 15 8 1 15 2 14 3 13 4 8 12 5 11 6 10 7 9 Output 48 Note In the first example, the suitable pairs of indices are: (1, 3), (2, 2), (2, 3) and (2, 4).
The segment $p[l ... r]$ has median equal to $m$ if and only if $m$ belongs to it and $less = greater$ or $less = greater - 1$, where $less$ is the number of elements in $p[l ... r]$ that are strictly less than $m$ and $greater$ is the number of elements in $p[l ... r]$ that are strictly greater than $m$. Here we have used the fact that $p$ is a permutation (on $p[l ... r]$ there is exactly one occurrence of $m$). In other words, $m$ belongs to $p[l ... r]$ and the value $greater - less$ is equal to $0$ or $1$. Calculate prefix sums $sum[0 ... n]$, where $sum[i]$ is the value $greater - less$ on the prefix of length $i$ (i.e., on the subarray $p[0 ... i - 1]$). For a fixed value $r$, it is easy to calculate the number of such $l$ that $p[l ... r]$ is suitable. First, check that $m$ occurs on $[0 ... r]$. Valid values of $l$ are such indices that: no $m$ on $[0 ... l - 1]$ and $sum[l] = sum[r]$ or $sum[r] = sum[l] + 1$. Let's maintain the number of prefix sums $sum[i]$ to the left of $m$ for each value. We can use just a map $c$, where $c[s]$ is the number of such indices $l$ that $sum[l] = s$ and $l$ is to the left of $m$. So, for each $r$ such that $p[0 ... r]$ contains $m$, do `ans += c[sum] + c[sum - 1]`, where $sum$ is the current value of $greater - less$. The time complexity is $O(n \log n)$ if a standard map is used or $O(n)$ if a classical array for $c$ is used (remember about possible negative indices, just use an offset).
1005_E2. Median on Segments (General Case Edition)
[ "sortings" ]
2,400
You are given an integer sequence a_1, a_2, ..., a_n. Find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of median of a_l, a_{l+1}, ..., a_r is exactly the given number m. The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used. For example, if a=[4, 2, 7, 5] then its median is 4 since after sorting the sequence, it will look like [2, 4, 5, 7] and the left of two middle elements is equal to 4. The median of [7, 1, 2, 9, 6] equals 6 since after sorting, the value 6 will be in the middle of the sequence. Write a program to find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of median of a_l, a_{l+1}, ..., a_r is exactly the given number m. Input The first line contains integers n and m (1 ≤ n,m ≤ 2⋅10^5) — the length of the given sequence and the required value of the median. The second line contains an integer sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2⋅10^5). Output Print the required number. Examples Input 5 4 1 4 5 60 4 Output 8 Input 3 1 1 1 1 Output 6 Input 15 2 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 Output 97 Note In the first example, the suitable pairs of indices are: (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 5), (4, 5) and (5, 5).
Let us define a function $greaterCount(m)$ as the number of subarrays with median greater than or equal to $m$. In this case, the answer to the problem is $greaterCount(m) - greaterCount(m + 1)$. The subarray $a[l ... r]$ has median greater than or equal to $m$ if and only if $notLess > less$, where $notLess$ is the number of elements equal to or greater than $m$, and $less$ is the number of elements less than $m$. In other words, instead of processing $a[l ... r]$, we can use the sequence $x[l ... r]$ containing $-1$ or/and $+1$. An element $x[i] = -1$ if $a[i] < m$. An element $x[i] = +1$ if $a[i] \ge m$. Now, the median of $a[l ... r]$ is greater than or equal to $m$ if and only if $x[l] + x[l+1] + ... + x[r] > 0$. Let us iterate over $a$ from left to right. Maintain the current partial sum $sum = x[0] + x[1] + ... + x[i]$. Additionally, in the array $s$, let us maintain the number of partial sums for each of its values. This means that before incrementing $i$, we should do `s[sum]++`. So if $i$ is the index of the right endpoint of a subarray (i.e., $r = i$), then the number of suitable indices $l$ is the number of such $j$ that $x[0] + x[1] + ... + x[j] < sum$. In other words, find the sum of all $s[w]$, where $w < sum$. This is exactly the number of indices with partial sum less than $sum$. Each time the partial sum changes by $-1$ or $+1$. So the value "sum of all $s[w]$, where $w < sum$" is easy to recalculate on each change. If you decrease $sum$, just subtract the value $s[sum]$. If you increase $sum$, before increasing, just add $s[sum]$. Since indices in $s$ can be from $-n$ to $n$, we can use 0-based indices using an array $s[0 ... 2 \times n]$. In this case, initialize $sum$ as $n$ but not as $0$ (this makes $sum$ to be non-negative on each step). This solution works in $O(n)$.
1005_F. Berland and the Shortest Paths
[ "brute force", "dfs and similar", "graphs", "shortest paths" ]
2,100
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n. It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads. The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that: * it is possible to travel from the capital to any other city along the n-1 chosen roads, * if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible). In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads). The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met. Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads. Input The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6. The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital. Output Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options. In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different. Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6. If there are several answers, output any of them. Examples Input 4 4 3 1 2 2 3 1 4 4 3 Output 2 1110 1011 Input 4 6 3 1 2 2 3 1 4 4 3 2 4 1 3 Output 1 101001 Input 5 6 2 1 2 1 3 2 4 2 5 3 4 3 5 Output 2 111100 110110
Use BFS to precalculate an array $d$, which is the array of the shortest path lengths from the Capital. The condition to minimize the sum of distances in each tree is equivalent to the fact that each tree is a shortest path tree. Let us consider them as oriented trees that are outgoing from the Capital. When moving along the edges of such trees, you always move along shortest paths. An edge $(u,v)$ can be included in such a tree if and only if $d[u]+1=d[v]$ (since the original edges are bidirectional, you should consider each of them twice: as $(u,v)$ and as $(v,u)$). Let us focus only on edges for which $d[u]+1=d[v]$. Call them "red" edges. To build a tree for each city (except the Capital), you should choose exactly one red edge that terminates in this city. Therefore, the number of suitable trees is a product of the numbers of incoming edges over all vertices (cities). However, we need to find only $k$ of such trees. Let us start from some such tree and rebuild it at each step. As an initial tree, you can choose the first incoming red edge into each vertex (except the Capital). In fact, we will perform exactly the increment operation for a number in a mixed radix notation. To rebuild a tree, iterate over vertices and if the current used red edge is not the last for the vertex, use the next and stop algorithm. Otherwise, if the last red edge is used, use the first red edge for this vertex (and go to the next vertex) and continue with the next vertex. Compare this algorithm with a simple increment operation for a long number.
1006_A. Adjacent Replacements
[ "implementation" ]
800
Mishka got an integer array a of length n as a birthday present (what a surprise!). Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: * Replace each occurrence of 1 in the array a with 2; * Replace each occurrence of 2 in the array a with 1; * Replace each occurrence of 3 in the array a with 4; * Replace each occurrence of 4 in the array a with 3; * Replace each occurrence of 5 in the array a with 6; * Replace each occurrence of 6 in the array a with 5; * ... * Replace each occurrence of 10^9 - 1 in the array a with 10^9; * Replace each occurrence of 10^9 in the array a with 10^9 - 1. Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers (2i - 1, 2i) for each i ∈\{1, 2, …, 5 ⋅ 10^8\} as described above. For example, for the array a = [1, 2, 4, 5, 10], the following sequence of arrays represents the algorithm: [1, 2, 4, 5, 10] → (replace all occurrences of 1 with 2) → [2, 2, 4, 5, 10] → (replace all occurrences of 2 with 1) → [1, 1, 4, 5, 10] → (replace all occurrences of 3 with 4) → [1, 1, 4, 5, 10] → (replace all occurrences of 4 with 3) → [1, 1, 3, 5, 10] → (replace all occurrences of 5 with 6) → [1, 1, 3, 6, 10] → (replace all occurrences of 6 with 5) → [1, 1, 3, 5, 10] → ... → [1, 1, 3, 5, 10] → (replace all occurrences of 10 with 9) → [1, 1, 3, 5, 9]. The later steps of the algorithm do not change the array. Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it. Input The first line of the input contains one integer number n (1 ≤ n ≤ 1000) — the number of elements in Mishka's birthday present (surprisingly, an array). The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the elements of the array. Output Print n integers — b_1, b_2, ..., b_n, where b_i is the final value of the i-th element of the array after applying "Mishka's Adjacent Replacements Algorithm" to the array a. Note that you cannot change the order of elements in the array. Examples Input 5 1 2 4 5 10 Output 1 1 3 5 9 Input 10 10000 10 50605065 1 5 89 5 999999999 60506056 1000000000 Output 9999 9 50605065 1 5 89 5 999999999 60506055 999999999 Note The first example is described in the problem statement.
It is easy to see that for the odd elements, there is no change after applying the algorithm described in the problem statement. For the even elements, there is only one change: each of the even elements will be decreased by $1$. Therefore, we can iterate over all the elements of the array and print $a_i - (a_i % 2)$, where $x % y$ is the remainder of dividing $x$ by $y$. The overall complexity is $O(n)$.
1006_B. Polycarp's Practice
[ "greedy", "implementation", "sortings" ]
1,200
Polycarp is practicing his problem solving skill. He has a list of n problems with difficulties a_1, a_2, ..., a_n, respectively. His plan is to practice for exactly k days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all n problems in exactly k days. Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in k days he will solve all the n problems. The profit of the j-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the j-th day (i.e. if he solves problems with indices from l to r during a day, then the profit of the day is max_{l ≤ i ≤ r}a_i). The total profit of his practice is the sum of the profits over all k days of his practice. You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all n problems between k days satisfying the conditions above in such a way, that the total profit is maximum. For example, if n = 8, k = 3 and a = [5, 4, 2, 6, 5, 1, 9, 2], one of the possible distributions with maximum total profit is: [5, 4, 2], [6, 5], [1, 9, 2]. Here the total profit equals 5 + 6 + 9 = 20. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2000) — the number of problems and the number of days, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2000) — difficulties of problems in Polycarp's list, in the order they are placed in the list (i.e. in the order Polycarp will solve them). Output In the first line of the output print the maximum possible total profit. In the second line print exactly k positive integers t_1, t_2, ..., t_k (t_1 + t_2 + ... + t_k must equal n), where t_j means the number of problems Polycarp will solve during the j-th day in order to achieve the maximum possible total profit of his practice. If there are many possible answers, you may print any of them. Examples Input 8 3 5 4 2 6 5 1 9 2 Output 20 3 2 3 Input 5 1 1 1 1 1 1 Output 1 5 Input 4 2 1 2000 2000 2 Output 4000 2 2 Note The first example is described in the problem statement. In the second example there is only one possible distribution. In the third example the best answer is to distribute problems in the following way: [1, 2000], [2000, 2]. The total profit of this distribution is 2000 + 2000 = 4000.
The maximum possible `total profit` that you can obtain is the sum of the $k$ largest values in the given array. This is obvious because we can always separate these $k$ maximums and then extend the segments corresponding to them to the left or to the right, thus covering the entire array. I suggest the following: extract the $k$ largest values from the given array and place a separator immediately after each of them (except the rightmost one). The overall complexity of this algorithm is $O(n \log n)$.
1006_C. Three Parts of the Array
[ "binary search", "data structures", "two pointers" ]
1,200
You are given an array d_1, d_2, ..., d_n consisting of n integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be sum_1, the sum of elements of the second part be sum_2 and the sum of elements of the third part be sum_3. Among all possible ways to split the array you have to choose a way such that sum_1 = sum_3 and sum_1 is maximum possible. More formally, if the first part of the array contains a elements, the second part of the array contains b elements and the third part contains c elements, then: $$$sum_1 = ∑_{1 ≤ i ≤ a}d_i, sum_2 = ∑_{a + 1 ≤ i ≤ a + b}d_i, sum_3 = ∑_{a + b + 1 ≤ i ≤ a + b + c}d_i.$$$ The sum of an empty array is 0. Your task is to find a way to split the array such that sum_1 = sum_3 and sum_1 is maximum possible. Input The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array d. The second line of the input contains n integers d_1, d_2, ..., d_n (1 ≤ d_i ≤ 10^9) — the elements of the array d. Output Print a single integer — the maximum possible value of sum_1, considering that the condition sum_1 = sum_3 must be met. Obviously, at least one valid way to split the array exists (use a=c=0 and b=n). Examples Input 5 1 3 1 1 4 Output 5 Input 5 1 3 2 1 4 Output 4 Input 3 4 1 2 Output 0 Note In the first example there is only one possible splitting which maximizes sum_1: [1, 3, 1], [~], [1, 4]. In the second example the only way to have sum_1=4 is: [1, 3], [2, 1], [4]. In the third example there is only one way to split the array: [~], [4, 1, 2], [~].
Since the given array consists of positive integers, for each value of $a$, there can be at most one value of $c$ such that $sum_1 = sum_3$. We can use binary search on the array of prefix sums of $d$ to find the correct value of $c$, if it exists. If it does exist and $a + c \le n$, this is a candidate solution, so we store it. Alternatively, we can use the two pointers trick: when $a$ increases, $c$ cannot decrease. Be careful to use 64-bit integers to store sums. Overall complexity is $O(n \log n)$ or $O(n)$.
1006_D. Two Strings Swaps
[ "implementation" ]
1,700
You are given two strings a and b consisting of lowercase English letters, both of length n. The characters of both strings have indices from 1 to n, inclusive. You are allowed to do the following changes: * Choose any index i (1 ≤ i ≤ n) and swap characters a_i and b_i; * Choose any index i (1 ≤ i ≤ n) and swap characters a_i and a_{n - i + 1}; * Choose any index i (1 ≤ i ≤ n) and swap characters b_i and b_{n - i + 1}. Note that if n is odd, you are formally allowed to swap a_{⌈n/2⌉} with a_{⌈n/2⌉} (and the same with the string b) but this move is useless. Also you can swap two equal characters but this operation is useless as well. You have to make these strings equal by applying any number of changes described above, in any order. But it is obvious that it may be impossible to make two strings equal by these swaps. In one preprocess move you can replace a character in a with another character. In other words, in a single preprocess move you can choose any index i (1 ≤ i ≤ n), any character c and set a_i := c. Your task is to find the minimum number of preprocess moves to apply in such a way that after them you can make strings a and b equal by applying some number of changes described in the list above. Note that the number of changes you make after the preprocess moves does not matter. Also note that you cannot apply preprocess moves to the string b or make any preprocess moves after the first change is made. Input The first line of the input contains one integer n (1 ≤ n ≤ 10^5) — the length of strings a and b. The second line contains the string a consisting of exactly n lowercase English letters. The third line contains the string b consisting of exactly n lowercase English letters. Output Print a single integer — the minimum number of preprocess moves to apply before changes, so that it is possible to make the string a equal to string b with a sequence of changes from the list above. Examples Input 7 abacaba bacabaa Output 4 Input 5 zcabd dbacz Output 0 Note In the first example preprocess moves are as follows: a_1 := 'b', a_3 := 'c', a_4 := 'a' and a_5:='b'. Afterwards, a = "bbcabba". Then we can obtain equal strings by the following sequence of changes: swap(a_2, b_2) and swap(a_2, a_6). There is no way to use fewer than 4 preprocess moves before a sequence of changes to make string equal, so the answer in this example is 4. In the second example no preprocess moves are required. We can use the following sequence of changes to make a and b equal: swap(b_1, b_5), swap(a_2, a_4).
Let us divide all characters of both strings into groups in such a way that characters in each group can be swapped with each other with `changes`. Thus, there will be the following groups: ${a_1, a_n, b_1, b_n}$, ${a_2, a_{n - 1}, b_2, b_{n - 1}}$, and so on. Since these groups do not affect each other, we can calculate the number of `preprocess moves` in each group and then sum it up. How do we determine if a group does not require any preprocess moves? For a group consisting of $2$ characters (there will be one such group if $n$ is odd, it will contain $a_{\lceil\dfrac{n}{2}\rceil}$ and $b_{\lceil\dfrac{n}{2}\rceil}$), this is straightforward: if the characters in this group are equal, the answer is $0$, otherwise it is $1$. To determine the required number of preprocess moves for a group consisting of four characters, we can use the following fact: this group does not require preprocess moves if and only if the characters in this group can be divided into pairs. Thus, if the group contains four equal characters, or two pairs of equal characters, then the answer for this group is $0$. Otherwise, we can check that replacing only one character of $a_i$ and $a_{n - i + 1}$ will be enough; if so, then the answer is $1$, otherwise it is $2$. The overall complexity is $O(n)$.
1006_E. Military Problem
[ "dfs and similar", "graphs", "trees" ]
1,600
In this problem you will have to help Berland army with organizing their command delivery system. There are n officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer a is the direct superior of officer b, then we also can say that officer b is a direct subordinate of officer a. Officer x is considered to be a subordinate (direct or indirect) of officer y if one of the following conditions holds: * officer y is the direct superior of officer x; * the direct superior of officer x is a subordinate of officer y. For example, on the picture below the subordinates of the officer 3 are: 5, 6, 7, 8, 9. The structure of Berland army is organized in such a way that every officer, except for the commander, is a subordinate of the commander of the army. Formally, let's represent Berland army as a tree consisting of n vertices, in which vertex u corresponds to officer u. The parent of vertex u corresponds to the direct superior of officer u. The root (which has index 1) corresponds to the commander of the army. Berland War Ministry has ordered you to give answers on q queries, the i-th query is given as (u_i, k_i), where u_i is some officer, and k_i is a positive integer. To process the i-th query imagine how a command from u_i spreads to the subordinates of u_i. Typical DFS (depth first search) algorithm is used here. Suppose the current officer is a and he spreads a command. Officer a chooses b — one of his direct subordinates (i.e. a child in the tree) who has not received this command yet. If there are many such direct subordinates, then a chooses the one having minimal index. Officer a gives a command to officer b. Afterwards, b uses exactly the same algorithm to spread the command to its subtree. After b finishes spreading the command, officer a chooses the next direct subordinate again (using the same strategy). When officer a cannot choose any direct subordinate who still hasn't received this command, officer a finishes spreading the command. Let's look at the following example: <image> If officer 1 spreads a command, officers receive it in the following order: [1, 2, 3, 5 ,6, 8, 7, 9, 4]. If officer 3 spreads a command, officers receive it in the following order: [3, 5, 6, 8, 7, 9]. If officer 7 spreads a command, officers receive it in the following order: [7, 9]. If officer 9 spreads a command, officers receive it in the following order: [9]. To answer the i-th query (u_i, k_i), construct a sequence which describes the order in which officers will receive the command if the u_i-th officer spreads it. Return the k_i-th element of the constructed list or -1 if there are fewer than k_i elements in it. You should process queries independently. A query doesn't affect the following queries. Input The first line of the input contains two integers n and q (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ q ≤ 2 ⋅ 10^5) — the number of officers in Berland army and the number of queries. The second line of the input contains n - 1 integers p_2, p_3, ..., p_n (1 ≤ p_i < i), where p_i is the index of the direct superior of the officer having the index i. The commander has index 1 and doesn't have any superiors. The next q lines describe the queries. The i-th query is given as a pair (u_i, k_i) (1 ≤ u_i, k_i ≤ n), where u_i is the index of the officer which starts spreading a command, and k_i is the index of the required officer in the command spreading sequence. Output Print q numbers, where the i-th number is the officer at the position k_i in the list which describes the order in which officers will receive the command if it starts spreading from officer u_i. Print "-1" if the number of officers which receive the command is less than k_i. You should process queries independently. They do not affect each other. Example Input 9 6 1 1 1 3 5 3 5 7 3 1 1 5 3 4 7 3 1 8 1 9 Output 3 6 8 -1 9 4
Let us form the following vector $p$: we run DFS from the first vertex and push the vertex $v$ to the vector when entering this vertex. Let $tin_v$ be the position of the vertex $v$ in the vector $p$ (the size of the vector $p$ at the moment we call DFS from the vertex $v$) and $tout_v$ be the position of the first vertex pushed to the vector after leaving the vertex $v$ (the size of the vector $p$ at the moment when we return from DFS from the vertex $v$). Then it is obvious that the subtree of the vertex $v$ lies in the half-interval $[tin_v; tout_v)$. After running such DFS we can answer the queries. Let $pos_i = v_i + k_i - 1$ (answering the $i$-th query). If $pos_i$ is greater than or equal to $n$ then the answer to the $i$-th query is `-1`. We need to check if the vertex $p_{pos_i}$ lies in the subtree of the vertex $v_i$. The vertex $a$ is in the subtree of the vertex $b$ if and only if $[tin_a; tout_a) \subseteq [tin_b; tout_b)$. If the vertex $p_{pos_i}$ is not in the subtree of the vertex $v_i$ then the answer is `-1`. Otherwise, the answer is $p_{pos_i}$. Overall complexity is $O(n + q)$.
1006_F. Xor-Paths
[ "bitmasks", "brute force", "dp", "meet-in-the-middle" ]
2,100
There is a rectangular grid of size n × m. Each cell has a number written on it; the number on the cell (i, j) is a_{i, j}. Your task is to calculate the number of paths from the upper-left cell (1, 1) to the bottom-right cell (n, m) meeting the following constraints: * You can move to the right or to the bottom only. Formally, from the cell (i, j) you may move to the cell (i, j + 1) or to the cell (i + 1, j). The target cell can't be outside of the grid. * The xor of all the numbers on the path from the cell (1, 1) to the cell (n, m) must be equal to k (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and "xor" in Pascal). Find the number of such paths in the given grid. Input The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 20, 0 ≤ k ≤ 10^{18}) — the height and the width of the grid, and the number k. The next n lines contain m integers each, the j-th element in the i-th line is a_{i, j} (0 ≤ a_{i, j} ≤ 10^{18}). Output Print one integer — the number of paths from (1, 1) to (n, m) with xor sum equal to k. Examples Input 3 3 11 2 1 5 7 10 0 12 6 4 Output 3 Input 3 4 2 1 3 3 3 0 3 3 2 3 0 1 1 Output 5 Input 3 4 1000000000000000000 1 3 3 3 0 3 3 2 3 0 1 1 Output 0 Note All the paths from the first example: * (1, 1) → (2, 1) → (3, 1) → (3, 2) → (3, 3); * (1, 1) → (2, 1) → (2, 2) → (2, 3) → (3, 3); * (1, 1) → (1, 2) → (2, 2) → (3, 2) → (3, 3). All the paths from the second example: * (1, 1) → (2, 1) → (3, 1) → (3, 2) → (3, 3) → (3, 4); * (1, 1) → (2, 1) → (2, 2) → (3, 2) → (3, 3) → (3, 4); * (1, 1) → (2, 1) → (2, 2) → (2, 3) → (2, 4) → (3, 4); * (1, 1) → (1, 2) → (2, 2) → (2, 3) → (3, 3) → (3, 4); * (1, 1) → (1, 2) → (1, 3) → (2, 3) → (3, 3) → (3, 4).
This is a typical problem that can be solved using the `meet-in-the-middle` technique. The number of moves we will make is equal to $n + m - 2$. So if $n + m$ is small enough (25 is the upper bound, I believe), then we can simply run recursive backtracking in $O(2^{n + m - 2})$ or in $O({n + m - 2 \choose m - 1}\times (n + m - 2))$ to iterate over all binary masks of length $n + m - 2$ containing exactly $m - 1$ ones and check each path described by such mask (where 0 in the mask represents a move down and 1 represents a move right) to see if its `xor` is equal to $k$. However, this is too slow. So let's split this mask of $n + m - 2$ bits into two parts: the left part will consist of $mid = \lfloor\dfrac{n + m - 2}{2}\rfloor$ bits and the right part will consist of $n + m - 2 - mid$ bits. Note that each left mask (and each right mask as well) uniquely describes the endpoint of the path and the path itself. Let's create $n \times m$ associative arrays $cnt$, where $cnt_{x, y, c}$ for the endpoint $(x, y)$ and `xor` $c$ will denote the number of paths that end in the cell $(x, y)$ with `xor` $c$. Let's run recursive backtracking, which will iterate over paths starting from the cell $(1, 1)$ and move to the right or down, while maintaining the `xor` of the path. If we have made $mid$ moves and are currently in the cell $(x, y)$ with `xor` $c$, then we set $cnt_{x, y, c} := cnt_{x, y, c} + 1$ and return from the function. Otherwise, we try to move down or right, while updating the `xor` as needed. Let's run another recursive backtracking, which will iterate over paths starting from the cell $(n, m)$ and move to the left or up, while maintaining the `xor` of the path except for the last cell. Similarly, if we have made $n + m - 2 - mid$ moves and are currently in the cell $(x, y)$ with `xor` $c$, then we add $cnt_{x, y, k ^ c}$ to the answer (this is because we are "complementing" our `xor` from the right part of the path with the appropriate `xor` from the left part of the path). Otherwise, we try to move left or up, while updating the `xor` as needed. This is the `meet-in-the-middle` technique (at least the way I implement it). The overall complexity is $O(2^{\dfrac{n + m - 2}{2}} \times \dfrac{n + m - 2}{2})$.
1008_A. Romaji
[ "implementation", "strings" ]
900
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not. Help Vitya find out if a word s is Berlanese. Input The first line of the input contains the string s consisting of |s| (1≤ |s|≤ 100) lowercase Latin letters. Output Print "YES" (without quotes) if there is a vowel after every consonant except "n", otherwise print "NO". You can print each letter in any case (upper or lower). Examples Input sumimasen Output YES Input ninja Output YES Input codeforces Output NO Note In the first and second samples, a vowel goes after each consonant except "n", so the word is Berlanese. In the third sample, the consonant "c" goes after the consonant "r", and the consonant "s" stands on the end, so the word is not Berlanese.
You need to check if after every letter except one of these `aouien`, there follows one of these `aouie`. Do not forget to check the last letter.
1008_B. Turn the Rectangles
[ "greedy", "sortings" ]
1,000
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles. Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such). Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles. Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle. Output Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO". You can print each letter in any case (upper or lower). Examples Input 3 3 4 4 6 3 5 Output YES Input 2 3 4 5 5 Output NO Note In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3]. In the second test, there is no way the second rectangle will be not higher than the first one.
You must iterate over the rectangles from left to right and rotate each rectangle in such a way that its height is as large as possible but not greater than the height of the previous rectangle (if it is not the first one). If, on some iteration, there is no such way to place the rectangle, the answer is `NO`.
1008_C. Reorder the Array
[ "combinatorics", "data structures", "math", "sortings", "two pointers" ]
1,300
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 ≤ n ≤ 10^5) — the length of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 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.
The answer is $n$ minus the maximum number of equal elements. Let the maximum number of equal elements be $x$. We will prove that $n-x$ is reachable. It is clear that for every permutation of the array, the answer will be the same, so we will sort the array in non-decreasing order. Now we simply need to perform a left shift by $x$. After this, the $n-x$ rightmost elements will move to a position of a smaller element. Now we will prove that the answer is no more than $n-x$. Consider some permutation. It is known that every permutation can be decomposed into cycles. Consider two occurrences of the same number in the same cycle. Then there is at least one number between them which will move to a position of a non-smaller element. Even if it is the same occurrence and even if the length of the cycle is $1$, we can say that for every occurrence of this number there is at least one number which moves to a position of a non-smaller one. So if some number occurs $x$ times, there are at least $x$ bad positions and therefore no more than $n-x$ good positions. To count the number of equal elements, you can, for instance, use `std::map`.
1008_D. Pave the Parallelepiped
[ "bitmasks", "brute force", "combinatorics", "math", "number theory" ]
2,400
You are given a rectangular parallelepiped with sides of positive integer lengths A, B and C. Find the number of different groups of three integers (a, b, c) such that 1≤ a≤ b≤ c and parallelepiped A× B× C can be paved with parallelepipeds a× b× c. Note, that all small parallelepipeds have to be rotated in the same direction. For example, parallelepiped 1× 5× 6 can be divided into parallelepipeds 1× 3× 5, but can not be divided into parallelepipeds 1× 2× 3. Input The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. Each of the next t lines contains three integers A, B and C (1 ≤ A, B, C ≤ 10^5) — the sizes of the parallelepiped. Output For each test case, print the number of different groups of three points that satisfy all given conditions. Example Input 4 1 1 1 1 6 1 2 2 2 100 100 100 Output 1 4 4 165 Note In the first test case, rectangular parallelepiped (1, 1, 1) can be only divided into rectangular parallelepiped with sizes (1, 1, 1). In the second test case, rectangular parallelepiped (1, 6, 1) can be divided into rectangular parallelepipeds with sizes (1, 1, 1), (1, 1, 2), (1, 1, 3) and (1, 1, 6). In the third test case, rectangular parallelepiped (2, 2, 2) can be divided into rectangular parallelepipeds with sizes (1, 1, 1), (1, 1, 2), (1, 2, 2) and (2, 2, 2).
## First Solution: First, for every natural number up to $10^5$ we count its number of divisors in $O(\sqrt{n})$. Also, for every unordered set of 3 masks $(m_1, m_2, m_3)$ of length 3, we check if there is a way to enumerate them such that $1 \in m_1$, $2 \in m_2$, and $3 \in m_3$. We will call such sets "acceptable." Now, let's consider two parallelepipeds. For each dimension of the second parallelepiped, let's construct a mask of length 3, which contains the numbers of the dimensions of the first parallelepiped for which the length of the first parallelepiped along this dimension is divisible by the length of the second parallelepiped along the chosen dimension. These three masks form an acceptable set if and only if we can pave the first parallelepiped with the second one. Now, for a given parallelepiped, let's calculate, for every mask of length 3, the number of possible lengths of the second parallelepiped which would produce this mask. We can do this by taking the greatest common divisor (GCD) of the lengths of the first parallelepiped along the dimensions whose numbers are in the mask and subtracting from it the calculated numbers for every submask. Now, let's iterate over acceptable sets of masks. For each different mask from the set which is included into the set \(k\) times, we need to calculate the number of ways to take \(k\) unordered lengths which produce this mask and multiply these numbers. The sum of these numbers is the answer to the query. So, for every query we need $O(2^{m^2})$ operations, where $m = 3$ is the number of dimensions of the parallelepiped. ## Second Solution: First, for every natural number up to $10^5$, we count its number of divisors in $O(\sqrt{n})$. Then, for every query, for every subset of numbers in it, we keep their GCD and the number of its divisors. So, for every subset of these three numbers, we know the number of their common divisors. Let's look at the parallelepiped $(a, b, c)$. The way we orient it with respect to the large parallelepiped is determined by a permutation of size 3-that is, which dimension would correspond to every dimension in the large one. Using the inclusion-exclusion principle on these permutations, we can count how many parallelepipeds there are (considering the orientation) that we can orient in some way to then pave the large parallelepiped with it. Namely, we fix the set of permutations for which our parallelepiped shall satisfy. Then, for every side of the small parallelepiped, we know which sides of the large one it shall divide. To find the number of such sides of the small one, we shall take the number of common divisors of the corresponding sides of the large one. Now, to find the number of such small parallelepipeds, we must multiply the three resultant numbers. In this way, every parallelepiped satisfying this criterion (not considering the orientation) with three different side lengths was counted 6 times, with two different lengths was counted 3 times, with one different length was counted 1 time. But it won't be difficult for us to use the same approach in counting such parallelepipeds, but with no less than two same side lengths: let's say the first and the second. To do this, when we fix which permutations this parallelepiped shall satisfy, we should just add the condition that its first and second side lengths must be equal; this means they both must divide both of the sets corresponding to them, so instead of these two sets, we must take their union. Let's add the resultant number multiplied by three to the answer. Now, every parallelepiped with three different side lengths is still counted 6 times, with two different is now counted also 6 times, and with one different is counted 4 times. The number of satisfying parallelepipeds with equal sides is just the number of common divisors of all the sides of the large parallelepiped. Let's add it multiplied by two, and now every needed parallelepiped is counted 6 times. We divide this number by 6 and get the answer. So, for every query we need $O(p(m) \times 2^{m!} \times m)$ operations, where $p(m)$ is the number of partitions of $m$, and $m = 3$ is the number of dimensions of the parallelepiped.
1008_E. Guess two numbers
[ "binary search", "interactive" ]
3,000
This is an interactive problem. Vasya and Vitya play a game. Vasya thought of two integers a and b from 1 to n and Vitya tries to guess them. Each round he tells Vasya two numbers x and y from 1 to n. If both x=a and y=b then Vitya wins. Else Vasya must say one of the three phrases: 1. x is less than a; 2. y is less than b; 3. x is greater than a or y is greater than b. Vasya can't lie, but if multiple phrases are true, he may choose any of them. For example, if Vasya thought of numbers 2 and 4, then he answers with the phrase 3 to a query (3, 4), and he can answer with the phrase 1 or phrase 3 to a query (1, 5). Help Vitya win in no more than 600 rounds. Input The first line contains a single integer n (1 ≤ n ≤ 10^{18}) — the upper limit of the numbers. Interaction First, you need to read the number n, after that you can make queries. To make a query, print two integers: x and y (1 ≤ x, y ≤ n), then flush the output. After each query, read a single integer ans (0 ≤ ans ≤ 3). If ans > 0, then it is the number of the phrase said by Vasya. If ans = 0, it means that you win and your program should terminate. If you make more than 600 queries or make an incorrect query, you will get Wrong Answer. Your solution will get Idleness Limit Exceeded, if you don't print anything or forget to flush the output. To flush you need to do the following right after printing a query and a line end: * fflush(stdout) in C++; * System.out.flush() in Java; * stdout.flush() in Python; * flush(output) in Pascal; * For other languages see documentation. Hacks format For hacks, use the following format: In the first line, print a single integer n (1 ≤ n ≤ 10^{18}) — the upper limit of the numbers. In the second line, print two integers a and b (1 ≤ a, b ≤ n) — the numbers which Vasya thought of. In the third line, print a single integer m (1 ≤ m ≤ 10^5) — the number of instructions for the interactor. In each of the next m lines, print five integers: x_i, y_i, r^{12}_i, r^{13}_i, and r^{23}_i (1 ≤ x_i, y_i ≤ n), where r^{ST}_i equals to either number S or number T. While answering the query x y, the interactor finds a number i from 1 to n with the minimal value |x-x_i| + |y-y_i|. If multiple numbers can be chosen, the least i is preferred. Then the interactor answers to the query, but if there are two phrases S and T that can be given, then r^{ST}_i is chosen. For example, the sample test data file contains the following: 5 2 4 2 2 5 1 1 2 4 1 2 3 3 Example Input 5 3 3 2 1 0 Output 4 3 3 4 3 3 1 5 2 4 Note Let's analyze the sample test. The chosen numbers are 2 and 4. The interactor was given two instructions. For the query (4, 3), it can return 2 or 3. Out of the two instructions the second one is chosen, so the interactor returns a^{23}_2=3. For the query (3, 4), it can return only 3. For the query (3, 3), it can return 2 or 3. Out of the two instructions the first one is chosen (since in case of equal values, the least number is preferred), so the interactor returns a^{23}_1=2. For the query (1, 5), it can return 1 or 3. Out of the two instructions the first one is chosen, so the interactor returns a^{13}_1=1. In the fifth query (2, 4), the numbers are guessed correctly, the player wins.
First Solution: Let's keep the set of possible answers as a union of three rectangles forming an angle: $A =[ x_l, x_m) \times [ y_l, y_m)$, $B =[ x_l, x_m) \times [ y_m, y_r)$, and $C =[ x_m, x_r) \times [ y_l, y_m)$, where $x_l < x_m \le x_r$ and $y_l < y_m \le y_r$. Let $S_A$, $S_B$, and $S_C$ be their areas. We will denote such a state as $(x_l, x_m, x_r, y_l, y_m, y_r)$. The initial state is $(0, n + 1, n + 1, 0, n + 1, n + 1)$. Now there are three cases: - If $S_B \le S_A + S_C$ and $S_B \le S_A + S_B$, then we will make a query $(\lfloor \dfrac{x_l + x_m}{2}\rfloor,\lfloor \dfrac{y_l + y_m}{2}\rfloor)$. - If $S_B > S_A + S_C$, we will make a query $(\lfloor \dfrac{x_l + x_m}{2}\rfloor, y_m)$. - Finally, if $S_C > S_A + S_B$, we will make a query $(x_m,\lfloor \dfrac{y_l + y_m}{2}\rfloor)$. In the case of every response to every query, the new set of possible answers will also form an angle. Now we want to prove that the area of the angle decreases at least by a quarter every two requests. In case (1), if the answer is $1$, then we move to a state $(\lfloor \dfrac{x_l + x_m}{2}\rfloor + 1, x_m, x_r, y_l, y_m, y_r)$. We cut off at least half of $A$ and at least half of $B$. But $\dfrac{S_A}{2} + \dfrac{S_B}{2} = \dfrac{S_A + S_B}{4} + \dfrac{S_A + S_B}{4} \ge \dfrac{S_A + S_B}{4} + \dfrac{S_C}{4} = \dfrac{S_A + S_B + S_C}{4}$. I.e., we have cut off at least a quarter already within just one request. If the answer is $2$, the situation is similar. Finally, if the answer is $3$, then we move to a state $(x_l,\lfloor \dfrac{x_l + x_m}{2}\rfloor, x_r, y_l,\lfloor \dfrac{y_l + y_m}{2}\rfloor, y_r)$. We cut off at least a quarter of $A$, at least half of $B$, and at least half of $C$. But $\dfrac{S_A}{4} + \dfrac{S_B}{2} + \dfrac{S_C}{2} \ge \dfrac{S_A}{4} + \dfrac{S_B}{4} + \dfrac{S_C}{4} = \dfrac{S_A + S_B + S_C}{4}$. We also have cut off at least a quarter within just one request. Thus, in case (1), we cut off at least a quarter within one request. In case (2), if the answer is $1$, then we move to a state $(\lfloor \dfrac{x_l + x_m}{2}\rfloor + 1, x_m, x_r, y_l, y_m, y_r)$. We cut off at least half of $A$ and at least half of $B$. But $\dfrac{S_A}{2} + \dfrac{S_B}{2} \ge \dfrac{S_B}{2} \ge \dfrac{S_B}{4} + \dfrac{S_B}{4} \ge \dfrac{S_B}{4} + \dfrac{S_A + S_C}{4} = \dfrac{S_A + S_B + S_C}{4}$. We have cut off at least a quarter within just one request. If the answer is $2$, then we move to a state $(x_l, x_r, x_r, y_m + 1, y_r, y_r)$. But then it will be case (1), thus we will cut off at least a quarter with the next request. Finally, if the answer is $3$, then we move to a state $(x_l,\lfloor \dfrac{x_l + x_m}{2}\rfloor, x_r, y_l, y_m, y_r)$. We cut off at least half of $B$. But $\dfrac{S_B}{2} \ge \dfrac{S_B}{4} + \dfrac{S_B}{4} \ge \dfrac{S_B}{4} + \dfrac{S_A + S_C}{4} = \dfrac{S_A + S_B + S_C}{4}$. We also have cut off at least a quarter within just one request. Case (3) is similar to case (2). Thus, the maximal number of requests will be no more than $1 + 2 \times \log_{4/3}((10^{18})^2) \approx 577$. Second Solution: Let's keep the set of possible answers in the form of a ladder $A$. Then let's find the minimal $X$ such that $S(A \cap {x \le X}) \ge \dfrac{S(A)}{3}$. And let's find the minimal $Y$ such that $S(A \cap {y \le Y}) \ge \dfrac{S(A)}{3}$. Then $S(A \cap {x \ge X} \cap {y \ge Y}) = S(A \setminus(A \cap {x \le X - 1}) \setminus(A \cap {y \le Y - 1})) \ge S(A) - S(A \cap {x \le X - 1}) - S(A \cap {y \le Y - 1}) \ge S(A) - \dfrac{S(A)}{3} - \dfrac{S(A)}{3} = \dfrac{S(A)}{3}$. This means we cut off at least a third of the area of the ladder on each request. Thus, the maximal number of requests will be no more than $1 + \log_{3/2}((10^{18})^2) \approx 205$.
1009_A. Game Shopping
[ "implementation" ]
800
Maxim wants to buy some games at the local game shop. There are n games in the shop, the i-th game costs c_i. Maxim has a wallet which can be represented as an array of integers. His wallet contains m bills, the j-th bill has value a_j. Games in the shop are ordered from left to right, Maxim tries to buy every game in that order. When Maxim stands at the position i in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the i-th game using this bill. After Maxim tried to buy the n-th game, he leaves the shop. Maxim buys the i-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the i-th game. If he successfully buys the i-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game. For example, for array c = [2, 4, 5, 2, 4] and array a = [5, 3, 4, 6] the following process takes place: Maxim buys the first game using the first bill (its value is 5), the bill disappears, after that the second bill (with value 3) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because c_2 > a_2, the same with the third game, then he buys the fourth game using the bill of value a_2 (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value a_3. Your task is to get the number of games Maxim will buy. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of games and the number of bills in Maxim's wallet. The second line of the input contains n integers c_1, c_2, ..., c_n (1 ≤ c_i ≤ 1000), where c_i is the cost of the i-th game. The third line of the input contains m integers a_1, a_2, ..., a_m (1 ≤ a_j ≤ 1000), where a_j is the value of the j-th bill from the Maxim's wallet. Output Print a single integer — the number of games Maxim will buy. Examples Input 5 4 2 4 5 2 4 5 3 4 6 Output 3 Input 5 2 20 40 50 20 40 19 20 Output 0 Input 6 4 4 8 15 16 23 42 1000 1000 1000 1000 Output 4 Note The first example is described in the problem statement. In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop. In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet.
Let's maintain a variable $pos$ which will represent the number of games Maxim buys. Initially, $pos = 0$. Assume that the arrays $a$ and $c$ are 0-indexed. Then, let's iterate over all $i = 0 ... n - 1$ and if $pos < m$ and $a[pos] \ge c[i]$, set $pos := pos + 1$. Thus, $pos$ will be the answer after this loop.
1009_B. Minimum Ternary String
[ "greedy", "implementation" ]
1,400
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2'). You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa). For example, for string "010210" we can perform the following moves: * "010210" → "100210"; * "010210" → "001210"; * "010210" → "010120"; * "010210" → "010201". Note than you cannot swap "02" → "20" and vice versa. You cannot perform any other operations with the given string excluding described above. You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero). String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 ≤ i ≤ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i. Input The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive). Output Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero). Examples Input 100210 Output 001120 Input 11222121 Output 11112222 Input 20 Output 20
Note that the described swaps allow us to place any `1` character in any position of the string $s$ (the relative order of `0` and `2` characters cannot be changed). Let us remove all `1` characters from the string $s$ (and keep their count in some variable). Now a more profitable move is to place all the `1` characters immediately before the first `2` character of $s$ (and if there is no `2` character in $s$, then place them at the end of the string).
1009_C. Annoying Present
[ "greedy", "math" ]
1,700
Alice got an array of length n as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice. Bob has chosen m changes of the following form. For some integer numbers x and d, he chooses an arbitrary position i (1 ≤ i ≤ n) and for every j ∈ [1, n] adds x + d ⋅ dist(i, j) to the value of the j-th cell. dist(i, j) is the distance between positions i and j (i.e. dist(i, j) = |i - j|, where |x| is an absolute value of x). For example, if Alice currently has an array [2, 1, 2, 2] and Bob chooses position 3 for x = -1 and d = 2 then the array will become [2 - 1 + 2 ⋅ 2,~1 - 1 + 2 ⋅ 1,~2 - 1 + 2 ⋅ 0,~2 - 1 + 2 ⋅ 1] = [5, 2, 1, 3]. Note that Bob can't choose position i outside of the array (that is, smaller than 1 or greater than n). Alice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric. What is the maximum arithmetic mean value Bob can achieve? Input The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of elements of the array and the number of changes. Each of the next m lines contains two integers x_i and d_i (-10^3 ≤ x_i, d_i ≤ 10^3) — the parameters for the i-th change. Output Print the maximal average arithmetic mean of the elements Bob can achieve. Your answer is considered correct if its absolute or relative error doesn't exceed 10^{-6}. Examples Input 2 3 -1 3 0 0 -1 -4 Output -2.500000000000000 Input 3 2 0 2 5 0 Output 7.000000000000000
Based on the constraints, we can infer that the greedy approach is the correct one. First, let's transition from maximizing the arithmetic mean to the sum, as they are essentially equivalent. Second, note that each $x$ is added to each element regardless of the chosen position. Finally, consider the function $f(d, i)$, which represents the total sum obtained by applying a change of $d$ to position $i$. This function is non-strictly convex, meaning that its maximum or minimum values can always be found in one of the following positions: $\dfrac{n}{2}$ (the method of rounding does not matter), $1$, and $n$. Therefore, the solution is as follows: for positive $d$, we apply the change to position $1$, and for non-positive $d$, we apply the change to position $\lfloor \dfrac{n}{2} \rfloor$. The impact of the change can be calculated using the formula for the sum of an arithmetic progression. Additionally, you should either perform all of your calculations in `long double` (a 10-byte type) or maintain the sum in `long long` (which can be estimated with $m \times n^2 \times MAXN \le 10^{18}$, so it fits) and divide it by $n$ at the end (which will allow you to use double). The overall complexity is $O(m)$.
1009_D. Relatively Prime Graph
[ "brute force", "constructive algorithms", "graphs", "greedy", "math" ]
1,700
Let's call an undirected graph G = (V, E) relatively prime if and only if for each edge (v, u) ∈ E GCD(v, u) = 1 (the greatest common divisor of v and u is 1). If there is no edge between some pair of vertices v and u then the value of GCD(v, u) doesn't matter. The vertices are numbered from 1 to |V|. Construct a relatively prime graph with n vertices and m edges such that it is connected and it contains neither self-loops nor multiple edges. If there exists no valid graph with the given number of vertices and edges then output "Impossible". If there are multiple answers then print any of them. Input The only line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of vertices and the number of edges. Output If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The i-th of the next m lines should contain the i-th edge (v_i, u_i) of the resulting graph (1 ≤ v_i, u_i ≤ n, v_i ≠ u_i). For each pair (v, u) there can be no more pairs (v, u) or (u, v). The vertices are numbered from 1 to n. If there are multiple answers then print any of them. Examples Input 5 6 Output Possible 2 5 3 2 5 1 3 4 4 1 5 4 Input 6 12 Output Impossible Note Here is the representation of the graph from the first example: <image>
Although $n$ is up to $10^5$, a straightforward $O(n^2 \log n)$ solution will suffice. Iterate for $i$ from $1$ to $n$ in the outer loop, from $i + 1$ to $n$ in the inner loop, and check the GCD each time. When $m$ edges are found, break from both loops. Here is why this works fast enough. The total number of pairs $(x, y)$ with $1 \le x, y \le n, gcd(x, y) = 1$ is $\phi(1) + \phi(2) + ... + \phi(n)$, where $\phi$ is Euler's totient function. We also want to subtract a single pair $(1, 1)$. This sum grows so fast that after about $600$ iterations $\phi(1) + \phi(2) + ... + \phi(600)$ will be greater than $100000$ for any $n$. The only thing left is to check that $m$ is large enough to build a connected graph ($m \ge n - 1$) and small enough to fit all possible edges for a given $n$ (the formula above). Overall complexity: $O(n^2 \log n)$.
1009_E. Intercity Travelling
[ "combinatorics", "math", "probabilities" ]
2,000
Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car. The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance between Moscow and Saratov is n km. Let's say that Moscow is situated at the point with coordinate 0 km, and Saratov — at coordinate n km. Driving for a long time may be really difficult. Formally, if Leha has already covered i kilometers since he stopped to have a rest, he considers the difficulty of covering (i + 1)-th kilometer as a_{i + 1}. It is guaranteed that for every i ∈ [1, n - 1] a_i ≤ a_{i + 1}. The difficulty of the journey is denoted as the sum of difficulties of each kilometer in the journey. Fortunately, there may be some rest sites between Moscow and Saratov. Every integer point from 1 to n - 1 may contain a rest site. When Leha enters a rest site, he may have a rest, and the next kilometer will have difficulty a_1, the kilometer after it — difficulty a_2, and so on. For example, if n = 5 and there is a rest site in coordinate 2, the difficulty of journey will be 2a_1 + 2a_2 + a_3: the first kilometer will have difficulty a_1, the second one — a_2, then Leha will have a rest, and the third kilometer will have difficulty a_1, the fourth — a_2, and the last one — a_3. Another example: if n = 7 and there are rest sites in coordinates 1 and 5, the difficulty of Leha's journey is 3a_1 + 2a_2 + a_3 + a_4. Leha doesn't know which integer points contain rest sites. So he has to consider every possible situation. Obviously, there are 2^{n - 1} different distributions of rest sites (two distributions are different if there exists some point x such that it contains a rest site in exactly one of these distributions). Leha considers all these distributions to be equiprobable. He wants to calculate p — the expected value of difficulty of his journey. Obviously, p ⋅ 2^{n - 1} is an integer number. You have to calculate it modulo 998244353. Input The first line contains one number n (1 ≤ n ≤ 10^6) — the distance from Moscow to Saratov. The second line contains n integer numbers a_1, a_2, ..., a_n (1 ≤ a_1 ≤ a_2 ≤ ... ≤ a_n ≤ 10^6), where a_i is the difficulty of i-th kilometer after Leha has rested. Output Print one number — p ⋅ 2^{n - 1}, taken modulo 998244353. Examples Input 2 1 2 Output 5 Input 4 1 3 3 7 Output 60
Let us consider each kilometer of the journey separately and calculate the expected value of its difficulty (and then use linearity of expectation to obtain the answer). The difficulty of each kilometer depends on the rest site immediately preceding it (or, if there were no rest sites, on the distance from Moscow to this kilometer). So when considering the difficulty of the $i$-th kilometer (one-indexed), we may obtain a formula: $diff_i = \dfrac{a_1}{2} + \dfrac{a_2}{2^2} + ... + \dfrac{a_{i - 1}}{2^{i - 1}} + \dfrac{a_i}{2^{i - 1}}$. The denominator of the last summand is $2^{i - 1}$ because it represents the situation where the last rest was in Moscow, and its probability is exactly $\dfrac{1}{2^{i - 1}}$. We can actually rewrite this as follows: $diff_1 = a_1$, $diff_{i + 1} = diff_i - \dfrac{a_i}{2^i} + \dfrac{a_{i + 1}}{2^i}$, thus calculating all that we need in linear time.
1009_F. Dominant Indices
[ "data structures", "dsu", "trees" ]
2,300
You are given a rooted undirected tree consisting of n vertices. Vertex 1 is the root. Let's denote a depth array of vertex x as an infinite sequence [d_{x, 0}, d_{x, 1}, d_{x, 2}, ...], where d_{x, i} is the number of vertices y such that both conditions hold: * x is an ancestor of y; * the simple path from x to y traverses exactly i edges. The dominant index of a depth array of vertex x (or, shortly, the dominant index of vertex x) is an index j such that: * for every k < j, d_{x, k} < d_{x, j}; * for every k > j, d_{x, k} ≤ d_{x, j}. For every vertex in the tree calculate its dominant index. Input The first line contains one integer n (1 ≤ n ≤ 10^6) — the number of vertices in a tree. Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y). This line denotes an edge of the tree. It is guaranteed that these edges form a tree. Output Output n numbers. i-th number should be equal to the dominant index of vertex i. Examples Input 4 1 2 2 3 3 4 Output 0 0 0 0 Input 4 1 2 1 3 1 4 Output 1 0 0 0 Input 4 1 2 2 3 2 4 Output 2 1 0 0
In this problem, we can use the small-to-large merging trick (also known as DSU on trees): when building a depth array for a vertex, we first recursively build depth arrays for its children, then pull them upwards and merge them using the small-to-large technique. In various blogs on this technique, it was mentioned that this will require $O(n \log n)$ operations with the structures we use to maintain depth arrays overall. However, in this problem, we can prove a better estimate: it will require $O(n)$ operations. This is because the size of the depth array (considering only non-zero elements) for a vertex is equal to the height of its subtree, not to the number of vertices in it. To prove that the number of operations is $O(n)$, one can use the intuitive fact that when we merge two depth arrays, all elements of the smaller array are "destroyed" in the process, so if the size of the smaller array is $k$, then we require $O(k)$ operations to "destroy" $k$ elements. The main problem is that we sometimes need to "pull" our depth arrays upwards, thus inserting a $1$ to the beginning of the array. Standard arrays do not support this operation, so we need to either use something like `std::map` (and the complexity will be $O(n \log n)$), or keep the depth arrays in reversed order and handle them using `std::vector` (and then the complexity will be $O(n)$).
1009_G. Allowed Letters
[ "bitmasks", "flows", "graph matchings", "graphs", "greedy" ]
2,400
Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is yet to name the startup! Actually, Polycarp has already came up with the name but some improvement to it will never hurt. So now he wants to swap letters at some positions in it to obtain the better name. It isn't necessary for letters to be adjacent. In addition, each of the investors has chosen some index in the name and selected a set of letters that can go there. Indices chosen by different investors are pairwise distinct. If some indices aren't chosen by any investor then any letter can go there. Finally, Polycarp is sure that the smallest lexicographically name is the best. (Like why do you think Google decided to become Alphabet?) More formally, you are given a string consisting of lowercase Latin letters from "a" to "f". You can swap letters at any positions arbitrary number of times (zero swaps is also possible). What is the smallest lexicographically name you can obtain such that the letter at every position is among the allowed letters? If Polycarp can't produce any valid name then print "Impossible". Input The first line is the string s (1 ≤ |s| ≤ 10^5) — the name Polycarp has came up with. The string consists only of lowercase Latin letters from "a" to "f". The second line contains a single integer m (0 ≤ m ≤ |s|) — the number of investors. The i-th of the next m lines contain an integer number pos_i and a non-empty string of allowed characters for pos_i (1 ≤ pos_i ≤ |s|). Each string contains pairwise distinct letters from "a" to "f". pos_1, pos_2, ..., pos_m are pairwise distinct. If any position of the string doesn't appear in the investors demands then any letter can go in this position. Output If Polycarp can't produce any valid name then print "Impossible". Otherwise print the smallest lexicographically name Polycarp can obtain by swapping letters in string s such that the letter at every position is among the allowed ones. Examples Input bedefead 5 2 e 1 dc 5 b 7 ef 6 ef Output deadbeef Input abacaba 0 Output aaaabbc Input fc 2 1 cfab 2 f Output cf
The idea of solution is the following: we build the answer letter-by-letter; when choosing a character for some position, we try all possible characters and check that we can build the suffix after placing this character. But we need to somehow do this checking fast. Let's build a flow network, where we have $6$ vertices representing the characters of the string and $2^6$ vertices representing the masks of characters. Add directed edges from the source to every node representing some character with capacity equal to the number of such characters in the original string; also add directed edges from every node representing some character to all vertices representing masks where this character is contained (with infinite capacity); and finally, add a directed edge from every "mask"-node to the sink with capacity equal to the number of positions where this mask of characters is allowed. If we find maximum flow in this network, we can check that the answer exists, and if it exists, build some answer. Now let's try to build optimal answer by somehow rebuilding the flow in the network. Suppose we are trying to place a character $x$ to position containing mask $m$. To check whether we can do it, we have to try rebuilding the flow in such a way that the edge from vertex corresponding to $x$ to vertex corresponding to $m$ has non-zero flow. If it is already non-zero, then we are done; otherwise, we may cancel a unit of flow going through an edge from source to $x$-vertex, then cancel a unit of flow going through an edge from $m$-vertex to sink, decrease the capacity of these two edges by $1$ and check that there exists an augmenting path. If it exists, then returning the capacities back and adding one unit of flow through the path $source \to x \to m \to sink$ actually builds some answer where some character $x$ is placed on some position with mask $m$, so we may place it there; otherwise it's impossible. When we finally decided to place $x$ on position $m$, we have to decrease the flow through $source \to x \to m \to sink$ and the capacities of edges $source \to x$ and $m \to sink$. All this algorithm runs in $O(n \times 2^A \times A^2)$, where $A$ is the size of the alphabet.
1013_A. Piles With Stones
[ "math" ]
800
There is a beautiful garden of stones in Innopolis. Its most beautiful place is the n piles with stones numbered from 1 to n. EJOI participants have visited this place twice. When they first visited it, the number of stones in piles was x_1, x_2, …, x_n, correspondingly. One of the participants wrote down this sequence in a notebook. They visited it again the following day, and the number of stones in piles was equal to y_1, y_2, …, y_n. One of the participants also wrote it down in a notebook. It is well known that every member of the EJOI jury during the night either sits in the room 108 or comes to the place with stones. Each jury member who comes there either takes one stone for himself or moves one stone from one pile to another. We can assume that there is an unlimited number of jury members. No one except the jury goes to the place with stones at night. Participants want to know whether their notes can be correct or they are sure to have made a mistake. Input The first line of the input file contains a single integer n, the number of piles with stones in the garden (1 ≤ n ≤ 50). The second line contains n integers separated by spaces x_1, x_2, …, x_n, the number of stones in piles recorded in the notebook when the participants came to the place with stones for the first time (0 ≤ x_i ≤ 1000). The third line contains n integers separated by spaces y_1, y_2, …, y_n, the number of stones in piles recorded in the notebook when the participants came to the place with stones for the second time (0 ≤ y_i ≤ 1000). Output If the records can be consistent output "Yes", otherwise output "No" (quotes for clarity). Examples Input 5 1 2 3 4 5 2 1 4 3 5 Output Yes Input 5 1 1 1 1 1 1 0 1 0 1 Output Yes Input 3 2 3 9 1 7 9 Output No Note In the first example, the following could have happened during the night: one of the jury members moved one stone from the second pile to the first pile, and the other jury member moved one stone from the fourth pile to the third pile. In the second example, the jury took stones from the second and fourth piles. It can be proved that it is impossible for the jury members to move and took stones to convert the first array into the second array.
It can be simply shown that the answer is `Yes` if and only if the sum in the first visit is not less than the sum in the second visit.
1013_B. And
[ "greedy" ]
1,200
There is an array with n elements a1, a2, ..., an and the number x. In one operation you can select some i (1 ≤ i ≤ n) and replace element ai with ai & x, where & denotes the [bitwise and](https://en.wikipedia.org/wiki/Bitwise_operation#AND) operation. You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply. Input The first line contains integers n and x (2 ≤ n ≤ 100 000, 1 ≤ x ≤ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≤ ai ≤ 100 000), the elements of the array. Output Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible. Examples Input 4 3 1 2 3 7 Output 1 Input 2 228 1 1 Output 0 Input 3 7 1 2 3 Output -1 Note In the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move. In the second example the array already has two equal elements. In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Clearly, if it is possible, then there are no more than $2$ operations needed. So we basically need to distinguish $4$ outcomes, $-1$, $0$, $1$, and $2$. The answer is zero if there are already equal elements in the array. To check if the answer is $-1$, we can apply the operation to each element of the array. If all elements are still distinct, then it could not be helped. To check if the answer is one, we can brute-force the element $a$ to apply the operation to, and if this operation changes this element, we can check if there is an $a & x$ element in the array. In all other cases, the answer is two.
1013_C. Photo of The Sky
[ "brute force", "implementation", "math", "sortings" ]
1,500
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes. Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, where (x_1, y_1) and (x_2, y_2) are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero. After taking the photo, Pavel wrote down coordinates of n of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky. Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points. Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle. Input The first line of the input contains an only integer n (1 ≤ n ≤ 100 000), the number of points in Pavel's records. The second line contains 2 ⋅ n integers a_1, a_2, ..., a_{2 ⋅ n} (1 ≤ a_i ≤ 10^9), coordinates, written by Pavel in some order. Output Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records. Examples Input 4 4 1 3 2 3 2 1 3 Output 1 Input 3 5 8 5 5 7 5 Output 0 Note In the first sample stars in Pavel's records can be (1, 3), (1, 3), (2, 3), (2, 4). In this case, the minimal area of the rectangle, which contains all these points is 1 (rectangle with corners at (1, 3) and (2, 4)).
First, let us sort the array $a$, so we can assume that $a_1 \le a_2 \le ... \le a_{2 \times n}$. Note that the area of a rectangle with bottom-left corner at $(x_1, y_1)$ and upper-right corner at $(x_2, y_2)$ is $(x_2 - x_1) \times (y_2 - y_1)$. Thus, the task is to partition the array $a$ into two multisets (sets with equal elements) $X$ and $Y$ of size $n$, such that $(\max(X) - \min(X)) \times (\max(Y) - \min(Y))$ is minimized among all such partitions ($\min(X)$ is the minimum element in multiset $X$, and $\max(X)$ is the maximum element in multiset $X$). Let us consider such a partition. There are two cases: 1. The minimum and maximum elements are in the same multiset: Let us assume that they are both in $X$. Then, $\max(X) - \min(X) = a_{2 \times n} - a_1$. We need to minimize $\max(Y) - \min(Y)$. If the index of the minimum element in $a$ is $i$, and the index of the maximum element is $j$, then $j - i \ge n - 1$, because there are $n$ elements in $Y$. Thus, we can use $Y = {a_i, a_{i+1}, ..., a_{i+n-1}}$, and the desired difference will not increase. Therefore, it is optimal to use some segment of length $n$ as $Y$. 2. The minimum and maximum elements are not in the same multiset: Let us assume that the minimum element is in $X$, and the maximum element is in $Y$. Then, note that the maximum element in $X$ is always $\ge a_n$, because the size of $X$ is $n$. And the minimum element in $Y$ will be $\le a_{n+1}$, because the size of $Y$ is $n$. Thus, $(\max(X) - \min(X)) \times (\max(Y) - \min(Y)) \ge (a_n - a_1) \times (a_{2 \times n} - a_{n+1})$, so we can use a prefix of length $n$ as $X$ and a suffix of length $n$ as $Y$. Therefore, the answer is the minimum of $(a_{2 \times n} - a_1) \times (a_{i+n-1} - a_i)$ for each $2 \le i \le n$ and $(a_n - a_1) \times (a_{2 \times n} - a_{n+1})$. That is, we can simply check all contiguous subsets as the first set and all the remaining elements as the second set. The complexity of this algorithm is $O(n \times \log(n))$.
1013_D. Chemical table
[ "constructive algorithms", "dfs and similar", "dsu", "graphs", "matrices" ]
1,900
Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table. Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2). <image> Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions. Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase. Input The first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have. The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different. Output Print the minimal number of elements to be purchased. Examples Input 2 2 3 1 2 2 2 2 1 Output 0 Input 1 5 3 1 3 1 1 1 5 Output 2 Input 4 3 6 1 2 1 3 2 2 2 3 3 1 3 3 Output 1 Note For each example you have a picture which illustrates it. The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially. The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced. Test 1 We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything. <image> Test 2 We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements. <image> Test 3 There are several possible solutions. One of them is illustrated below. Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions. <image>
One way to solve this problem is to interpret the cells in a 2D matrix as an edge in a bipartite graph, that is, a cell $(i,j)$ is an edge between $i$ of the left part and $j$ of the right part. Note that each fusion operation (we have edges $(r_1,c_1)$, $(r_1,c_2)$, $(r_2,c_1)$ and get edge $(r_2,c_2)$) does not change the connected components of the graph. Moreover, we can prove that we can obtain each edge in the connected component by fusion. Let's examine an example edge $(x,y)$, and some path between $x$ and $y$ (since they lie in one connected component). Since the graph is bipartite, the length of this path must be odd, and it is $\ge 3$, otherwise the edge already exists. So we have this path. Take the first three edges and make the corresponding fusion, replacing these three edges with the brand new fused edge. The length of the path decreases by $2$. Repeat until the path is a mere edge. This way, the number of edges to add (cells to buy) is just the number of connected components minus one.
1013_E. Hills
[ "dp" ]
1,900
Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is 5, 4, 6, 2, then houses could be built on hills with heights 5 and 6 only. The Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build k houses, so there must be at least k hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan? However, the exact value of k is not yet determined, so could you please calculate answers for all k in range <image>? Here <image> denotes n divided by two, rounded up. Input The first line of input contains the only integer n (1 ≤ n ≤ 5000)—the number of the hills in the sequence. Second line contains n integers ai (1 ≤ ai ≤ 100 000)—the heights of the hills in the sequence. Output Print exactly <image> numbers separated by spaces. The i-th printed number should be equal to the minimum number of hours required to level hills so it becomes possible to build i houses. Examples Input 5 1 1 1 1 1 Output 1 2 2 Input 3 1 2 3 Output 0 2 Input 5 1 2 3 2 2 Output 0 1 3 Note In the first example, to get at least one hill suitable for construction, one can decrease the second hill by one in one hour, then the sequence of heights becomes 1, 0, 1, 1, 1 and the first hill becomes suitable for construction. In the first example, to get at least two or at least three suitable hills, one can decrease the second and the fourth hills, then the sequence of heights becomes 1, 0, 1, 0, 1, and hills 1, 3, 5 become suitable for construction.
The problem can be stated succinctly as follows: "We are allowed to decrease any element and must create at least $k$ local maximums. Count the minimum number of operations for all $k$." Note that any set of positions, where no positions are adjacent, can be made to be local maximums by decreasing the neighboring hills to some value. Let's introduce the following dynamic programming: Let $dp[prefix][local_maxs]$ be the minimum cost if we analyze only the given prefix, have the specified number of local maximums ("good hills to build on"), and we make a local maximum in the last hill of this prefix. A naive implementation of this leads to $O(n^2)$ states and $O(n^4)$ time, since in each state we can brute force the previous position of a local maximum ($n$) and then calculate the cost of patching the segment from the previous local maximum to the current one. A more careful analysis reveals that this is, in fact, an $O(n^3)$ solution, since on the segment only the first and last elements need to be decreased (possibly the first and last elements are the same). To obtain a full solution in $O(n^2)$, we need to optimize the dynamic programming a bit. As we noted in the previous paragraph, there is one extreme case, when the first and last elements are the same. We can handle this transition by hand in $O(1)$ for each state. Otherwise, the cost of the segment strictly between local maximums is the cost of its left part plus the cost of its right part. This seems like something we can decompose, right? Since our goal is to update the state $(prefix, local)$, the right part is now a fixed constant for all such transitions. We need to select the minimum value of $dp[i][local - 1] + cost(i, i + 1)$ where $i \le prefix - 3$. This can be done by calculating a supplementary dynamic programming table during the primary dynamic programming calculation. For example, we can calculate $f[pref][j] = \min dp[i][j] + cost(i, i + 1)$ for $i \le pref$.
1013_F. AB-Strings
[ "constructive algorithms", "strings" ]
2,800
There are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole string. Your task is to find a sequence of operations after which one of the strings consists only of a letters and the other consists only of b letters. The number of operations should be minimized. Input The first line contains a string s (1 ≤ |s| ≤ 2·105). The second line contains a string t (1 ≤ |t| ≤ 2·105). Here |s| and |t| denote the lengths of s and t, respectively. It is guaranteed that at least one of the strings contains at least one a letter and at least one of the strings contains at least one b letter. Output The first line should contain a single integer n (0 ≤ n ≤ 5·105) — the number of operations. Each of the next n lines should contain two space-separated integers ai, bi — the lengths of prefixes of s and t to swap, respectively. If there are multiple possible solutions, you can print any of them. It's guaranteed that a solution with given constraints exists. Examples Input bab bb Output 2 1 0 1 3 Input bbbb aaa Output 0 Note In the first example, you can solve the problem in two operations: 1. Swap the prefix of the first string with length 1 and the prefix of the second string with length 0. After this swap, you'll have strings ab and bbb. 2. Swap the prefix of the first string with length 1 and the prefix of the second string with length 3. After this swap, you'll have strings bbbb and a. In the second example, the strings are already appropriate, so no operations are needed.
Note that we can compress equal adjacent letters. We can then perform a dynamic programming with parameters (first letter of $s$, length of $s$, first letter of $t$, length of $t$). However, the number of transactions and even states is too large. We can write a slow, but correct solution, and examine the transactions that are made in dp. The most common transaction is to swap the first group in $s$ with the first group in $t$. However, there are special cases, such as when the first letters are the same or when the lengths are very small. Running a slow dynamic programming helps to find all the cases for the solution. Formally, the correctness of this algorithm can be proven by induction and the analysis of large cases, which we omit for clarity. Another approach is to consider different first operations, and then use a greedy algorithm. See the second solution for details. We do not prove this solution.
1015_A. Points in Segments
[ "implementation" ]
800
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints. Consider all integer points between 1 and m inclusive. Your task is to print all such points that don't belong to any segment. The point x belongs to the segment [l; r] if and only if l ≤ x ≤ r. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of segments and the upper bound for coordinates. The next n lines contain two integers each l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — the endpoints of the i-th segment. Segments may intersect, overlap or even coincide with each other. Note, it is possible that l_i=r_i, i.e. a segment can degenerate to a point. Output In the first line print one integer k — the number of points that don't belong to any segment. In the second line print exactly k integers in any order — the points that don't belong to any segment. All points you print should be distinct. If there are no such points at all, print a single integer 0 in the first line and either leave the second line empty or do not print it at all. Examples Input 3 5 2 2 1 2 5 5 Output 2 3 4 Input 1 7 1 7 Output 0 Note In the first example the point 1 belongs to the second segment, the point 2 belongs to the first and the second segments and the point 5 belongs to the third segment. The points 3 and 4 do not belong to any segment. In the second example all the points from 1 to 7 belong to the first segment.
In this problem, all you need to do is check for each point from $1$ to $m$ if it cannot belong to any segment. This can be done in $O(n \times m)$ time using two nested loops or in $O(n + m)$ time using a simple prefix sums calculation. Both solutions are presented below.
1015_B. Obtaining the String
[ "implementation" ]
1,200
You are given two strings s and t. Both strings have length n and consist of lowercase Latin letters. The characters in the strings are numbered from 1 to n. You can successively perform the following move any number of times (possibly, zero): * swap any two adjacent (neighboring) characters of s (i.e. for any i = \{1, 2, ..., n - 1\} you can swap s_i and s_{i + 1}). You can't apply a move to the string t. The moves are applied to the string s one after another. Your task is to obtain the string t from the string s. Find any way to do it with at most 10^4 such moves. You do not have to minimize the number of moves, just find any sequence of moves of length 10^4 or less to transform s into t. Input The first line of the input contains one integer n (1 ≤ n ≤ 50) — the length of strings s and t. The second line of the input contains the string s consisting of n lowercase Latin letters. The third line of the input contains the string t consisting of n lowercase Latin letters. Output If it is impossible to obtain the string t using moves, print "-1". Otherwise in the first line print one integer k — the number of moves to transform s to t. Note that k must be an integer number between 0 and 10^4 inclusive. In the second line print k integers c_j (1 ≤ c_j < n), where c_j means that on the j-th move you swap characters s_{c_j} and s_{c_j + 1}. If you do not need to apply any moves, print a single integer 0 in the first line and either leave the second line empty or do not print it at all. Examples Input 6 abcdef abdfec Output 4 3 5 4 5 Input 4 abcd accd Output -1 Note In the first example the string s changes as follows: "abcdef" → "abdcef" → "abdcfe" → "abdfce" → "abdfec". In the second example there is no way to transform the string s into the string t through any allowed moves.
This problem can be solved using the following greedy approach: Iterate over all $i$ from $1$ to $n$. If $s_i = t_i$, proceed. Otherwise, find any position $j > i$ such that $s_j = t_i$ and move the character from position $j$ to position $i$. If there is no such position in $s$, the answer is `-1`. The upper bound on the time complexity (and the size of the answer) of this solution is $O(n^2)$.
1015_C. Songs Compression
[ "sortings" ]
1,100
Ivan has n songs on his phone. The size of the i-th song is a_i bytes. Ivan also has a flash drive which can hold at most m bytes in total. Initially, his flash drive is empty. Ivan wants to copy all n songs to the flash drive. He can compress the songs. If he compresses the i-th song, the size of the i-th song reduces from a_i to b_i bytes (b_i < a_i). Ivan can compress any subset of the songs (possibly empty) and copy all the songs to his flash drive if the sum of their sizes is at most m. He can compress any subset of the songs (not necessarily contiguous). Ivan wants to find the minimum number of songs he needs to compress in such a way that all his songs fit on the drive (i.e. the sum of their sizes is less than or equal to m). If it is impossible to copy all the songs (even if Ivan compresses all the songs), print "-1". Otherwise print the minimum number of songs Ivan needs to compress. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 1 ≤ m ≤ 10^9) — the number of the songs on Ivan's phone and the capacity of Ivan's flash drive. The next n lines contain two integers each: the i-th line contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ 10^9, a_i > b_i) — the initial size of the i-th song and the size of the i-th song after compression. Output If it is impossible to compress a subset of the songs in such a way that all songs fit on the flash drive, print "-1". Otherwise print the minimum number of the songs to compress. Examples Input 4 21 10 8 7 4 3 1 5 4 Output 2 Input 4 16 10 8 7 4 3 1 5 4 Output -1 Note In the first example Ivan can compress the first and the third songs so after these moves the sum of sizes will be equal to 8 + 7 + 1 + 5 = 21 ≤ 21. Also Ivan can compress the first and the second songs, then the sum of sizes will be equal 8 + 4 + 3 + 5 = 20 ≤ 21. Note that compressing any single song is not sufficient to copy all the songs on the flash drive (for example, after compressing the second song the sum of sizes will be equal to 10 + 4 + 3 + 5 = 22 > 21). In the second example even if Ivan compresses all the songs the sum of sizes will be equal 8 + 4 + 1 + 4 = 17 > 16.
If we do not compress any songs, the sum of their sizes will be equal to $\sum_{i = 1}^{n} a_i$. Let this sum be $sum$. Now, if we compress the $j$-th song, how will $sum$ change? It will decrease by $a_j - b_j$. This suggests that the optimal way to compress the songs is to compress them in non-increasing order of $a_j - b_j$. Let us create an array $d$ of size $n$, where $d_j = a_j - b_j$. Let us sort it in non-increasing order, and then iterate over all $j$ from $1$ to $n$. If at the current step $sum \le m$, we print $j - 1$ and terminate the program. Otherwise, we set $sum := sum - d_j$. After all iterations, we have to check again if $sum \le m$. If so, we print $n$; otherwise, we print `-1`. The time complexity is $O(n \log n)$ because of sorting.
1015_D. Walking Between Houses
[ "constructive algorithms", "greedy" ]
1,600
There are n houses in a row. They are numbered from 1 to n in order from left to right. Initially you are in the house 1. You have to perform k moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current house). If you go from the house x to the house y, the total distance you walked increases by |x-y| units of distance, where |a| is the absolute value of a. It is possible to visit the same house multiple times (but you can't visit the same house in sequence). Your goal is to walk exactly s units of distance in total. If it is impossible, print "NO". Otherwise print "YES" and any of the ways to do that. Remember that you should do exactly k moves. Input The first line of the input contains three integers n, k, s (2 ≤ n ≤ 10^9, 1 ≤ k ≤ 2 ⋅ 10^5, 1 ≤ s ≤ 10^{18}) — the number of houses, the number of moves and the total distance you want to walk. Output If you cannot perform k moves with total walking distance equal to s, print "NO". Otherwise print "YES" on the first line and then print exactly k integers h_i (1 ≤ h_i ≤ n) on the second line, where h_i is the house you visit on the i-th move. For each j from 1 to k-1 the following condition should be satisfied: h_j ≠ h_{j + 1}. Also h_1 ≠ 1 should be satisfied. Examples Input 10 2 15 Output YES 10 4 Input 10 9 45 Output YES 10 1 10 1 2 1 2 1 6 Input 10 9 81 Output YES 10 1 10 1 10 1 10 1 10 Input 10 9 82 Output NO
The solution for this problem is very simple: at first, if $k > s$ or $k \times (n - 1) < s$, the answer is `NO`. Otherwise, let's do the following thing $k$ times: let $dist$ be $min(n - 1, s - k + 1)$ (we have to greedily decrease the remaining distance, but we also should remember about the number of moves which we need to perform). We have to walk to **any** possible house which is located at distance $dist$ from the current house (also don't forget to subtract $dist$ from $s$). The proof of the fact that we can always walk to the house at distance $dist$ is very simple: one of the possible answers (which is obtained by the algorithm above) will look like several moves of distance $n-1$, (possibly) one move of random distance less than $n-1$, and several moves of distance $1$. The first part of the answer can be obtained if we are staying near the leftmost or the rightmost house, and the second and third parts can always be obtained because the distances we will walk in each of these moves is less than $n-1$. Time complexity is $O(k)$.
1015_E1. Stars Drawing (Easy Edition)
[ "brute force", "dp", "greedy" ]
1,700
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed). Let's consider empty cells are denoted by '.', then the following figures are stars: <image> The leftmost figure is a star of size 1, the middle figure is a star of size 2 and the rightmost figure is a star of size 3. You are given a rectangular grid of size n × m consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from 1 to n, columns are numbered from 1 to m. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed n ⋅ m. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes. In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most n ⋅ m stars. Input The first line of the input contains two integers n and m (3 ≤ n, m ≤ 100) — the sizes of the given grid. The next n lines contains m characters each, the i-th line describes the i-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only. Output If it is impossible to draw the given grid using stars only, print "-1". Otherwise in the first line print one integer k (0 ≤ k ≤ n ⋅ m) — the number of stars needed to draw the given grid. The next k lines should contain three integers each — x_j, y_j and s_j, where x_j is the row index of the central star character, y_j is the column index of the central star character and s_j is the size of the star. Each star should be completely inside the grid. Examples Input 6 8 ....*... ...**... ..*****. ...**... ....*... ........ Output 3 3 4 1 3 5 2 3 5 1 Input 5 5 .*... ****. .**** ..**. ..... Output 3 2 2 1 3 3 1 3 4 1 Input 5 5 .*... ***.. .*... .*... ..... Output -1 Input 3 3 *.* .*. *.* Output -1 Note In the first example the output 2 3 4 1 3 5 2 is also correct.
Since we are not limited in the number of `stars` in the answer, the following solution will work. We iterate over all possible `stars` centers and try to extend the rays of the current `star` as large as possible. This can be done by a simple iteration and check in $O(n)$. If the size of the current `star` is non-zero, we add it to the answer. It is obvious that the number of `stars` in such an answer will not exceed $n \times m$. Then we try to draw all of these `stars` on the empty grid. Drawing each `star` can also be done in $O(n)$. If, after drawing, our grid is equal to the input grid, the answer is `YES` and our set of `stars` is the correct answer. Otherwise, the answer is `NO`. Time complexity: $O(n^3)$.
1015_E2. Stars Drawing (Hard Edition)
[ "binary search", "dp", "greedy" ]
1,900
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed). Let's consider empty cells are denoted by '.', then the following figures are stars: <image> The leftmost figure is a star of size 1, the middle figure is a star of size 2 and the rightmost figure is a star of size 3. You are given a rectangular grid of size n × m consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from 1 to n, columns are numbered from 1 to m. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed n ⋅ m. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes. In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most n ⋅ m stars. Input The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000) — the sizes of the given grid. The next n lines contains m characters each, the i-th line describes the i-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only. Output If it is impossible to draw the given grid using stars only, print "-1". Otherwise in the first line print one integer k (0 ≤ k ≤ n ⋅ m) — the number of stars needed to draw the given grid. The next k lines should contain three integers each — x_j, y_j and s_j, where x_j is the row index of the central star character, y_j is the column index of the central star character and s_j is the size of the star. Each star should be completely inside the grid. Examples Input 6 8 ....*... ...**... ..*****. ...**... ....*... ........ Output 3 3 4 1 3 5 2 3 5 1 Input 5 5 .*... ****. .**** ..**. ..... Output 3 2 2 1 3 3 1 3 4 1 Input 5 5 .*... ***.. .*... .*... ..... Output -1 Input 3 3 *.* .*. *.* Output -1 Note In the first example the output 2 3 4 1 3 5 2 is also correct.
The general idea of this problem is the same as in the previous problem. However, we now need to perform all the previous operations more efficiently. The solution is divided into two parts. The first part: Let's calculate four matrices of size $n \times m$ - $up$, $down$, $left$, and $right$. $up_{i, j}$ will denote the distance to the nearest dot character to the top from the current position. Similarly, $down_{i, j}$ will denote the distance to the nearest dot character to the bottom from the current position, $left_{i, j}$ to the left, and $right_{i, j}$ to the right. We can calculate all these matrices in $O(n^2)$ using simple dynamic programming. If we iterate over all possible $i$ from $1$ to $n$ and $j$ from $1$ to $m$, we can easily see that if the current character is a dot, then $up_{i, j} = left_{i, j} = 0$. Otherwise, if $i > 1$, then $up_{i, j} = up_{i - 1, j}$, and if $j > 1$, then $left_{i, j} = left_{i, j - 1}$. The remaining two matrices can be calculated in the same way as these two matrices, but we need to iterate over all $i$ from $n$ to $1$ and $j$ from $m$ to $1$. Therefore, this part of the solution runs in $O(n^2)$. After calculating all these matrices, the maximum possible length of the rays of the `star` with center in position $(i, j)$ is $min(up_{i, j}, down_{i, j}, left_{i, j}, right_{i, j}) - 1$. The second part is to draw all `star`s in $O(n^2)$. Let's calculate two more matrices of size $n \times m$ - $h$ and $v$. Let's iterate over all `star`s in our answer. Let the center of the current `star` be $(i, j)$ and its size be $s$. Let's increase $h_{i, j - s}$ by one and decrease $h_{i, j + s + 1}$ by one (if $j + s + 1 \le m$). The same with the matrix $v$. Increase $v_{i - s, j}$ and decrease $v_{i + s + 1, j}$ (if $i + s + 1 \le n$). Then let's iterate over all possible $i$ from $1$ to $n$ and $j$ from $1$ to $m$. If $i > 1$, then set $v_{i, j} := v_{i, j} + v_{i - 1, j}$, and if $j > 1$, set $h_{i, j} := h_{i, j} + h_{i, j - 1}$. How do we know whether the character at the position $(i, j)$ is an asterisk character or a dot character? If either $h_{i, j}$ or $v_{i, j}$ is greater than zero, then the character at the position $(i, j)$ in our matrix will be the asterisk character. Otherwise, it is the dot character. This part also runs in $O(n^2)$. The time complexity of the solution is $O(n^2)$.
1015_F. Bracket Substring
[ "dp", "strings" ]
2,300
You are given a bracket sequence s (not necessarily a regular one). 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. Your problem is to calculate the number of regular bracket sequences of length 2n containing the given bracket sequence s as a substring (consecutive sequence of characters) modulo 10^9+7 (1000000007). Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the half-length of the resulting regular bracket sequences (the resulting sequences must have length equal to 2n). The second line of the input contains one string s (1 ≤ |s| ≤ 200) — the string s that should be a substring in each of the resulting regular bracket sequences (|s| is the length of s). Output Print only one integer — the number of regular bracket sequences containing the given bracket sequence s as a substring. Since this number can be huge, print it modulo 10^9+7 (1000000007). Examples Input 5 ()))() Output 5 Input 3 (() Output 4 Input 2 ((( Output 0 Note All regular bracket sequences satisfying the conditions above for the first example: * "(((()))())"; * "((()()))()"; * "((()))()()"; * "(()(()))()"; * "()((()))()". All regular bracket sequences satisfying the conditions above for the second example: * "((()))"; * "(()())"; * "(())()"; * "()(())". And there is no regular bracket sequences of length 4 containing "(((" as a substring in the third example.
First, let's calculate the matrix $len$ of size $(n + 1) \times 2$. Let $len_{i, j}$ denote the maximum length of the prefix of $s$ which equals to the suffix of the prefix of $s$ of length $i$ with the additional character `(` if $j = 0$ and `)` otherwise. In other words, $len_{i, j}$ denotes the maximum length of the prefix of $s$ that we can reach if we have the prefix of $s$ of length $i$ and want to add the character `(` if $j = 0$ and `)` otherwise, and only one possible move is to remove characters from the beginning of this prefix with an additional character. This matrix can be easily calculated in $O(n^3)$ without any dynamic programming. It can also be calculated in $O(n)$ using prefix-function and dynamic programming. Now, let's calculate the following dynamic programming $dp_{i, j, k, l}$. This means that we have gained $i$ characters of the regular bracket sequence, the balance of this sequence is $j$, the last $k$ characters of the gained prefix is the prefix of $s$ of length $k$, and $l$ equals to $1$ if we obtain the full string $s$ at least once and $0$ otherwise. The stored value of the $dp_{i, j, k, l}$ is the number of ways to reach this state. Initially, $dp_{0, 0, 0, 0} = 1$, and all other values equal $0$. The following recurrence works: try to add to the current prefix the character `(` if the current balance is less than $n$, then we will move to the state $dp{i + 1, j + 1, len_{k, 0}, f~ |~ (len_{k, 0} = |s|)}$. $|s|$ is the length of $s$, and $|$ is the `OR` operation (if at least one is true then the result is true). We add to the number of ways to reach the destination state the number of ways to reach the current state. The same with the character `)`. Try to add to the current prefix the character `)` if the current balance is greater than $0$, then we will move to the state $dp{i + 1, j - 1, len_{k, 1}, f~ |~ (len_{k, 1} = |s|)}$. We also add to the number of ways to reach the destination state the number of ways to reach the current state. After calculating this dynamic programming, the answer is $\sum_{i = 0}^{|s|} dp_{2n, 0, i, 1}$. The time complexity is $O(n^3)$.
1016_A. Death Note
[ "greedy", "implementation", "math" ]
900
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?). Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly m names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page. Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from 1 to n. Input The first line of the input contains two integers n, m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 10^9) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i means the number of names you will write in the notebook during the i-th day. Output Print exactly n integers t_1, t_2, ..., t_n, where t_i is the number of times you will turn the page during the i-th day. Examples Input 3 5 3 7 9 Output 0 2 1 Input 4 20 10 9 19 2 Output 0 0 1 1 Input 1 100 99 Output 0 Note In the first example pages of the Death Note will look like this [1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.
In this problem, all we need to do is maintain the variable $res$, which will represent the number of names written on the current page. Initially, this number equals zero. The answer for the $i$-th day equals $\lfloor\dfrac{res + a_i}{m}\rfloor$. This value represents the number of full pages we will write during the $i$-th day. After answering, we need to set $res := (res + a_i) % m$, where the operation $x % y$ takes $x$ modulo $y$.
1016_B. Segment Occurrences
[ "brute force", "implementation" ]
1,300
You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a). You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i]. Input The first line contains three integer numbers n, m and q (1 ≤ n, m ≤ 10^3, 1 ≤ q ≤ 10^5) — the length of string s, the length of string t and the number of queries, respectively. The second line is a string s (|s| = n), consisting only of lowercase Latin letters. The third line is a string t (|t| = m), consisting only of lowercase Latin letters. Each of the next q lines contains two integer numbers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the arguments for the i-th query. Output Print q lines — the i-th line should contain the answer to the i-th query, that is the number of occurrences of string t in a substring s[l_i..r_i]. Examples Input 10 3 4 codeforces for 1 3 3 10 5 6 5 7 Output 0 1 0 1 Input 15 2 3 abacabadabacaba ba 1 15 3 4 2 14 Output 4 0 3 Input 3 5 2 aaa baaab 1 3 1 1 Output 0 0 Note In the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively.
Consider a naive approach: for each query $[l, r]$, iterate over positions $i \in [l, r - |m| + 1]$ and check if $s[i, i + |m| - 1] = t$. This is obviously $O(q \times n \times m)$. Now, notice that there are only $O(n)$ positions for $t$ to start from. We can calculate if there is an occurrence of $t$ starting in this position beforehand in $O(n \times m)$. Thus, we transition to an $O(q \times n)$ solution. Finally, we calculate a partial sum array over this occurrence check array and answer each query in $O(1)$. Overall complexity: $O(n \times m + q)$.
1016_D. Vasya And The Matrix
[ "constructive algorithms", "flows", "math" ]
1,800
Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed! Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1, b2, ..., bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively. Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix. Input The first line contains two numbers n and m (2 ≤ n, m ≤ 100) — the dimensions of the matrix. The second line contains n numbers a1, a2, ..., an (0 ≤ ai ≤ 109), where ai is the xor of all elements in row i. The third line contains m numbers b1, b2, ..., bm (0 ≤ bi ≤ 109), where bi is the xor of all elements in column i. Output If there is no matrix satisfying the given constraints in the first line, output "NO". Otherwise, on the first line output "YES", and then n rows of m numbers in each ci1, ci2, ... , cim (0 ≤ cij ≤ 2·109) — the description of the matrix. If there are several suitable matrices, it is allowed to print any of them. Examples Input 2 3 2 9 5 3 13 Output YES 3 4 5 6 7 8 Input 3 3 1 7 6 2 15 12 Output NO
If $a_1 \oplus a_2 \oplus ... \oplus a_n \ne b_1 \oplus b_2 \oplus ... \oplus b_m$, then there is no suitable matrix. The operation $\oplus$ denotes xor. Otherwise, we can always construct a suitable matrix by the following method: the first element of the first row will be equal to $a_1 \oplus b_2 \oplus b_3 \oplus ... \oplus b_m$. The second element of the first row is $b_2$, the third element is $b_3$, and the last one is $b_m$. The first element of the second row will be $a_2$, the first element of the third row is $a_3$, and the first element of the last row is $a_n$. The rest of the elements will be zero. It is not difficult to verify that the matrix obtained satisfies all the restrictions.
1016_G. Appropriate Team
[ "bitmasks", "math", "number theory" ]
2,700
Since next season are coming, you'd like to form a team from two or three participants. There are n candidates, the i-th candidate has rank a_i. But you have weird requirements for your teammates: if you have rank v and have chosen the i-th and j-th candidate, then GCD(v, a_i) = X and LCM(v, a_j) = Y must be met. You are very experienced, so you can change your rank to any non-negative integer but X and Y are tied with your birthdate, so they are fixed. Now you want to know, how many are there pairs (i, j) such that there exists an integer v meeting the following constraints: GCD(v, a_i) = X and LCM(v, a_j) = Y. It's possible that i = j and you form a team of two. GCD is the greatest common divisor of two number, LCM — the least common multiple. Input First line contains three integers n, X and Y (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ X ≤ Y ≤ 10^{18}) — the number of candidates and corresponding constants. Second line contains n space separated integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}) — ranks of candidates. Output Print the only integer — the number of pairs (i, j) such that there exists an integer v meeting the following constraints: GCD(v, a_i) = X and LCM(v, a_j) = Y. It's possible that i = j. Examples Input 12 2 2 1 2 3 4 5 6 7 8 9 10 11 12 Output 12 Input 12 1 6 1 3 5 7 9 11 12 10 8 6 4 2 Output 30 Note In the first example next pairs are valid: a_j = 1 and a_i = [2, 4, 6, 8, 10, 12] or a_j = 2 and a_i = [2, 4, 6, 8, 10, 12]. The v in both cases can be equal to 2. In the second example next pairs are valid: * a_j = 1 and a_i = [1, 5, 7, 11]; * a_j = 2 and a_i = [1, 5, 7, 11, 10, 8, 4, 2]; * a_j = 3 and a_i = [1, 3, 5, 7, 9, 11]; * a_j = 6 and a_i = [1, 3, 5, 7, 9, 11, 12, 10, 8, 6, 4, 2].
First, $X | Y$ must be satisfied (since $X | v$ and $v | Y$). Now let $Y = p_1^{py_1} p_2^{py_2} ... p_z^{py_z}$ and $X = p_1^{px_1} p_2^{px_2} ... p_z^{px_z}$. From now on, let us consider only $p_k$ such that $px_k < py_k$. Now, let us look at $a_i$: $X | a_i$ must be satisfied. Let $a_i = p_1^{pa_1} p_2^{pa_2} ... p_l^{pa_l} \times a'$. Since $GCD(v, a_i) = X$, if $pa_k > px_k$, then $v$ must have $p_k$ to the power of $px_k$ in its factorization; otherwise, the power of $p_k$ can be any non-negative integer $\ge px_k$. This leads us to the bitmask of restrictions $min_i$ ($min_i[k] = (pa_k > px_k)$) with size equal to the number of different prime divisors of $Y$. In the same way, let us process $a_j$. Of course, $a_j | Y$ and if $pa_k < py_k$, then $v$ must have $p_k$ to the power of $py_k$ in its factorization. This is another restriction bitmask $max_j$ ($max_j[k] = (pa_k < py_k)$). Therefore, for any pair $(i, j)$, there exists $v$ if and only if $min_i \land max_j = 0$. Since we look only at $p_k$ where $px_k < py_k$, then $v$ cannot have the power of $p_k$ equal to $px_k$ and $py_k$ at the same time. For any other $p$, it is enough to have the power of $p$ in $v$ equal to the power of $p$ in $Y$ (even if it is equal to $0$). Therefore, for each $max_j$, we need to know the number of $a_i$ such that $min_i$ is a submask of $\neg max_j$. So, we just need to calculate the sum of submasks for each mask; this can be done with $O(n \times 2^n)$ or $O(3^n)$. Finally, how to factorize the number $A$ up to $10^{18}$. Of course, `Pollard's algorithm` helps, but there is another way, which works sometimes. Let us factorize $A$ with primes up to $10^6$. So, after that, if $A > 1$, there are only three cases: $A = p$, $A = p^2$, or $A = p \times q$. $A = p^2$ is easy to check (use `sqrtl` function in C++). Otherwise, just check $GCD$ with all $a_i$, $X$, and $Y$: if you have found $GCD \ne 1$ and $GCD \ne A$, then $A = p \times q$ and you have found $p$. Otherwise, you can assume that $A = p$, because this probable mistake does not break anything in this task. The resulting complexity is $O(A^{\dfrac{1}{3}} + n \log{A} + z \times 2^z)$, where $z$ is the number of prime divisors of $Y$ $(z \le 15)$.
1017_A. The Rank
[ "implementation" ]
800
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 ≤ n ≤ 1000) — the number of students. Each of the next n lines contains four integers a_i, b_i, c_i, and d_i (0≤ a_i, b_i, c_i, d_i≤ 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.
For each student, add his/her $4$ scores together and count how many students have strictly lower scores than Thomas. Complexity: $O(n)$ or $O(n \log n)$.
1017_B. The Bits
[ "implementation", "math" ]
1,200
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](https://en.wikipedia.org/wiki/Bitwise_operation#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… 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≤ n≤ 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).
Let $t_{xy}$ be the number of indexes $i$ such that $a_i=x$ and $b_i=y$. The answer is $t_{00}\times t_{10} + t_{00}\times t_{11} + t_{01}\times t_{10}$.

Competitive Programming Editorials Dataset

This dataset provides a collection of competitive programming problem editorials sourced from Codeforces. Each entry includes essential details about the problem, such as tags, difficulty rating, and a comprehensive editorial written in Markdown format for clear readability.

Dataset Details

The dataset includes the following fields:

  • name: The title or name of the problem.
  • tags: Relevant tags associated with the problem, like algorithms, data structures, or specific concepts.
  • rating: The difficulty rating of the problem, based on Codeforces’ rating system.
  • description: A concise description of the problem.
  • editorial: The cleaned and formatted editorial written in Markdown. These editorials provide step-by-step explanations and solutions to the problems.

Source

The problems and editorials are sourced from:

  • Codeforces: A platform known for regular competitive programming contests and a diverse range of problem difficulty.

Format

All editorials are written in Markdown for enhanced readability and easy integration with Markdown viewers or editors.

Example Entry

{
  "name": "1000_A. Codehorses T-shirts",
  "tags": ["greedy", "implementation"],
  "rating": 1200,
  "description": "Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners...",
  "editorial": "First, let us remove all coinciding entries of both lists. The most convenient way to do this is to use a `map` or `hashmap`, but it is not the only option..."
}

Usage

This dataset can be used for fine-tuning LLM to solve competitive programming.

License

Please refer to the dataset's licensing terms on the platform where it is hosted.

Acknowledgments

A special thanks to the creators of Codeforces for their platform, which makes this resource possible. This dataset aims to provide clean, well-formatted editorials for educational purposes.


Downloads last month
11
Edit dataset card