contest_id
stringlengths
1
4
index
stringclasses
43 values
title
stringlengths
2
63
statement
stringlengths
51
4.24k
tutorial
stringlengths
19
20.4k
tags
listlengths
0
11
rating
int64
800
3.5k
code
stringlengths
46
29.6k
722
F
Cyclic Cipher
You are given $n$ sequences. Each sequence consists of positive integers, not exceeding $m$. All integers in one sequence are distinct, but the same integer may appear in multiple sequences. The length of the $i$-th sequence is $k_{i}$. Each second integers in each of the sequences are shifted by one to the left, i.e. integers at positions $i > 1$ go to positions $i - 1$, while the first integers becomes the last. Each second we take the first integer of each sequence and write it down to a new array. Then, for each value $x$ from $1$ to $m$ we compute the longest \textbf{segment} of the array consisting of element $x$ only. The above operation is performed for $10^{100}$ seconds. For each integer from $1$ to $m$ find out the longest segment found at this time.
Let's solve the problem for a particular number $X$. Without loss of generality, we assume that $X$ appeared in each sequence. If not, then the whole sequence is divided into contigous subsegments, for which above statement is true, and the answer for the number $X$ is equal to the maximum of the answers for these subsegments. Let's denote as $p_{i}$ the position (from $0$ to $k_{i}$ - 1) of $X$ in the $i$-th sequence. Then the number $X$ occures in the new array at position $i$ in the seconds equal to $p_{i} + l * k_{i}$. This condition can be rewritten as follows: the number $X$ occures at position $i$ on the $S$-th second, if $S \equiv p_{i} (mod k_{i})$. Thus, to determine whether the number $X$ occurs at some point in all positions from $i$ to $j$, you need to determine whether there is a solution for a system of equations: $\left\{{\begin{array}{l}{S\equiv p_{i}\ (m o d\ k_{i})}\\ {\cdot\cdot}\\ {S\equiv p_{j}\ (m o d\ k_{j})}\end{array}}\right.$ Suppose that we are able to quickly answer to such queries for arbitrary $i$ and $j$. Then the problem can be solved, for example, using two pointers. We will move the left boundary of the subsegment, and for fixed left boundary, we will move the right boundary as far as possible, until the solution of the corresponding system still exists. We can solve a system of equations for any subsegment in $O(log LCM)$ time per query using $O(n log n log LCM)$ precalculation in the following way: To begin with, we note that the set of solutions of this system is either empty or it itself can be represented in the same form $S \equiv p (mod k)$, where $k = LCM(k_{i}, k_{i + 1}, ..., k_{j})$. We will find the solutions of the systems for the following subsegments: for each $i$ and for each $j = 0, ..., log n$, we will take subsegment $(i, i + 2^{j} - 1)$. For each such subsegment we can find the solution of the corresponding system using $O(log LCM)$ time by solving a system consisting of two equations obtained from each of the halves of this subsegment. We can solve a system consisting of two equations using the Chinese remainder theorem. Now, to find a solution for any subsegment, it is enough to take two subsegments presented above, that their union is equal to the initial subsegment, and again solve a system of two equations. The resulting complexity of the solution is $O(n log n log LCM)$. Since the lengths of the sequences does not exceed 40, the resulting LCM can be upper bounded by 10^16. Since the total length of all sequences is $O(n)$, the total complexity of the solution for all the numbers remains the same.
[ "chinese remainder theorem", "data structures", "implementation", "number theory", "two pointers" ]
2,800
null
723
A
The New Year: Meeting Friends
There are three friend living on the straight line $Ox$ in Lineland. The first friend lives at the point $x_{1}$, the second friend lives at the point $x_{2}$, and the third friend lives at the point $x_{3}$. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year? It's guaranteed that the optimal answer is always integer.
To solve this problem you need to understand that friends must meet in the middle point of the given points, so friends who live in the leftmost and in the rightmost points must go to the middle point. Because of that the answer equals to $max(x_{1}, x_{2}, x_{3}) - min(x_{1}, x_{2}, x_{3})$.
[ "implementation", "math", "sortings" ]
800
null
723
B
Text Document Analysis
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters. In this problem you should implement the similar functionality. You are given a string which only consists of: - uppercase and lowercase English letters, - underscore symbols (they are used as separators), - parentheses (both opening and closing). It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested. For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)". Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds: - the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses), - the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
It is an implementation problem. Let's store in the variable $cnt$ the number of words inside brackets and in the variable $maxL$ - the maximum length of the word outside brackets. You can add the symbol <<_>> to the end of the given string, to correctly process the last word. Let's iterate through the given string from the left to the right and store in the variable $cur$ the current word. Also in the variable $bal$ we need to store balance of the open and close brackets. If the current symbol is letter - add it to the end of the string $cur$ and go to the next symbol of the given string. If the current symbol is open bracket, make $bal = bal + 1$. If the current symbol is close bracket, make $bal = bal - 1$. After that if $cur$ is non-empty string add 1 to $cnt$ if $bal$ equals to $1$. Else if $bal$ equals to $0$ update $maxL$ with length of the string $cur$. After that we need to assign $cur$ to the empty string and go to the next symbol of the given string.
[ "expression parsing", "implementation", "strings" ]
1,100
null
723
C
Polycarp at the Radio
Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is a band, which performs the $i$-th song. Polycarp likes bands with the numbers from $1$ to $m$, but he doesn't really like others. We define as $b_{j}$ the number of songs the group $j$ is going to perform tomorrow. Polycarp wants to change the playlist in such a way that the minimum among the numbers $b_{1}, b_{2}, ..., b_{m}$ will be as large as possible. Find this maximum possible value of the minimum among the $b_{j}$ ($1 ≤ j ≤ m$), and the minimum number of changes in the playlist Polycarp needs to make to achieve it. One change in the playlist is a replacement of the performer of the $i$-th song with any other group.
It is easy to understand that we always can get the maximum value of the minimum of the values $b_{j}$ which equals to $n / m$. So, we need to make vector $can$ which will store positions of the given array in which we will change values. At first it is all positions of the given array, in which the values are more than $m$. Then we need to store for all $i$ from 1 to $m$ in vectors $pos_{i}$ the positions of the given array, in which the bands equal to $i$. Then for every vector, which size is more than $n / m$ we need to add tje first $sz(pos_{i}) - (n / m)$ elements in the vector $can$, where $sz(pos_{i})$ is the size of the vector $pos_{i}$. After that we need to iterate through the numbers of bands from 1 to $m$. If $sz(pos_{i})$ is less than $n / m$ we need to take regular $(n / m) - sz(pos_{i})$ positions from the vector $can$ and change the values in this positions to $i$. In the same time we need to count the number of changes in the playlist.
[ "greedy" ]
1,600
null
723
D
Lakes in Berland
The map of Berland is a rectangle of the size $n × m$, which consists of cells of size $1 × 1$. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell. You task is to fill up with the earth the minimum number of water cells so that there will be \textbf{exactly} $k$ lakes in Berland. Note that the initial number of lakes on the map is \textbf{not less} than $k$.
To solve this problem we need to find all connected components consisting of dots, which do not have common border with ocean. For that we need to implement depth search which returns vector of the points from which the current connected component consists. Then we need to sort all connected components in order of increasing of their sizes and changes all dots on asterisks in components, beginning from the component with minimum size, until the number of left components does not equals to $k$.
[ "dfs and similar", "dsu", "graphs", "greedy", "implementation" ]
1,600
null
723
E
One-Way Reform
There are $n$ cities and $m$ two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads. The road minister decided to make a reform in Berland and to orient all roads in the country, i.e. to make each road one-way. The minister wants to \textbf{maximize} the number of cities, for which the number of roads that begins in the city \textbf{equals} to the number of roads that ends in it.
Let's solve this problem for each connected component separately. At first we need to understand fact that in each connected component there are even number of vertices with odd degree. Let in the current connected component there are $k$ vertices with odd degree and they have numbers $o_{1}, o_{2}, ..., o_{k}$. Then we need to add in graph non-directional edges $(o_{1}, o_{2})$, $(o_{3}, o_{4})$, $...$ $(o_{k - 1}, o_{k})$. So in the current component now all vertices have even degree and there is exist Euler cycle, which we need to find and orientate all edges in the order of this cycle. It is easy to show that after that for all vertices which had even degree before we added the edges in-degree is equal to out-degree. In the other words, we show that the maximum number of vertices with equal in- and out-degrees in orientated graph equals to the number of vertices with even degree in non-orientated graph. After we found Euler cycles for all connected components we need to print orientation of the edges and be careful and do not print edges which we added to the graph to connect vertices with odd degrees.
[ "constructive algorithms", "dfs and similar", "flows", "graphs", "greedy" ]
2,200
null
723
F
st-Spanning Tree
You are given an undirected connected graph consisting of $n$ vertices and $m$ edges. There are no loops and no multiple edges in the graph. You are also given two distinct vertices $s$ and $t$, and two values $d_{s}$ and $d_{t}$. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex $s$ doesn't exceed $d_{s}$, and the degree of the vertex $t$ doesn't exceed $d_{t}$, or determine, that there is no such spanning tree. The spanning tree of the graph $G$ is a subgraph which is a tree and contains all vertices of the graph $G$. In other words, it is a connected graph which contains $n - 1$ edges and can be obtained by removing some of the edges from $G$. The degree of a vertex is the number of edges incident to this vertex.
At first lets delete vertices $s$ and $t$ from the graph, find all connected components in the remaining graph and build for every component any spanning trees. Now we need to add in spanning tree vertices $s$ and $t$. At first let add edges from $s$ to all components, which have no edges to $t$. Then let add edges from $t$ to all components, which have no edges to $s$. If after that the degree of $s$ became more than $d_{s}$ or the degree of $t$ became more than $d_{t}$ answer does not exist. Now we have components which have edges and to $s$ and to $t$. Also currently we have two spanning trees which does not connect. Let's choose how to connect them - with vertex $s$, with vertex $t$ or with both of them (only if we have in the graph an edge ${s, t}$). For each option we need to greedily connect remaining components (if it is possible for current option). If we done it for any option we need only to print the answer.
[ "dsu", "graphs", "greedy", "implementation" ]
2,300
null
724
A
Checking the Calendar
You are given names of two days of the week. Please, determine whether it is possible that during some \textbf{non-leap year} the first day of some month was equal to the first day of the week you are given, while the first day of \textbf{the next month} was equal to the second day of the week you are given. \textbf{Both months should belong to one year}. In this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. The number of days in months during any non-leap year is: $31$, $28$, $31$, $30$, $31$, $30$, $31$, $31$, $30$, $31$, $30$, $31$. Names of the days of the week are given with lowercase English letters: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".
Days of the week in two adjacent months may either be the same (in February and March), or differ by two (in April and May) or differ by three (in January and February). Also, it was necessary to pay attention to direction of that difference (monday and tuesday is not the same as tuesday and monday).
[ "implementation" ]
1,000
null
724
B
Batch Sort
You are given a table consisting of $n$ rows and $m$ columns. Numbers in each row form a permutation of integers from $1$ to $m$. You are allowed to pick two elements in one row and swap them, but \textbf{no more than once} for each row. Also, \textbf{no more than once} you are allowed to pick two columns and swap them. Thus, you are allowed to perform from $0$ to $n + 1$ actions in total. \textbf{Operations can be performed in any order}. You have to check whether it's possible to obtain the identity permutation $1, 2, ..., m$ in each row. In other words, check if one can perform some of the operation following the given rules and make each row sorted in increasing order.
Order of swaps of numbers in each row is not important. In fact, the order is not important even when we will swap the entire columns (because we can always change the swaps in the rows so that the result will remain the same). Therefore we can choose columns which we will swap (or choose not to swap them at all), and then for each row check if we can arrange the numbers in ascending order using only one swap. This can be done by checking that all the numbers, except for maybe two of them, are already standing in their places.
[ "brute force", "greedy", "implementation", "math" ]
1,500
null
724
C
Ray Tracing
There are $k$ sensors located in the rectangular room of size $n × m$ meters. The $i$-th sensor is located at point $(x_{i}, y_{i})$. All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points $(0, 0)$ and $(n, m)$. Walls of the room are parallel to coordinate axes. At the moment $0$, from the point $(0, 0)$ the laser ray is released in the direction of point $(1, 1)$. The ray travels with a speed of ${\sqrt{2}}$ meters per second. Thus, the ray will reach the point $(1, 1)$ in exactly one second after the start. When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops. For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print $ - 1$ for such sensors.
Let's simulate the flight of the beam. It can be seen that for any segment between two successive reflections is true that the sum of the coordinates for each point of this segment is constant or the difference of the coordinates is constant. Thus, we can make lists of sensors for each possible sum and difference of coordinates. Then, when we process the segment of the beam trajectory, we can take all the points from the corresponding list and update result for them. This solution works fast, because each point is passed by the beam (and therefore viewed by us) not more than two times.
[ "greedy", "hashing", "implementation", "math", "number theory", "sortings" ]
1,800
null
724
D
Dense Subsequence
You are given a string $s$, consisting of lowercase English letters, and the integer $m$. One should choose some symbols from the given string so that any contiguous subsegment of length $m$ has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves. Then one uses the chosen symbols to form \textbf{a new string}. All symbols from the chosen position should be used, but we are allowed to rearrange them in any order. Formally, we choose a subsequence of indices $1 ≤ i_{1} < i_{2} < ... < i_{t} ≤ |s|$. The selected sequence must meet the following condition: for every $j$ such that $1 ≤ j ≤ |s| - m + 1$, there must be at least one selected index that belongs to the segment $[j,  j + m - 1]$, i.e. there should exist a $k$ from $1$ to $t$, such that $j ≤ i_{k} ≤ j + m - 1$. Then we take any permutation $p$ of the selected indices and form a new string $s_{ip1}s_{ip2}... s_{ipt}$. Find the lexicographically smallest string, that can be obtained using this procedure.
It is not hard to see that if we choose some subset of the letters then to achieve lexicographically smallest string you must first write all of the letters 'a', then all of the letters 'b' and so on. Let's assume that the string in the answer consists only of the letters 'a'. Then it should be as small of them as possible to get lexicographically smallest string. We can check whether it is enough to take only the letters 'a' to meet the requirement on the density of the indices (in each subsegment of length $m$ it has to be at least one letter 'a'). If this is true, we can find the minimum number of letters 'a', which will satisfy the density requirement, using the greedy algorithm (every time we will take the rightmost letter 'a', which is separated from the previous one by no more than $m$ positions). If this is not true, then the answer must contain some other letters except for 'a'. This means that we need to take as much 'a' letters as possible. So we can take all of them, because adding any additional letter will not affect the density requirement. Then do the same with the letter 'b', bearing in mind that all of the letters 'a' is already taken. If the letters 'b' is not enough, then take all of the letters 'a', all of the letters 'b' and proceed to the next letter, and so on.
[ "data structures", "greedy", "strings" ]
1,900
null
724
E
Goods transportation
There are $n$ cities located along the one-way road. Cities are numbered from $1$ to $n$ in the direction of the road. The $i$-th city had produced $p_{i}$ units of goods. No more than $s_{i}$ units of goods can be sold in the $i$-th city. For each pair of cities $i$ and $j$ such that \textbf{$1 ≤ i < j ≤ n$} you can \textbf{no more than once} transport \textbf{no more than} $c$ units of goods from the city $i$ to the city $j$. Note that goods can only be transported from a city with a lesser index to the city with a larger index. \textbf{You can transport goods between cities in any order.} Determine the maximum number of produced goods that can be sold in total in all the cities after a sequence of transportations.
Build a network of the following form: The network will consist of $n + 2$ vertices, the source located at the node with the number $n + 1$ and the sink at the node with the number $n + 2$. For each node $i$ such that $1 \le i \le n$ add the arc $(n + 1, i)$ with a capacity $p_{i}$ and arc $(i, n + 2)$ with capacity $s_{i}$. Also, for each pair of nodes $i$ and $j$ such that $1 \le i < j \le n$, add the arc $(i, j)$ with capacity $m$. The value of the maximum flow in this network is the answer to the problem. Since the network contains $O(n^{2})$ arcs, the usual flow search algorithms is not applicable here. Instead, we will find a capacity of the minimal cut in this network. The cut in this case is a partition of the set of all nodes from $1$ to $n + 2$ into two parts. Let $A$ be the part that contains the source and $B=\{1,2,\cdot\cdot\cdot,n,n+1,n+2\}\setminus A$ - all other nodes. Then the capacity of the cut is equal to $\sum_{i\in A}s_{i}+\sum_{i\in B}p_{i}+\sum_{i<j,i\in A,j\in B}c$. Capacity of the minimal cut can be found using the following dynamic programming: $cut(i, j)$ will be the minimum capacity of the cut, which was built on the first $i$ nodes, such that the set $A$ contains exactly $j$ nodes other than the source. It is easy to get the formula for this dynamic: $cut(i, j) = min(cut(i - 1, j - 1) + s_{i}, cut(i - 1, j) + p_{i} + j * c)$. The answer to the problem can be obtained as $min_{j = 0, n} cut(n, j)$. The resulting complexity of this solution is $O(n^{2})$. To fit in memory limit you should store only two consecutive rows during the computation of the dynamic.
[ "dp", "flows", "greedy" ]
2,900
null
724
F
Uniformly Branched Trees
A tree is a connected graph without cycles. Two trees, consisting of $n$ vertices each, are called isomorphic if there exists a permutation $p: {1, ..., n} → {1, ..., n}$ such that the edge $(u, v)$ is present in the first tree if and only if the edge $(p_{u}, p_{v})$ is present in the second tree. Vertex of the tree is called internal if its degree is greater than or equal to two. Count the number of different non-isomorphic trees, consisting of $n$ vertices, such that the degree of each internal vertex is \textbf{exactly} $d$. Print the answer over the given prime modulo $mod$.
At first, we will calculate the following dynamic programming: $trees(i, j, k)$ will be the number of rooted trees, where the root has exactly $j$ directed subtrees, the maximum size of which does not exceed $k$, and the degree of internal vertices is equal to $d$ (except for the root). Calculation of the value of the dynamics for fixed parameters is divided into two cases: there are on subtrees of size $k$ at all. In this case, you can take the value of $trees(i, j, k - 1)$; there are $t > 0$ subtrees of size $k$. In this case, we got $t r e e s(i-t\ast k,\ j-t,\ k-1)\ast\left({}^{t r e e s(k,\ d-1,\ k-1)+t-1}\right)$ different trees. The main idea here is that we do not distinguish trees that differ only by a permutation of the sons for some vertices (this is where the number of combinations come from). It's enough to set some order in which we will place the sons of all vertices. In this case, they are arranged in the order of ascending sizes and the index number of its subtrees (all the trees of fixed size can be written in one big list and enumerated). Now we need to count the number of unrooted trees. Let's get rid of this restriction, by rooting all the trees using some vertex. For this vertex, we will take the centroid (the vertex, after removing which, the tree splits into connected components, with the sizes not larger than the half of the original size of the tree). The advantage of this choice is that any tree always have either one or two centroids. The number of trees that have exactly one centroid is equal to $t r e e s(n,\ d,\lfloor{\frac{n}{2}}\rfloor))$. The fact that we chose the centroid, implies that the size of subtrees cannot exceed $\textstyle{\left|{\frac{n}{2}}\right|}$. The number of trees that have exactly two centroids is equal to $\left(t r e e s({\frac{n}{2}},\ d{-1},\ \ {\frac{n}{2}}-1)+1\right)$ if $n$ is divisible by $2$, and zero otherwise. If there are two centroids, they will be connected by an edge, and the removing of this edge will split the graph into two parts, each of which will contain exactly $\frac{n t}{2}$ vertices. The resulting complexity of this solution is $O(n^{2} * d^{2})$.
[ "combinatorics", "dp", "trees" ]
2,700
null
724
G
Xor-matic Number of the Graph
You are given an undirected graph, constisting of $n$ vertices and $m$ edges. Each edge of the graph has some non-negative integer written on it. Let's call a triple $(u, v, s)$ \textbf{interesting}, if $1 ≤ u < v ≤ n$ and there is a path (\textbf{possibly non-simple}, i.e. it can visit the same vertices and edges multiple times) between vertices $u$ and $v$ such that xor of all numbers written on the edges of this path is equal to $s$. \textbf{When we compute the value s for some path, each edge is counted in xor as many times, as it appear on this path.} It's not hard to prove that there are finite number of such triples. Calculate the sum over modulo $10^{9} + 7$ of the values of $s$ over all \textbf{interesting} triples.
Without loss of generality, let's assume that the graph is connected. If not, we will calculate the answer for each connected component and then sum them up. Let's choose two arbitrary vertices $u$ and $v$ such that $u < v$ and try to find all the interesting triples of the form $(u, v, ...)$. Let's find any path $p_{0}$, connecting these two vertices and calculate the xor of the numbers written on the edges of the path. Let's denote the obtained xor as $s_{0}$. Then take an arbitrary interesting triple $(u, v, s_{1})$ and any path $p_{1}$, with the xor of the numbers on it equals to $s_{1}$. Consider the cycle of the following form: let's go through the first path $p_{0}$, and then through the reversed direction of the second path $p_{1}$. Thus, we will get a cycle containing the vertex $u$, with the xor of the numbers on it equals to $s_{0}\oplus s_{1}$. On the other hand, we can take any cycle which starts and ends in the vertex $u$, with the xor of the numbers on it equals to $s_{2}$, and insert it before the path $p_{0}$. Thus, we will get the path $p_{2}$, with the xor of the numbers on it equals to $s_{0}\oplus s_{2}$, i.e. we will get an interesting triple $(u,\ v,\ s_{0}\oplus s_{2})$. Note that in the same manner we can add cycle, that doesn't pass through the vertex $u$. To do this, we can find any path from the vertex $u$ to some of the vertices of the cycle, then go through the cycle itself, and then add the edges of same path in reversed order. As a result, all the edges of this path will be included in the resulting path twice and will not affect the resulting xor. From this we get the following idea: for a fixed pair of vertices, we can find some path between them, and then add different cycles to it to obtain all interesting triples. Basis of the cycle space of the graph can be obtained as follows: we find some spanning tree, and then for each edge, which is not included in that tree, add the cycle containing this edge and the path in the tree connecting its endpoints to the basis. For each cycle of the basis we will find xor of the numbers written in its edges. Now, let's move from the operation of taking xor of numbers to the operations with vectors. To do this, we can represent all the numbers in the graph in the form of vectors of length $60$, where $i$-th element of the vector will be equal to the value of the $i$-th bit in this number. Then taking xor of two numbers will be reduced to the addition of two vectors over the modulo $2$. As a result, we can move from cycle space of the graph to the space $\mathbb{Z}_{2}^{00}$. A linear combination of cycles of the graph, gives us a linear combination of vectors corresponding to xor of the numbers on the edges of the cycles. The set of linear combinations of the vectors form a subspace of $\mathbb{Z}_{2}^{00}$. We can find the basis of this subspace using Gaussian elimination. Let's denote the dimension of the basis as $r$. Then, for every pair of vertices $u$ and $v$, the amount of interest triples for these vertices is equal to $2^{r}$, and all values of the parameter $s$ for these triples can be obtained by adding the vector corresponding to an arbitrary path between these vertices to the described subspace. Let's choose a pair of vertices $u$ and $v$ and some bit $i$ and count how many times the value of $2^{i}$ will appear in the resulting sum. Let's assume that the value of the $i$-th bit on the path between the chosen vertices is equal to $b$. If $i$-th bit is equal to one for at least one vector of the basis, then this bit will be equal to one in the $2^{r - 1}$ triples. Otherwise, $i$-th bit in all the $2^{r}$ triples will be equal to $b$. Let's start the depth first search from some vertex fixed vertex $r$, and find a paths to each vertex of the graph. For each of this paths we calculate the value of xor of the numbers on them. For each bit $i$ let's count how many times it was equal to zero and one on these paths (denote this numbers $zero_{i}$ and $one_{i}$). Then, for a fixed bit $i$, for exactly $zero_{i} * one_{i}$ pairs of vertices it will be equal to one on the path connecting this vertices, and for $\ (t^{c e r o_{i}})+\binom{o n e_{i}}{2})$ pairs it will be zero. Thus, if the $i$-th bit is equal to one in at least one vector from the basis, we should add $2^{i}*{\binom{n}{2}}*2^{r-1}$ to the answer. In the other case, if bits $i$ is equal to zero for all vectors from the basis, we should add $2^{i} * zero_{i} * one_{i} * 2^{r}$ to the answer. The resulting complexity of this solution is $O(m * log 10^{18})$.
[ "bitmasks", "graphs", "math", "number theory", "trees" ]
2,600
null
725
A
Jumping Ball
In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of $n$ bumpers. The bumpers are numbered with integers from $1$ to $n$ from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position $i$ it goes one position to the right (to the position $i + 1$) if the type of this bumper is '>', or one position to the left (to $i - 1$) if the type of the bumper at position $i$ is '<'. If there is no such position, in other words if $i - 1 < 1$ or $i + 1 > n$, the ball falls from the game field. Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.
Let's divide the sequence into three parts: a sequence (possibly, empty) of '<' bumpers in the beginning, a sequence (possibly, empty) of '>' bumpers in the end, and a sequence (possibly, empty) of any type bumpers between the first and the second parts. It can be easily seen that if the ball starts in the left part, it falls from the left side; if the ball starts in the right part, it falls from the right side; if the ball starts anywhere in the middle part, it never reaches the other parts and doesn't fall from the field. Thus, the answer is the number of '<' bumpers in the beginning plus the number of '>' bumpers in the end. The complexity of the solution is $O(n)$.
[ "implementation" ]
1,000
null
725
B
Food on the Plane
A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with $1$ from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats 'd', 'e' and 'f' are located to the right. Seats 'a' and 'f' are located near the windows, while seats 'c' and 'd' are located near the aisle. It's lunch time and two flight attendants have just started to serve food. They move from the first rows to the tail, always maintaining a distance of two rows from each other because of the food trolley. Thus, at the beginning the first attendant serves row $1$ while the second attendant serves row $3$. When both rows are done they move one row forward: the first attendant serves row $2$ while the second attendant serves row $4$. Then they move three rows forward and the first attendant serves row $5$ while the second attendant serves row $7$. Then they move one row forward again and so on. Flight attendants work with the same speed: it takes exactly $1$ second to serve one passenger and $1$ second to move one row forward. Each attendant first serves the passengers on the seats to the right of the aisle and then serves passengers on the seats to the left of the aisle (if one looks in the direction of the cockpit). Moreover, they always serve passengers in order from the window to the aisle. Thus, the first passenger to receive food in each row is located in seat 'f', and the last one — in seat 'c'. Assume that all seats are occupied. Vasya has seat $s$ in row $n$ and wants to know how many seconds will pass before he gets his lunch.
The only observation one has to make to solve this problem is that flight attendants move $4$ rows forward at $16$ seconds. Here, $6$ seconds are required to serve everyone in one row, then $1$ second to move forward, $6$ seconds to serve one more row, then $3$ more seconds to move. Thus, $6 + 1 + 6 + 3 = 16$ in total. Now, if we are interested in seat $c$ in row $x$, the answer is equal to the answer for seat $c$ in row $xmod4 + 1$ plus $\left|{\frac{x-1}{4}}\right|\cdot16$. Note, that we use integer division, so it's not equal to $(x - 1) \cdot 4$. Solution: compute the serving time for first $4$ rows. Find the answer using formula above.
[ "implementation", "math" ]
1,200
null
725
C
Hidden Word
Let’s define a grid to be a set of tiles with $2$ rows and $13$ columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid: \begin{center} \begin{verbatim} ABCDEFGHIJKLM NOPQRSTUVWXYZ \end{verbatim} \end{center} We say that two tiles are adjacent if they share a side or a corner. In the example grid above, the tile with the letter 'A' is adjacent only to the tiles with letters 'B', 'N', and 'O'. A tile is not adjacent to itself. A sequence of tiles is called a path if each tile in the sequence is adjacent to the tile which follows it (except for the last tile in the sequence, which of course has no successor). In this example, "ABC" is a path, and so is "KXWIHIJK". "MAB" is not a path because 'M' is not adjacent to 'A'. A single tile can be used more than once by a path (though the tile cannot occupy two consecutive places in the path because no tile is adjacent to itself). You’re given a string $s$ which consists of $27$ upper-case English letters. Each English letter \textbf{occurs at least once} in $s$. Find a grid that contains a path whose tiles, viewed in the order that the path visits them, form the string $s$. If there’s no solution, print "Impossible" (without the quotes).
1. The input string $s$ contains 27 letters and it contains every letter in the English alphabet. The English alphabet has 26 letters, so there is exactly one repeated letter. 2. If the instances of the repeated letter are adjacent in the string, there can be no solution. That's because every English letter occurs in $s$ and the solution grid contains exactly 26 tiles, so any solution must have all letters distinct. Consider the tile containing the repeated letter. None of the tiles adjacent to it can contain the repeated letter because the letters of the grid are distinct, so the grid doesn't contain $s$. 3. Otherwise, there is a solution. Delete the second occurrence of the repeated letter and write the resulting string in circular order. For example, if the string with the repeated letter deleted is ABCDEFGHIJKLMNOPQRSTUVWXYZ, we write this to the grid: ABCDEFGHIJKLM ZYXWVUTSRQPON Then we rotate the grid, one step at a time, until it contains $s$. For example, if the above grid isn't a valid solution, we next try this: ZABCDEFGHIJKL YXWVUTSRQPONM And then this: YZABCDEFGHIJK XWVUTSRQPONML This will eventually give us a solution. Suppose the repeated letter lies between G and H in the original string. In each rotation, there are 2 letters adjacent to both G and H in the grid (in the above examples these letters are S and T, then Q and R, then O and P). When we rotate the string by a step, the adjacent letters advance by 1 or 2 steps. Eventually the repeated letter will be adjacent to both G and H, and this will yield a solution.
[ "brute force", "constructive algorithms", "implementation", "strings" ]
1,600
null
725
D
Contest Balloons
One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by $1$. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed. You should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings. A contest has just finished. There are $n$ teams, numbered $1$ through $n$. The $i$-th team has $t_{i}$ balloons and weight $w_{i}$. It's guaranteed that $t_{i}$ doesn't exceed $w_{i}$ so nobody floats initially. Limak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has. What is the best place Limak can get?
Previous ones describe how to find a correct approach. It may lead to a slightly more complicated solution, but you will learn something for sure. To come up with a solution, you must try iterating over some value or maybe binary searching an optimal value. Let's list a few reasonable ideas. Try to binary search the answer (for fixed final place of Limak you must say if he can get at least this place). Or iterate over the number of disqualified teams (if Limak should beat exactly $i$ teams, what is the best place he can get?). Or iterate over the number of balloons Limak should give away. The last idea turns out to be fruitful. The first observation is that you don't have to consider every possible number of balloons to give away. We can assume that the final number of balloons will be either $0$ or $t_{i}$ for some $i$. Otherwise Limak could give away some more balloons and his place won't be worse (if there are no more teams, let's imagine he can destroy them). We use here a simple observation that the $i$-th team either will be disqualified or will still have exactly $t_{i}$ balloons, i.e. values $t_{i}$ won't change. We have $O(n)$ possibilities for the final number of balloons. Let's first solve a problem in $O(n^{2}\cdot\log{n})$ by considering possibilities separately, each in $O(n\cdot\log n)$. Let's say Limak will have $k$ balloons at the end. He can give away $t_{1} - k$ balloons. He should try to get rid of teams with $t_{i} > k$ because worse teams don't affect his place. You should sort teams with $t_{i} > k$ by the number of balloons they need to get disqualified i.e. $w_{i} - t_{i} + 1$. It's easiest for Limak to get rid of teams with small value of $w_{i} - t_{i} + 1$ so you should just check how many of those values can be chosen so that the sum of them won't exceed $t_{1} - k$. It turns out to be possible to improve the above by considering possibilities in the decreasing order. Think what happens when you decrease $k$. Some more teams become a possible target and you should consider their values $w_{i} - t_{i} + 1$. A sorted set of those values should be useful. Try to invent a solution yourself now. Then you can see one simple version in the next paragraph. Now let's see an $O(n\cdot\log n)$ greedy solution. Create a variable $k$ representing the final number of balloons Limak has, initially $k = t_{1}$. Create and maintain a multiset with values $w_{i} - t_{i} + 1$ of teams better than the current $k$, i.e. teams with $t_{i} > k$. If it makes sense to give away some more balloons, Limak has to eliminate at least one of those better teams (otherwise he can stop now). It's easiest to eliminate a team with the smallest $w_{i} - t_{i} + 1$, so we can just remove the smallest element from the set and decrease $k$ by its value. Maybe some more teams become better than the current $k$ and you should add those to the multiset. Note that the multiset contains exactly those teams which would win with Limak in the current scenario, so after every change of $k$ you can update the answer 'ans = min(ans, my_multiset.size() + 1)'. Remember to stop if $k$ becomes smaller than $0$.
[ "data structures", "greedy" ]
1,800
null
725
E
Too Much Money
Alfred wants to buy a toy moose that costs $c$ dollars. The store doesn’t give change, so he must give the store exactly $c$ dollars, no more and no less. He has $n$ coins. To make $c$ dollars from his coins, he follows the following algorithm: let $S$ be the set of coins being used. $S$ is initially empty. Alfred repeatedly adds to $S$ the highest-valued coin he has such that the total value of the coins in $S$ after adding the coin doesn’t exceed $c$. If there is no such coin, and the value of the coins in $S$ is still less than $c$, he gives up and goes home. Note that Alfred never removes a coin from $S$ after adding it. As a programmer, you might be aware that Alfred’s algorithm can fail even when there is a set of coins with value exactly $c$. For example, if Alfred has one coin worth $3, one coin worth $4, and two coins worth $5, and the moose costs $12, then Alfred will add both of the $5 coins to $S$ and then give up, since adding any other coin would cause the value of the coins in $S$ to exceed $12. Of course, Alfred could instead combine one $3 coin, one $4 coin, and one $5 coin to reach the total. Bob tried to convince Alfred that his algorithm was flawed, but Alfred didn’t believe him. Now Bob wants to give Alfred some coins (in addition to those that Alfred already has) such that Alfred’s algorithm fails. Bob can give Alfred any number of coins of any denomination (subject to the constraint that each coin must be worth a positive integer number of dollars). There can be multiple coins of a single denomination. He would like to minimize the total value of the coins he gives Alfred. Please find this minimum value. If there is no solution, print "Greed is good". You can assume that the answer, if it exists, is positive. In other words, Alfred's algorithm will work if Bob doesn't give him any coins.
1. If there is a solution where Bob gives Alfred $n$ coins, then there is a solution where Bob gives Alfred only one coin. We can prove it by induction on $n$. The base case $n = 1$ is trivial. In the inductive case, let $x$ and $y$ be the highest-valued coins that Bob uses (where $x \ge y$). The sequence of coins chosen by Alfred looks like this: $c_{1}, c_{2}, ..., c_{a}, x, c_{a + 1}, ..., c_{b}, y, ...$ I claim that if we replace $x$ and $y$ with a single coin worth $x + y$ dollars then we will still have a solution. Clearly $x + y$ will be chosen by Alfred no later than Alfred chose $x$ in the original sequence. So if some coin would have caused Alfred to have more than $c$ dollars and so was skipped by Alfred, it will still be skipped by Alfred in the new solution since Alfred has no less money in $S$ than he did in the original solution. Likewise, we know that $x+y+\sum c_{i}<c$ 2. After pre-processing the input, we can simulate Alfred's algorithm in $O({\sqrt{c}})$ with the following process: find the next coin that Alfred will use (this can be done in $O(1)$ with $O(c)$ pre-processing). Suppose there are x copies of this coin in the input, the coin is worth y dollars, and Alfred has z dollars. Then Alfred will use $min(x, z / y)$ copies of this coin. We can find this value in $O(1)$. Now suppose this algorithm has run for $k$ steps. Then $y$ has taken $k$ distinct values and Alfred has used at least one coin of each value, so the coins in $S$ are worth at least $k(k + 1) / 2$. Thus, after $O({\sqrt{c}})$ steps the value of the coins in $S$ will exceed $c$. So this process runs in $O({\sqrt{c}})$ time. 3. Try every possible solution from $1$ to $c$ and check if it works. The complexity is $O(c{\sqrt{c}})$.
[ "brute force", "greedy" ]
2,600
null
725
F
Family Photos
Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first. There are $n$ stacks of photos. Each stack contains \textbf{exactly two} photos. In each turn, a player may take only a photo from the top of one of the stacks. Each photo is described by two non-negative integers $a$ and $b$, indicating that it is worth $a$ units of happiness to Alice and $b$ units of happiness to Bonnie. Values of $a$ and $b$ might differ for different photos. It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively. The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has $x$ happiness and Bonnie has $y$ happiness at the end, you should print $x - y$.
1. We are going to transform the stacks in such a way that every move is no worse than passing. 2. Consider a stack with values $a, b, c, d$. (The top photo is worth $a$ for Alice and $b$ for Bonnie and the bottom photo is worth $c$ for Alice and $d$ for Bonnie.) If $a + b \ge c + d$ then taking the top photo is no worse than passing. We can prove it by rearranging the inequality: $a - d \ge c - b$. $a - d$ is the value of the stack, from Alice's perspective, if Alice gets to move first. $c - b$ is the value, from Alice's perspective, if Bonnie gets to move first. So Alice doesn't incur a loss by making the first move, which means that a move here is no worse than passing. By symmetry, the same argument applies to Bonnie. 3. If $a + b < c + d$ then both players would rather have the other player make the first move. However, this doesn't necessarily mean that the stack will be ignored by the players. If $a > d$ then Alice can still profit by making the first move here. Since it would be even better for Alice if Bonnie made the first move, Alice can ignore this stack until Bonnie passes, and only then make a move here. So if $a > d$ then this stack is equivalent to a single photo with value $(a - d, d - a)$. 4. Likewise, if $b > c$ then the stack is equivalent to a single photo with value $(c - b, b - c)$. 5. If $a + b < c + d$ and neither (3) nor (4) apply, both players will ignore the stack and we can simply delete it. 6. Now every move is no worse than passing, so every photo will eventually be taken. For every photo $(a, b)$, replace it with a photo $\textstyle{\binom{a+b}{2}},{\frac{a+b}{2}}$ and add $\frac{a-b}{2}$ to the final answer. This is equivalent to the original problem because ${\frac{a-b}{2}}+{\frac{a+b}{2}}=a$ and ${\frac{a-b}{2}}-{\frac{a+b}{2}}=-b$. 7. Now every photo is worth the same to both players, so we can sort them in descending order and assign the photos with even indices to Alice and the photos with odd indices to Bonnie. Since every stack in the transformed problem has $a + b \ge c + d$, this guarantees that the top photo will be taken before the bottom photo in each stack. The complexity is $O(n\log n)$.
[ "games", "greedy" ]
2,900
null
725
G
Messages on a Tree
Alice and Bob are well-known for sending messages to each other. This time you have a rooted tree with Bob standing in the root node and copies of Alice standing in each of the other vertices. The root node has number $0$, the rest are numbered $1$ through $n$. At some moments of time some copies of Alice want to send a message to Bob and receive an answer. We will call this copy the initiator. The process of sending a message contains several steps: - The initiator sends the message to the person standing in the parent node and begins waiting for the answer. - When some copy of Alice receives a message from some of her children nodes, she sends the message to the person standing in the parent node and begins waiting for the answer. - When Bob receives a message from some of his child nodes, he immediately sends the answer to the child node where the message came from. - When some copy of Alice (except for initiator) receives an answer she is waiting for, she immediately sends it to the child vertex where the message came from. - When the initiator receives the answer she is waiting for, she doesn't send it to anybody. - There is a special case: a copy of Alice can't wait for two answers at the same time, so if some copy of Alice receives a message from her child node while she already waits for some answer, she rejects the message and sends a message saying this back to the child node where the message came from. Then the copy of Alice in the child vertex processes this answer as if it was from Bob. - The process of sending a message to a parent node or to a child node is instant but a receiver (a parent or a child) gets a message after $1$ second. If some copy of Alice receives several messages from child nodes at the same moment while she isn't waiting for an answer, she processes the message from the \textbf{initiator} with the smallest number and rejects all the rest. If some copy of Alice receives messages from children nodes and also receives the answer she is waiting for at the same instant, then Alice first processes the answer, then immediately continue as normal with the incoming messages. You are given the moments of time when some copy of Alice becomes the initiator and sends a message to Bob. For each message, find the moment of time when the answer (either from Bob or some copy of Alice) will be received by the initiator. You can assume that if Alice wants to send a message (i.e. become the initiator) while waiting for some answer, she immediately rejects the message and receives an answer from herself in no time.
Hint: Sort the queries somehow so that the answer on every query will depend only on previous queries. After that, use heavy-light decomposition to answer the queries quickly. Solution: First, sort the queries by $d[x_{i}] + t_{i}$, where $d[a]$ is the depth of the vertex $a$. It can be easily shown that the answer for every query depends only on the previous ones, so we can proceed them one by one. Also, after the sort we can assume that any query blocks the path from the initiator to the node that rejects the query in one instant, so we can only care about unblocking times. Suppose some node $v$ unblocks at the moment $T_{v}$. Which queries will be rejected by $v$ if they reach it? Obviously, the queries which have $v$ on the path from the initiator to the root and for which $t_{i} + d[x_{i}] - d[v] < T_{v}$ holds. Let's rewrite this as follows: $T_{v} + d[v] > t_{i} + d[x_{i}]$. Now the left part depends only on the blocking node, and the right part depends only on the query. Let's define $B_{v} = T_{v} + d[v]$. Now we have an $O(nm)$ solution: we proceed queries one by one, for each query we find such a node $v$ on the path from $x_{i}$ to the root so that the $B_{v} > t_{i} + d[x_{i}]$ holds for the node, and it has the maximum depth, and then reassign values of $B_{v}$ on the path from $x_{i}$ to $v$. To make the solution faster, we have to construct the heavy-light decomposition on the tree. Now let's store the values $B_{v}$ in segment trees on the decomposed paths. To assign on the path we should note that the values $B_{v}$ form arithmetical progression. To query the deepest node we should store the maximum value of $B_{v}$ in every node of the segment trees. This solution works in $O(m\log^{2}(n))$.
[]
3,300
null
727
A
Transformation: from A to B
Vasily has a number $a$, which he wants to turn into a number $b$. For this purpose, he can do two types of operations: - multiply the current number by $2$ (that is, replace the number $x$ by $2·x$); - append the digit $1$ to the right of current number (that is, replace the number $x$ by $10·x + 1$). You need to help Vasily to transform the number $a$ into the number $b$ using only the operations described above, or find that it is impossible. Note that in this task you are not required to minimize the number of operations. It suffices to find any way to transform $a$ into $b$.
Let's solve this problem in reverse way - try to get the number $A$ from $B$. Note, that if $B$ ends with 1 the last operation was to append the digit $1$ to the right of current number. Because of that let delete last digit of $B$ and move to the new number. If the last digit is even the last operation was to multiply the current number by $2$. Because of that let's divide $B$ on 2 and move to the new number. In the other cases (if $B$ ends with odd digit except 1) the answer is <<NO>>. We need to repeat described algorithm after we got the new number. If on some step we got the number equals to $A$ we find the answer, and if the new number is less than $A$ the answer is <<NO>>.
[ "brute force", "dfs and similar", "math" ]
1,000
null
727
B
Bill Total Value
Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "{$name_{1}price_{1}name_{2}price_{2}...name_{n}price_{n}$}", where $name_{i}$ (name of the $i$-th purchase) is a non-empty string of length not more than $10$, consisting of lowercase English letters, and $price_{i}$ (the price of the $i$-th purchase) is a non-empty string, consisting of digits and dots (decimal points). It is possible that purchases with equal names have different prices. The price of each purchase is written in the following format. If the price is an integer number of dollars then cents are not written. Otherwise, after the number of dollars a dot (decimal point) is written followed by cents \textbf{in a two-digit format} (if number of cents is between $1$ and $9$ inclusively, there is a leading zero). Also, every three digits (from less significant to the most) in dollars are separated by dot (decimal point). No extra leading zeroes are allowed. The price always starts with a digit and ends with a digit. For example: - "234", "1.544", "149.431.10", "0.99" and "123.05" are valid prices, - ".333", "3.33.11", "12.00", ".33", "0.1234" and "1.2" are not valid. Write a program that will find the total price of all purchases in the given bill.
In this problem we need to simply implement calculating the sum of prices. At first we need to find all prices - sequences of consecutive digits and dots. Then we need to find the integer number of dollars in each price and count integer sum of dollars in the variable $r$. Also we need to make the same thing for cents and calculate in the variable $c$. After process all prices we need to transform cents in rubles, i. e. add to $r$ the value $c / 100$, and $c$ assign to $c%100$. Now we need only to print the answer and do not forget, that for cents if $c < 10$ we need to print 0 at first and then $c$ because the number of cents must consisting of two digits like wrote in the statement.
[ "expression parsing", "implementation", "strings" ]
1,600
null
727
C
Guess the Array
This is an interactive problem. You should use flush operation after each printed line. For example, in C++ you should use fflush(stdout), in Java you should use System.out.flush(), and in Pascal — flush(output). In this problem you should guess an array $a$ which is unknown for you. The only information you have initially is the length $n$ of the array $a$. The only allowed action is to ask the sum of two elements by their indices. Formally, you can print two indices $i$ and $j$ (the indices should be \textbf{distinct}). Then your program should read the response: the single integer equals to $a_{i} + a_{j}$. It is easy to prove that it is always possible to guess the array using at most $n$ requests. Write a program that will guess the array $a$ by making at most $n$ requests.
At first let's make three queries on sum $a_{1} + a_{2} = c_{1}$, $a_{1} + a_{3} = c_{2}$ and $a_{2} + a_{3} = c_{3}$. After that we got a system of three equations with three unknown variables $a_{1}, a_{2}, a_{3}$. After simple calculating we got that $a_{3} = (c_{3} - c_{1} + c_{2}) / 2$. The values of $a_{1}$ and $a_{2}$ now can be simply found. After that we now the values of $a_{1}, a_{2}, a_{3}$ and spent on it 3 queries. Then for all $i$ from 4 to $n$ we need to make the query $a_{1} + a_{i}$. If the next sum equals to $c_{i}$ then $a_{i} = c_{i} - a_{1}$ (recall that we already know the value of $a_{1}$). So we guess the array with exactly $n$ queries.
[ "constructive algorithms", "interactive", "math" ]
1,400
null
727
D
T-shirts Distribution
The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size. During the registration, the organizers asked each of the $n$ participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him. Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size: - the size he wanted, if he specified one size; - any of the two neibouring sizes, if he specified two sizes. If it is possible, the program should find any valid distribution of the t-shirts.
Let in the array $cnt$ we store how many t-shirts of each size are in the typography. At first let's give the t-shirts to participants who wants exactly one size of the t-shirt and decrease appropriate values in $cnt$. If in some moment we have no t-shirt of needed size the answer is "NO". Now we need to give the t-shirts to participants who wants t-shirt with one of two sizes. Let's use greedy. At first we need to give t-shirts with size S to participants who wants it or t-shirt with size M. After that let's move to the t-shirts with size M. At first let's give this t-shirts to participants who wants it or t-shirts with size S and do not already have the t-shirt. After that if t-shirts with size M remain we need to give this t-shirts to participants who wants it or t-shirts with sizes L. Similarly, we must distribute the remaining t-shirts sizes. If after all operations not each participant has the t-shirt the answer is "NO". In the other case we found the answer.
[ "constructive algorithms", "flows", "greedy" ]
1,800
null
727
E
Games on a CD
Several years ago Tolya had $n$ computer games and at some point of time he decided to burn them to CD. After that he wrote down the names of the games one after another in a circle on the CD \textbf{in clockwise order}. The names were distinct, the length of each name was equal to $k$. The names didn't overlap. Thus, there is a cyclic string of length $n·k$ written on the CD. Several years have passed and now Tolya can't remember which games he burned to his CD. He knows that there were $g$ popular games that days. All of the games he burned were among these $g$ games, and \textbf{no game was burned more than once}. You have to restore any valid list of games Tolya could burn to the CD several years ago.
With help of Aho Corasick algorithm we need to build the suffix tree on the set of game names ans in the vertex of the tree (which correspond to the name of some game, this vertex will be on the depth $k$) we will store the number of this game. Builded tree allows to add symbols to some string one by one and find the vertex which corresponds to the longest prefix from all prefixes of game names which equals to the suffix of our string. If the length of this prefix equals to $k$ the suffix equals to some game name. Let's write the string which wrote on disk twice and calculate $idx_{i}$ - the index of the game which name equals to substring of doubled string from index $i - k + 1$ to index $i$ inclusively (if such index does not exist it's equals to $- 1$). Now we need to iterate through the indexes of symbols which is last in the name of some game. We can iterate from $0$ to $k - 1$. With fixed $f$ we need to check that all game names with last symbols in indexes $f+i k\;{\mathrm{~mod~}}n k$ for $0 \le i < n$ are different (for it we need to check that among $idx_{(f + ik)%nk + nk}$ there is no $- 1$ and all of them are different). If it is performed - print YES and now it is easy to restore the answer. If the condition failed for all $f$ - print NO. Asymptotic behavior of this solution - $O(n k+\sum|t_{i}|)$
[ "data structures", "hashing", "string suffix structures", "strings" ]
2,300
null
727
F
Polycarp's problems
Polycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter. He sent to the coordinator a set of $n$ problems. Each problem has it's quality, the quality of the $i$-th problem is $a_{i}$ ($a_{i}$ can be positive, negative or equal to zero). The problems are ordered by expected difficulty, but the difficulty is not related to the quality in any way. The easiest problem has index $1$, the hardest problem has index $n$. The coordinator's mood is equal to $q$ now. After reading a problem, the mood changes by it's quality. It means that after the coordinator reads a problem with quality $b$, the value $b$ is added to his mood. The coordinator always reads problems one by one from the easiest to the hardest, it's impossible to change the order of the problems. If after reading some problem the coordinator's mood becomes negative, he immediately stops reading and rejects the problemset. Polycarp wants to remove the minimum number of problems from his problemset to make the coordinator's mood non-negative at any moment of time. Polycarp is not sure about the current coordinator's mood, but he has $m$ guesses "the current coordinator's mood $q = b_{i}$". For each of $m$ guesses, find the minimum number of problems Polycarp needs to remove so that the coordinator's mood will always be greater or equal to $0$ while he reads problems from the easiest of the remaining problems to the hardest.
At first let's solve the problem for one value of $Q$. It is easy to show that optimal solution is the following: add to the set of tasks next task with quality equals to $a_{i}$. While the value of mood (the sum of qualities and $Q$) is less than 0, delete from the set of remaining task the task with worst quality. The quality of such task will be less than 0, because we will not spoil the mood on previous tasks. This solution can be implement with help of structures std::set or std::priority_queue. Described solution helps us to find answer on the query in $O(n\log n)$, but $O(m n\log n)$ does not fill in time limit. Note, that while we increase $Q$ the number of deleted problems does not increase and the possible number of such numbers is only $n$. So we need to solve the following task: for $0 \le x \le n$ calculate minimum value of $Q$ that the number of deleted problems does not exceed $x$. This problem can be easily solved for each $x$ with help of binary search in $O(n\log n\log M A X Q)$, in sum for all $x$ we got $O(n^{2}\log n\log M A X Q)$. Also we have an interest only $m$ values of $Q$, we can make the binary search only on this values and in total we got $O(n^{2}\log{n}\log{m})$ For each answer $x$ with help of stored values we need to find the first answer which minimum value of $Q$ does not more than $Q$ in the query. We can do it easy in $O(n)$ or with binary search in $O(\log n)$ (because the values $Q$ for the answers does not increase). In total we will get $O(mn)$ or $O(m\log n)$ in sum. The best asymptotic behavior is $O(n^{2}\log n\log m+m\log n)$ but solutions which work in $O(n^{2}\log n\log M A X Q+m n)$ also passed all tests.
[ "binary search", "dp", "greedy" ]
2,300
null
729
A
Interview with Oleg
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string $s$ consisting of $n$ lowercase English letters. There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers. The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here. To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length. Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
In this problem it is enough to iterate through the given string from the left to the right and find the longest substring like "ogo...go" from each position of the string. If such substring was founded add "***" and move to the end of this substring. In the other case, add current letter to the answer and move to the next position.
[ "implementation", "strings" ]
900
null
729
B
Spotlights
Theater stage is a rectangular field of size $n × m$. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not. You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines. A position is good if two conditions hold: - there is no actor in the cell the spotlight is placed to; - there is at least one actor in the direction the spotlight projects. Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.
Let's find the number of good positions where projector directed to the left. It can be done separately for each row. To make it we need to iterate through the row from the left to the right and store information about we met '{1}', for example, in the variable $f$. Then if we process the current value: if it is equal to '0', add one to the answer if $f$ equals to true; if it is equal to '1', then $f$ := true. We can find the answer for the 3 remaining directions in the same way.
[ "dp", "implementation" ]
1,200
null
729
C
Road to Cinema
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in $t$ minutes. There is a straight road of length $s$ from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point $0$, and the cinema is at the point $s$. There are $k$ gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly. There are $n$ cars in the rental service, $i$-th of them is characterized with two integers $c_{i}$ and $v_{i}$ — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity $v_{i}$. All cars are completely fueled at the car rental service. Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers $1$ kilometer in $2$ minutes, and consumes $1$ liter of fuel. In the accelerated mode a car covers $1$ kilometer in $1$ minutes, but consumes $2$ liters of fuel. The driving mode can be changed at any moment and any number of times. Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in $t$ minutes. Assume that all cars are completely fueled initially.
Let's note that there is a value for the fuel tank capacity (call it $w$), that if the car has the fuel tank capacity equal or more than $w$ it will be able to reach the cinema if time, else - will not be able. The value $w$ can be found with help of binary search because the function $can(w)$ (it is possible and it has enough time for such cur) is monotonic - in the beginning all values of this function is false, but after some moment the values of this function is always true. After we found $w$ it remain only to choose the cheapest car from the cars which fuel tank capacity equal or more than $w$. The function $can(w)$ can be realized with greedy algorithm. It is easy to write down the formula for find the number of kilometers which we can ride in fast mode if the nearest gas station is on the distance $x$ and we have $f$ liters of fuel in fuel tank: if $x > f$, then it is impossible to reach the nearest gas station and $can(w)$ must return false, if $x \le f$, then it is possible to ride in the fast mode min($x$, $f - x$) kilometers. So, now we know how to find the value $can(w)$ in one iterate through the array of gas stations in the increasing order of their positions.
[ "binary search", "greedy", "sortings" ]
1,700
null
729
D
Sea Battle
Galya is playing one-dimensional Sea Battle on a $1 × n$ grid. In this game $a$ ships are placed on the grid. Each of the ships consists of $b$ consecutive cells. No cell can be part of two ships, however, the ships \textbf{can touch} each other. Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss"). Galya has already made $k$ shots, all of them were misses. Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. It is guaranteed that there is at least one valid ships placement.
Let's note that in on the field there are $b$ zeroes in a row we must to shoot in at least one of them. We suppose that all ships was pressed to the right. Let's put the number 2 in cells where ships can be placed. Then iterate through the field from the left to the right and shoot in the cell if there is 0 and before it was $b - 1$ zero in a row. After iteration ended it is left only to shoot in any cell which value equals to 2. All described shoots are the answer for this problem.
[ "constructive algorithms", "greedy", "math" ]
1,700
null
729
E
Subordinates
There are $n$ workers in a company, each of them has a unique id from $1$ to $n$. \textbf{Exaclty} one of them is a chief, his id is $s$. Each worker except the chief has exactly one immediate superior. There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate superior, the immediate superior of the his immediate superior, and so on. For example, if there are three workers in the company, from which the first is the chief, the second worker's immediate superior is the first, the third worker's immediate superior is the second, then the third worker has two superiors, one of them is immediate and one not immediate. The chief is a superior to all the workers except himself. Some of the workers were in a hurry and made a mistake. You are to find the minimum number of workers that could make a mistake.
At first if the chief reported that he has one or more superiors let's change $a_{s}$ in zero. If there are workers who do not chiefs but reported that they have no superiors let assume that they reported a number which more than the other workers, for example, number $n$. It is necessarily that there must be the worker which has exactly one superior. If there is no such worker let's take the worker who reported the maximum number and change this number on 1. Then we need to make the same algorithm for numbers 2, 3, and etc. while there are workers, which have not yet considered. After we considered all workers the answer is the number of workers which reported numbers were changed.
[ "constructive algorithms", "data structures", "graphs", "greedy", "sortings" ]
1,900
null
729
F
Financiers Game
This problem has unusual memory constraint. At evening, Igor and Zhenya the financiers became boring, so they decided to play a game. They prepared $n$ papers with the income of some company for some time periods. Note that the income can be positive, zero or negative. Igor and Zhenya placed the papers in a row and decided to take turns making moves. Igor will take the papers from the left side, Zhenya will take the papers from the right side. Igor goes first and takes $1$ or $2$ (on his choice) papers from the left. Then, on each turn a player can take $k$ or $k + 1$ papers from his side if the opponent took exactly $k$ papers in the previous turn. Players can't skip moves. The game ends when there are no papers left, or when some of the players can't make a move. Your task is to determine the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it.
Let's solve this problem using dynamic programming. We can see that any position in the game can be described with three integers: the left and right bounds of the segment of papers that are still on the table, and the number of papers the previous player took; and who's turn it is. So, let $I_{lrk}$ be the game result if there were only papers from $l$ to $r$ initially, Igor moved first by taking $k$ or $k + 1$ papers. Similarly, let $Z_{lrk}$ be the same but Zhenya moved first. It can be easily seen that in general case $I_{l r k}=\operatorname*{max}(Z_{l+k,r,k}+\sum_{i=l}^{i<l+k}a_{i},Z_{l+k+1,r,k+1}+\sum_{i=l}^{i<l+k+1}a_{i}),$ $Z_{l r k}=\operatorname*{min}(I_{l,r-k,k}-\sum_{i=r-k+1}^{t\leq r}a_{i},I_{l,r-k-1,k+1}-\sum_{i=r-k}^{1\leq r}a_{i}).$ We need to carefully proceed the states where a player can't take the needed number of papers. The answer for the problem is $I_{1n1}$. At first sight it seems that this solution runs in $O(n^{3})$. However, it doesn't. What values can $l$, $r$ and $k$ be equal to? First, ${\frac{k(k+1)}{2}}\leq n$ because if the previous player took $k$ papers then there are at least as $1+2+3+...+k={\frac{k(k{+}1)}{2}}$ already taken papers. So, $k$ is not greater than $\sqrt{2n}$. Second, let's take a look at the difference between number of papers taken by Zhenya and Igor, i. e. at the value $d = (n - r) - (l - 1)$. We consider only cases in which both players made the same number of moves, so now it's Igor's move. Then $0 \le d \le k - 1$. Indeed, on each turn Zhenya took as many papers as Igor did, or one paper more, but in the latter case the "length" of move increased. The length of move increased by $k - 1$ overall, so the difference is at most $k - 1$. Thus, we can describe the dynamic programming state with $l$, $d$ and $k$, and there are $O(n^{2})$ states in total. We don't consider states in which it's Zhenya's turn, instead, we try all his possible moves to compute the states. The overall complexity is $O(n^{2})$. I find it easier to code by the use of recursion and memoization.
[ "dp" ]
2,500
null
731
A
Night at the Museum
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture: After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'. Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
In this problem you have to implement exactly what is written in the statement, i. e. you should find minimum number of rotations from letter a to the first letter in the input, then to the second one and so on. The only useful knowledge that may simplify the solution is that the distance between points $x$ and $y$ on the circle of length $l$ (26 in our case) is $min(|x - y|, l - |x - y|)$. This solution works in $O(|s|)$, and, of course, fits in time limit.
[ "implementation", "strings" ]
800
null
731
B
Coupons and Discounts
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition. Teams plan to train for $n$ times during $n$ consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be $a_{i}$ teams on the $i$-th day. There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two \textbf{consecutive} days (two pizzas in total). As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days. Sereja wants to order exactly $a_{i}$ pizzas on the $i$-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day $n$.
In a correct answer we may guarantee that for any two consecutive days we use no more than one coupon for bying pizzas in these days. Indeed, if we have two coupons for buying pizzas in days $i$ and $i + 1$, replace these coupons for two discounts, one for each of the days $i$ and $i + 1$. Consider the first day. According to the fact above, we may uniquely find the number of coupons for buying pizzas in 1 and 2 days we are going to use: it's either 0, if there is going to be an even number of pizzas in the first day, or 1 otherwise. The remaining pizzas in the first day will be bought by using discounts. If we use 1 coupon, then we may subtract 1 from the number of pizzas in the second day, and in both cases consider the second day and repeat the same actions. If at some moment we have the odd number of pizzas and we don't need any pizzas in the following day, then it is impossible to buy all pizzas using only coupons and discounts, and we may output "NO". If it didn't happen, then we were able to buy everything using only coupons and discounts. Such a solution works in $O(n)$.
[ "constructive algorithms", "greedy" ]
1,100
null
731
C
Socks
Arseniy is already grown-up and independent. His mother decided to leave him alone for $m$ days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes. Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's $n$ socks is assigned a unique integer from $1$ to $n$. Thus, the only thing his mother had to do was to write down two integers $l_{i}$ and $r_{i}$ for each of the days — the indices of socks to wear on the day $i$ (obviously, $l_{i}$ stands for the left foot and $r_{i}$ for the right). Each sock is painted in one of $k$ colors. When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses $k$ jars with the paint — one for each of $k$ colors. Arseniy wants to repaint some of the socks in such a way, that for each of $m$ days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now. The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of $m$ days.
When solving this problem, it is convenient to use graph interpretation of the problem. Consider the graph, whose vertices correspond to the socks and edges connect those socks that Arseniy wears on some day. By the statement, we have to make that any two vertices connected by an edge have the same color. It actually means that any connected component should share the same color. For each connected component let's find out which color should we choose for it. In order to recolor the minimum possible number of vertices, we should leave the maximum number of vertices with their original color. It means that the optimum color is the color shared by the most number of vertices in this connected component. So, we have the following solution: consider all connected components, in each component choose the most popular color and add the difference between the component size and the number of vertices of this color. In order to find the most popular color you may, for example, write all colors in an array, sort it and find the longest contiguous segment of colors. Such a solution works in $O((n+m)\log n)$.
[ "dfs and similar", "dsu", "graphs", "greedy" ]
1,600
null
731
D
80-th Level Archeology
Archeologists have found a secret pass in the dungeon of one of the pyramids of Cycleland. To enter the treasury they have to open an unusual lock on the door. The lock consists of $n$ words, each consisting of some hieroglyphs. The wall near the lock has a round switch. Each rotation of this switch changes the hieroglyphs according to some rules. The instruction nearby says that the door will open only if words written on the lock would be sorted in lexicographical order (the definition of lexicographical comparison in given in notes section). The rule that changes hieroglyphs is the following. One clockwise rotation of the round switch replaces each hieroglyph with the next hieroglyph in alphabet, i.e. hieroglyph $x$ ($1 ≤ x ≤ c - 1$) is replaced with hieroglyph $(x + 1)$, and hieroglyph $c$ is replaced with hieroglyph $1$. Help archeologist determine, how many clockwise rotations they should perform in order to open the door, or determine that this is impossible, i.e. no cyclic shift of the alphabet will make the sequence of words sorted lexicographically.
Denote as $x$ the number of alphabet cyclic shifts we will perform. Our goal is to formulate the statement of lexicographical order in terms of $x$. Note that $x$ may be considered as an integer between $0$ and $c - 1$, i. e., as a residue modulo $c$. Let's also consider all characters as values between $0$ to $c - 1$ as we may subtract 1 from the value of each character. Consider two consecutive words in the given list. There are two possibilities corresponding two cases in the definition of lexicographical order: The first case is when there exists such a position that these words differ in this position and coincide before this position. Suppose that first word has value of $a$ on this position, and second word has the value of $b$. Then these words will follow in lexicographical order if and only if $(a+x)\ \mathrm{~mod~}c<(b+x)\ \ \mathrm{~mod~}c$. It's easy to see that if we consider all residues modulo $c$ as a circle, then this inequality defines an arc of possible $x$'s on this circle. So, this pair of contiguous words produces the following statement "$x$ belongs to some arc on the circle". The second case is when there is no such a position, i. e. one word is a prefix of another. If the first word is a prefix of second one then these words always follow in lexicographical order irrespective to the choice of $x$. In the other case (second word is a proper prefix of the first word) we can't do anything with these to words since they will never follow in a lexicographical order, so we should print $- 1$. Now we have to find a point on the circle belonging to the given set of arcs. Suppose we have $k$ arcs. Consider a line segment from $0$ to $c - 1$ instead of a circle; each arc will transform to either one or two its subsegments. Now we have to find out if there exists a point covered by exactly $k$ segments. It may be done in different ways, for example you may add 1 on each of this segment by using some data structure, or you may add $1$ to the left endpoint of each segment and $- 1$ to the point after the right endpoint of each segment, and consider prefix sums (an off-line way to handle range addition queries). Or you may write down all endpoints of all segments, sort them by a coordinate and iterate over them from left to right, keeping the number of open segments. If at some moment you have exactly $k$ open segments, then the answer is "YES".
[ "brute force", "data structures", "greedy", "sortings" ]
2,200
null
731
E
Funny Game
Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them. The game they came up with has the following rules. Initially, there are $n$ stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first. One move happens as follows. Lets say there are $m ≥ 2$ stickers on the wall. The player, who makes the current move, picks some integer $k$ from $2$ to $m$ and takes $k$ leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent. Given the integer $n$ and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.
First of all, comment on such type of games. In CS the game where two players are willing to maximize the difference between their own score and the score of their opponent is called a "zero-sum game". A useful knowledge is that problems for such a kind of games are usually solved using dynamic programming. Note that at any moment the first sticker contains the sum of numbers on some prefix of an original sequence. This means that the state of a game is defined by a single number $i$: the length of an original sequence prefix that were summed into a single number. Let's make two observations. First of all, for any state $i$ the turn that current player will perform doesn't depend on scores of both players. Indeed, at any moment we may forget about the scores of both players since they add the constant factor to the resulting score difference, so we may virtually discard both players current scores. So, all we need to know about state $i$ is what difference there will be between the current player score and his opponent score if the game would have started from the state $i$ with zero scores. Second observation is that the turn chosen by a player from the state $i$ and the final difference of scores at the end does not depend from which player is currently making a turn (Petr or Gennady), i. e. the game is symmetric. Denote as $D[i]$ the difference between the first player score and the second player score if the game would have started from the state $i$ with zero scores. It is a convenient way to think about this game as if there were no separate scores of two players, but only a single balance value (difference) between them, and the first player is adding some numbers to the balance at his turn and second player subtracts some numbers from the balance. In such formulation $D[i]$ is a balance change at the end of the game if the current player is willing to maximize it and he is currently in the state $i$. The answer for a problem will be, as one can see, $D[1]$. Note that if the current player would be willing to minimize balance, then the final balance change from the state $i$ would be $- D[i]$ because the game is symmetric. Let's calculate all $D[i]$ using dynamic programming. At the end of the game, i. e. in the state $n$ the value $D[n]$ is equal to zero because the players won't be making any turns, and so the balance won't change. Consider some state $i$. Suppose current player will take all the stickers up to the $j$-th (here $j$-th means the index in the original sequence). In such case he will change balance by $S[j]$ (where $S[j]$ is the sum of first $j$ numbers in an original sequence), and game will move to the state $j$. After that his opponent will change the balance by $- D[j]$ (note that the balance change value is added with an opposite sign since the opponent will be playing from this state). So, the final balance change when making such a turn will be $S[j] - D[j]$. In the DP definition we play for a player that is willing to maximize the balance, so $D[i]=\operatorname*{max}_{i<j\leq n}(S[j]-D[j])$. Such a formula produces a solution in $O(n^{2})$, but one may find that that it's enough to keep the maximum value of $S[j] - D[j]$ on suffix $j > i$, recalculating it in $O(1)$ when moving from $i$ to $i - 1$. So, we have the solution that works in $O(n)$.
[ "dp", "games" ]
2,200
null
731
F
Video Cards
Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated. There are $n$ video cards in the shop, the power of the $i$-th video card is equal to integer value $a_{i}$. As Vlad wants to be sure the new game will work he wants to buy not one, but several video cards and unite their powers using the cutting-edge technology. To use this technology one of the cards is chosen as the leading one and other video cards are attached to it as secondary. For this new technology to work it's required that the power of each of the secondary video cards is divisible by the power of the leading video card. In order to achieve that the power of any secondary video card can be reduced to any integer value less or equal than the current power. However, the power of the leading video card should remain unchanged, i.e. it \textbf{can't} be reduced. Vlad has an infinite amount of money so he can buy any set of video cards. Help him determine which video cards he should buy such that after picking the leading video card and may be reducing some powers of others to make them work together he will get the maximum total value of video power.
First observation is that if we fix the leading video card power $x$, we may take all the video cards of power at least $x$, as each of them brings the positive power value. So, we may sort all the cards in the ascending power order and then we will always choose some suffix of cards in such an order. The final total power equals to $\sum_{i=1}^{n}(a_{i}-(a_{i}{\mathrm{~~mod~}}x))$. Note that under the summation there is a number that is divisible by $x$ and that is no larger than $200 000$ at the same time. It means that there are no more than $\left|{\frac{20000}{x}}\right|$ different terms in this sum. Let's calculate the value of a sum spending the operations proportional to the number of different terms in it. To do it we need to find out for each of the values $x$, $2x$, $3x$, ..., how many video cards will have exactly such power at the end. It's easy: final power $kx$ corresponds to those video cards, which originally had the power between $kx$ and $(k + 1)x - 1$. Their number can be found out in $O(1)$ if we build an array $C[i]$ storing the number of video cards of each power and calculate prefix sums on it. It means that we got a solution that performs about $\sum_{x=1}^{20000}\left[{\frac{290090}{x}}\right]\approx\sum_{x=1}^{200000}{\frac{219000}{x}}=200\,000({\frac{1}{1}}+{\frac{1}{2}}+\cdot\cdot+{\frac{1}{200000}})\approx200\,000\,\ln200\,000$ operations. It's useful to know that the sum inside brackets is called a harmonic series, and that its sum is very close to the natural logarithm of the number of terms (up to a constant factor in limit). It means that we got a solution in complexity of $O(n+m\log m)$ where $m$ is the maximum power of a single video card.
[ "brute force", "data structures", "implementation", "math", "number theory" ]
1,900
null
732
A
Buy a Shovel
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for $k$ burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of $r$ burles ($1 ≤ r ≤ 9$). What is the minimum number of shovels Polycarp has to buy so that he can pay for the purchase without any change? It is obvious that he can pay for 10 shovels without any change (by paying the requied amount of 10-burle coins and not using the coin of $r$ burles). But perhaps he can buy fewer shovels and pay without any change. Note that Polycarp should buy at least one shovel.
In this problem we have to find the minimal possible value of $x$ such that $k \cdot x mod 10 = 0$ or $k \cdot x mod 10 = r$. It's easy to see that this $x$ always exists and it is not greater than $10$ (because $k \cdot 10 mod 10 = 0$). Let's iterate on $x$, and if its current value satisfies any of the requirements, we print the answer. Time complexity: $O(const)$, where $const = 10$.
[ "brute force", "constructive algorithms", "implementation", "math" ]
800
null
732
B
Cormen --- The Best Friend Of a Man
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least $k$ walks for any two consecutive days in order to feel good. For example, if $k = 5$ and yesterday Polycarp went for a walk with Cormen $2$ times, today he has to go for a walk at least $3$ times. Polycarp analysed all his affairs over the next $n$ days and made a sequence of $n$ integers $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is the number of times Polycarp will walk with the dog on the $i$-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.). Help Polycarp determine the minimum number of walks he needs to do additionaly in the next $n$ days so that Cormen will feel good during all the $n$ days. You can assume that on the day before the first day and on the day after the $n$-th day Polycarp will go for a walk with Cormen exactly $k$ times. Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers $b_{1}, b_{2}, ..., b_{n}$ ($b_{i} ≥ a_{i}$), where $b_{i}$ means the total number of walks with the dog on the $i$-th day.
If we don't make enough walks during days $i$ and $i + 1$, it's better to make an additional walk on day $i + 1$ because it also counts as a walk during days $i + 1$ and $i + 2$ (and if we walk one more time on day $i$, it won't help us in the future). So we can start iterating from the second day ($1$"=indexed). We will add $max(0, k - a_{i} - a_{i - 1})$ walks to the day $i$ (and to our answer), so Cormen has enough walks during days $i$ and $i - 1$. After we have iterated through all days, we can print the answer. Time complexity: $O(n)$.
[ "dp", "greedy" ]
1,000
null
732
C
Sanatorium
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all. Vasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived. According to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.
Let's iterate on the time of day when Vasiliy arrived at the sanatorium (breakfast, dinner or supper) and on the time when Vasiliy left. We sum the changed values of $b$, $d$ and $s$ (considering that we take all possible meals during the first and the last day) into the variable $sum$, find $mx$ - the maximum of these three variables (also changed), and if our current answer is more than $3 \cdot mx - sum$, we update it with this value. After considering all $9$ possible scenarios, we print the answer. Time complexity: $O(const)$, $const = 3^{3}$.
[ "binary search", "constructive algorithms", "greedy", "implementation", "math" ]
1,200
null
732
D
Exams
Vasiliy has an exam period which will continue for $n$ days. He has to pass exams on $m$ subjects. Subjects are numbered from 1 to $m$. About every day we know exam for which one of $m$ subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day. On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest. About each subject Vasiliy know a number $a_{i}$ — the number of days he should prepare to pass the exam number $i$. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during $a_{i}$ days for the exam number $i$. He can mix the order of preparation for exams in any way. Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time.
Let's use binary search to find the answer (the latest day when we have passed all the exams). To check whether we can pass all the exams until some fixed day $x$, we will take all the examples as late as possible. We will prepare to the earliest exam, then to the second earliest, and so on. If we are not ready for some exam or if we don't pass them until the day $x$ ends, then we can't pass all the exams in time. After finishing our binary search we print the answer. Time complexity: $O(mlogn)$.
[ "binary search", "greedy", "sortings" ]
1,700
null
732
E
Sockets
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations. There are $n$ computers for participants, the $i$-th of which has power equal to positive integer $p_{i}$. At the same time there are $m$ sockets available, the $j$-th of which has power euqal to positive integer $s_{j}$. It is possible to connect the $i$-th computer to the $j$-th socket if and only if their powers are the same: $p_{i} = s_{j}$. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power $x$, the power on the adapter's socket becomes equal to $\left|{\frac{x}{2}}\right|$, it means that it is equal to the socket's power divided by two with rounding up, for example ${\bigl\lfloor}{\frac{10}{2}}{\bigr\rfloor}=5$ and ${\frac{|15}{2}}|=8$. Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power $10$, it becomes possible to connect one computer with power $3$ to this socket. The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers $c$ at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters $u$ to connect $c$ computers. Help organizers calculate the maximum number of connected computers $c$ and the minimum number of adapters $u$ needed for this. The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.
Firstly, we need to sort both arrays (with computers and with sockets) in non-descending order (also we need to sustain their indices to print the answer). Then we iterate on the value $x$ until it reaches the logarithm of the maximum value in $s$ (or until it reaches 31). For each value of $x$ we iterate on computers in non-descending order, also we maintain the index of the most suitable socket (let's call this index $i$). If socket number $i$ is already used or if its power is less than current computer's requirement, we increase $i$. If our current socket's power matches current computer's requirement, then we connect this computer with current socket. Each iteration connects the largest possible number of computers and sockets. After each iteration we install adapters on all non"=used sockets: $s_{i}=\left\lceil{\frac{a}{2}}\right\rceil$. After all iterations we print the answer. Time complexity: $O(nlogn + mlogm + (n + m)logA)$, where $A$ is the maximum power of socket.
[ "greedy", "sortings" ]
2,100
null
732
F
Tourist Reform
Berland is a tourist country! At least, it can become such — the government of Berland is confident about this. There are $n$ cities in Berland, some pairs of which are connected by two-ways roads. Each road connects two different cities. In Berland there are no roads which connect the same pair of cities. It is possible to get from any city to any other city using given two-ways roads. According to the reform each road will become one-way. It will be oriented to one of two directions. To maximize the tourist attraction of Berland, after the reform for each city $i$ the value $r_{i}$ will be calculated. It will equal to the number of cities $x$ for which there is an oriented path from the city $i$ to the city $x$. In other words, $r_{i}$ will equal the number of cities which can be reached from the city $i$ by roads. The government is sure that tourist's attention will be focused on the minimum value of $r_{i}$. Help the government of Berland make the reform to maximize the minimum of $r_{i}$.
Firstly, we have to find all the bridges and divide the graph into 2"=edge"=connected components. Then we calculate the size of each component. It can be easily proved that the answer is equal to size of the largest component. Then we need to orient the edges somehow. Start DFS from any vertex of the largest component. If we traverse the edge $(v, to)$ (coming from vertex $v$) and it has not been oriented yet, we orient it from $to$ to $v$, if it's a bridge (so it leads to the largest component) or from $v$ to $to$ otherwise. When all vertices are visited and all edges are oriented, we can print the answer. Time complexity: $O(n + m)$.
[ "dfs and similar", "graphs" ]
2,300
null
733
A
Grasshopper And the String
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of his jump. Formally, consider that at the begginning the Grasshopper is located directly in front of the leftmost character of the string. His goal is to reach the position right after the rightmost character of the string. In one jump the Grasshopper could jump to the right any distance from $1$ to the value of his jump ability. \begin{center} {\small The picture corresponds to the first example.} \end{center} The following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'.
In this problem you have to find the longest sequence of consonants. The answer is its length + 1. Iterate over each letter of string maintaining $cur$ - current number of consecutive consonants and $len$ - length of longest sequence. If current letter is consonant then increase $cur$ by 1, otherwise update $len = max(len, cur)$ and set $cur$ = 1. Don't forget to update $len$ value after exiting loop (as string can possibly end with consonant). Time complexity - $O(n)$, $n$ - length of the specified string.
[ "implementation" ]
1,000
null
733
B
Parade
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step. There will be $n$ columns participating in the parade, the $i$-th column consists of $l_{i}$ soldiers, who start to march from left leg, and $r_{i}$ soldiers, who start to march from right leg. The beauty of the parade is calculated by the following formula: if $L$ is the total number of soldiers on the parade who start to march from the left leg, and $R$ is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal $|L - R|$. \textbf{No more than once} you can choose one column and tell \textbf{all the soldiers} in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index $i$ and swap values $l_{i}$ and $r_{i}$. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.
Let's calculate $L$ and $R$ values before update moves. Result will be stored in $maxk$ - maximum beauty that can be achieved. So initially $maxk = |L - R|$. Now for every columm let's calculate $k_{i}$ - beauty of the parade after switching starting leg of $i$-th column. $k_{i} = |(L - l_{i} + r_{i}) - (R - r_{i} + l_{i})|$. If $k_{i} > maxk$ then update $maxk$ value and store index $i$ for answer. If there were no such $i$ that $k_{i} > maxk$ then answer is 0. Time complexity - $O(n)$.
[ "math" ]
1,100
null
733
C
Epidemic in Monstropolis
There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city. Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is \textbf{strictly greater} than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster $A$ eats the monster $B$, the weight of the monster $A$ increases by the weight of the eaten monster $B$. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were $n$ monsters in the queue, the $i$-th of which had weight $a_{i}$. For example, if weights are $[1, 2, 2, 2, 1, 2]$ (in order of queue, monsters are numbered from $1$ to $6$ from left to right) then some of the options are: - the first monster can't eat the second monster because $a_{1} = 1$ is not greater than $a_{2} = 2$; - the second monster can't eat the third monster because $a_{2} = 2$ is not greater than $a_{3} = 2$; - the second monster can't eat the fifth monster because they are not neighbors; - the second monster can eat the first monster, the queue will be transformed to $[3, 2, 2, 1, 2]$. After some time, someone said a good joke and all monsters recovered. At that moment there were $k$ ($k ≤ n$) monsters in the queue, the $j$-th of which had weight $b_{j}$. Both sequences ($a$ and $b$) contain the weights of the monsters in the order from the first to the last. You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other.
The key observation to solution is to notice that $b_{1}$ is union (monsters eat one another one by one in such a way that only one is being left) of elements of some prefix of $a$. And if you remove this prefix and first element of $b$ then this condition will remain true for new arrays $a$ and $b$. Answer is "NO" when: There is no such prefix that has sum of $b_{i}$. Prefix of sum $b_{i}$ consists of equal elements and its size $> 1$. Now let's consider certain prefix. Our goal is to find sequence of moves to get only one monster left. Here is one of possible solutions: Find such $i$ that $a_{i}$ is maximum in prefix and either $a_{i - 1}$ or $a_{i + 1}$ is strictly less that $a_{i}$. Eat any of possible neighbors. If only one monster is left then move to next segment. If all weights become equal then print "NO". The only thing left is to carefully calculate real positions of monsters on each step. Also you can't output them at a moment of calculation as there might be a "NO" answer afterwards. Time complexity - $O(n^{2})$. And challenge: can you optimize it to $O(n)$?
[ "constructive algorithms", "dp", "greedy", "two pointers" ]
1,800
null
733
D
Kostya the Sculptor
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has $n$ stones which are rectangular parallelepipeds. The edges sizes of the $i$-th of them are $a_{i}$, $b_{i}$ and $c_{i}$. He can take \textbf{no more than two stones} and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
Radius of inscribed sphere = $min(a, b, c) / 2$. Let's create list of pairwise distinct edges where two edges is condered different when either minimal sides of edges differ or maximal ones. For every edge $(a, b)$ let's find two maximal lengths of adjacent side $c_{1}$ and $c_{2}$. These are two parallelepipeds of maximal volume with one of edges being equal to $(a, b)$. If you glue them together then you will get parallelepiped with sides $(a, b, c_{1} + c_{2})$. Also don't forget cases where there is only one maximal side for edge. There are no more than $3 \cdot n$ edges. So iterating over every parallelepiped with structure $map$ to store maximums works in $O(k n\cdot\log k n)$ where $k \le 3$.
[ "data structures", "hashing" ]
1,600
null
733
E
Sleep in Class
The academic year has just begun, but lessons and olympiads have already occupied all the free time. It is not a surprise that today Olga fell asleep on the Literature. She had a dream in which she was on a stairs. The stairs consists of $n$ steps. The steps are numbered from bottom to top, it means that the lowest step has number $1$, and the highest step has number $n$. Above each of them there is a pointer with the direction (up or down) Olga should move from this step. As soon as Olga goes to the next step, the direction of the pointer (above the step she leaves) changes. It means that the direction "up" changes to "down", the direction "down"  —  to the direction "up". Olga always moves to the next step in the direction which is shown on the pointer above the step. If Olga moves beyond the stairs, she will fall and wake up. Moving beyond the stairs is a moving down from the first step or moving up from the last one (it means the $n$-th) step. In one second Olga moves one step up or down according to the direction of the pointer which is located above the step on which Olga had been at the beginning of the second. For each step find the duration of the dream if Olga was at this step at the beginning of the dream. Olga's fall also takes one second, so if she was on the first step and went down, she would wake up in the next second.
Olga is always able to go beyond stairs. To prove that let's consider some segment of stairs. If we enter it from upper step then we move down until reaching 'U' which reverses our moving direction. After that we leave segment from above. Now this 'U' became 'D' and other symbols remained the same as they were either visited twice or not visited at all. So we enter segment once again from upper step, this time we proceed to next 'U'. And at the some point we leave segment from below. It will happen in $ku + 1$ turn where $ku$ - number of 'U' symbols in segment. Leaving segment from above when it's entered from below is done in $kd + 1$ turns, $kd$ - number of 'D' symbols in segment. It can be proven the same way. Then we can divide stairs into three parts: Segment below current step Current step Segment above current step It can be easily seen that we will go beyond stairs either from $1^{st}$ or from $3^{rd}$ segment. Now let's calculate values of $ku$ and $kd$ for every step. $ku_{i}$ - number of 'U' symbols in prefix of stairs $s$ (exluding $s_{i}$), $kd_{i}$ - number of 'D' symbols in suffix (exluding $s_{i}$). $ku_{i} = ku_{i - 1} + int(s_{i} = = 'U')$ $kd_{i} = kd_{i + 1} + int(s_{i} = = 'D')$ We will also need values of $tl_{i}$ and $tr_{i}$, $tl_{i}$ - time in seconds to leave stairs from below as if $s_{i}$ is always equal to 'D' and $tr_{i}$ - time in seconds to leave stairs from above as if $s_{i}$ is always equal to 'U'. It's obvious that by moving iterator by one position to the right we increase distance to every calculated symbol 'U' by $1$, so it's $+ 2$ for each symbol to overall time (we go to this symbol and back to $i$). If previous symbol was 'U' then we should add $2$ more to overall time. In total this will be equal to $ku_{i} \cdot 2$. And as we moved one step away from exit we should increase time by $1$. $tl_{i} = tl_{i - 1} + ku_{i} \cdot 2 + 1$ And it's the same for $tr_{i}$. $tr_{i} = tr_{i + 1} + kd_{i} \cdot 2 + 1$ And finally let's derive formula to get answer in $O(1)$ for each step. Olga will go beyond stairs from the side which has least amount of obstacles. If amounts are equal then it's the matter of current letter. Let's imply that we are exiting from both sides at the same time and just subtract from time the part from the side opposite to exiting one. So we should subtract $tl_{j}$ or $tr_{j}$ (it depends on exiting side), where $j$ is position in string of last visited element of side opposite to exiting one. And also subtract doubled distance between current step and last visited obstacle multiplied by number of unvisited onstacles. So if we go beyond stairs from below then this is the derived formula: $tl_{i} + tr_{i} - tr_{posd[kdi - kui - f]} - (posd[kd_{i} - f - ku_{i}] - i) - 2 \cdot (kd_{i} - ku_{i} - f) \cdot (posd[kd_{i} - f - ku_{i}] - i)$ $posd$ - reversed array of indices (positions in string) of 'D' symbol. $kd_{i} - ku_{i} - f$ - number (not position) of last visited element from above. $f$ is $0$ if $s_{i} =$'D', $1$ if $s_{i} =$'U'. (This will be reversed on exiting from above) Answer for last step is calculated the same way. For deriving formula for exiting from above you will also need $posu$ - array of indices (positions in string) of 'U' symbol (not reversed this time).
[ "constructive algorithms", "data structures", "math", "two pointers" ]
2,400
null
733
F
Drivers Dissatisfaction
In one kingdom there are $n$ cities and $m$ two-way roads. Each road connects a pair of cities, and for each road we know the level of drivers dissatisfaction — the value $w_{i}$. For each road we know the value $c_{i}$ — how many lamziks we should spend to reduce the level of dissatisfaction with this road by one. Thus, to reduce the dissatisfaction with the $i$-th road by $k$, we should spend $k·c_{i}$ lamziks. And \textbf{it is allowed for the dissatisfaction to become zero or even negative}. In accordance with the king's order, we need to choose $n - 1$ roads and make them the main roads. An important condition must hold: it should be possible to travel from any city to any other by the main roads. The road ministry has a budget of $S$ lamziks for the reform. The ministry is going to spend this budget for repair of some roads (to reduce the dissatisfaction with them), and then to choose the $n - 1$ main roads. Help to spend the budget in such a way and then to choose the main roads so that the total dissatisfaction with the main roads will be as small as possible. The dissatisfaction with some roads can become negative. It is not necessary to spend whole budget $S$. It is guaranteed that it is possible to travel from any city to any other using existing roads. Each road in the kingdom is a two-way road.
If you choose any $n - 1$ roads then price of reducing overall dissatisfaction is equal to $min(c_{1}, c_{2}, ..c_{n - 1})$ where $c_{i}$ is price of reducing by $1$ dissatisfaction of $i$-th edge. So the best solution is to choose one edge and reduce dissatisfaction of it until running out of budget. Let's construct minimal spanning tree using Prim or Kruskal algorithm using edges of weights equal to dissatisfaction and calculate minimal price of reducing dissatisfaction. Time complexity - $O(m\log n)$. Now we can iterate over edges implying that current is the one to be reduced to minimum. For example, for every edge we can build new MST and recalculate answer. It's $O(m^{2}\cdot\log n)$. Therefore we should use this fact: it's poinless to reduce dissatisfaction of edges which weren't selected to be main. Then we can transform original MST instead of constructing $m$ new ones. Add next edge to MST, now it contains a cycle from which edge with maximal dissatisfaction is about to be deleted. This can be achieved in such a way: find LCA of vertices of new edge in $O(\log n)$ and using binary lifting with precalc in $O(\log n)$ find the edge to delete. Time complexity - $O(n\log n+m\log n)$.
[ "data structures", "dsu", "graphs", "trees" ]
2,200
null
734
A
Anton and Danik
Anton likes to play chess, and so does his friend Danik. Once they have played $n$ games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this.
Let $k_{a}$ will be amount of characters "A" in the string and $k_{d}$ will be amount of characters "D" in the string. Then, if $k_{a} > k_{d}$, we print "Anton". If $k_{a} < k_{d}$, we print "Danik". If $k_{a} = k_{d}$, we print "Friendship". Time complexity is $O(n)$.
[ "implementation", "strings" ]
800
#include <iostream> #include <string> using namespace std; int main() { int n; cin >> n; string s; cin >> s; int k_a = 0, k_d = 0; for (int i = 0; i < n; i++) if (s[i] == 'A') k_a++; else k_d++; if (k_a > k_d) cout << "Anton" << endl; if (k_a < k_d) cout << "Danik" << endl; if (k_a == k_d) cout << "Friendship" << endl; return 0; }
734
B
Anton and Digits
Recently Anton found a box with digits in his room. There are $k_{2}$ digits $2$, $k_{3}$ digits $3$, $k_{5}$ digits $5$ and $k_{6}$ digits $6$. Anton's favorite integers are $32$ and $256$. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit can be used no more than once, i.e. the composed integers should contain no more than $k_{2}$ digits $2$, $k_{3}$ digits $3$ and so on. Of course, unused digits are not counted in the sum.
We will act greedily. At first we'll make maximal possible amount of $256$ numbers. It will be equal to $n_{256}=\operatorname*{min}(k_{2},k_{5},k_{6})$. From the rest of the digits we'll make maximal possible amount of $32$ numbers. It will be equal to $n_{32}=\operatorname*{min}(k_{3},k_{2}-n_{256})$ (we use $k_{2} - n_{256}$ instead of $k_{2}$, because $n_{256}$ twos we've already used to make $256$ numbers. Now it's not hard to observe that the answer will be equal to $32\cdot n_{32}+256\cdot n_{256}$. Time complexity is $O(1)$.
[ "brute force", "greedy", "implementation", "math" ]
800
#include <iostream> #include <algorithm> using namespace std; int main() { int k2, k3, k5, k6; cin >> k2 >> k3 >> k5 >> k6; int n256 = min(k2, min(k5, k6)); int n32 = min(k3, k2 - n256); cout << 32 * n32 + 256 * n256 << endl; return 0; }
734
C
Anton and Making Potions
Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare $n$ potions. Anton has a special kettle, that can prepare one potions in $x$ seconds. Also, he knows spells of two types that can faster the process of preparing potions. - Spells of this type speed up the preparation time of one potion. There are $m$ spells of this type, the $i$-th of them costs $b_{i}$ manapoints and changes the preparation time of each potion to $a_{i}$ instead of $x$. - Spells of this type immediately prepare some number of potions. There are $k$ such spells, the $i$-th of them costs $d_{i}$ manapoints and instantly create $c_{i}$ potions. Anton can use \textbf{no more than one} spell of the first type and \textbf{no more than one} spell of the second type, and the total number of manapoints spent should not exceed $s$. Consider that all spells are used instantly and right before Anton starts to prepare potions. Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least $n$ potions.
At first, observe that if we'll take the $i$-th potion of the first type and the $j$-th potion of the second type, then we can prepare all the potions in $a_{i}\cdot(n-c_{j})$ seconds. So, we have to minimize this number. Let's iterate over what potion of the first type we'll use. Then we must find such spell of the second type that will prepare instantly as many as possible potions, and we'll have enough manapoints for it. It can be done using binary search, because the characteristics of potions of the second type - $c_{i}$ and $d_{i}$ are sorted in non-decreasing order. Time complexity is $O(m\cdot\log k+k)$.
[ "binary search", "dp", "greedy", "two pointers" ]
1,600
#include <iostream> using namespace std; const int max_n = 1000000; int n, m, k; int x, s; int a[max_n], b[max_n], c[max_n], d[max_n]; inline int max_complete(int money_left) { int l = 0, r = k; while (l < r) { int m = (l + r + 1) / 2; if (d[m] <= money_left) l = m; else r = m-1; } return c[l]; } int main() { ios_base::sync_with_stdio(false); cin >> n >> m >> k; cin >> x >> s; a[0] = x; b[0] = 0; c[0] = 0; d[0] = 0; for (int i = 1; i <= m; i++) cin >> a[i]; for (int i = 1; i <= m; i++) cin >> b[i]; for (int i = 1; i <= k; i++) cin >> c[i]; for (int i = 1; i <= k; i++) cin >> d[i]; long long ans = 1LL * n * x; for (int i = 0; i <= m; i++) { int money_left = s - b[i]; if (money_left < 0) continue; ans = min(ans, 1LL * (n - max_complete(money_left)) * a[i]); } cout << ans << endl; return 0; }
734
D
Anton and Chess
Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on $8$ to $8$ board to too simple, he uses an infinite one instead. The first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help. Consider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move. Help Anton and write the program that for the given position determines whether the white king is in check. Remainder, on how do chess pieces move: - Bishop moves any number of cells diagonally, but it can't "leap" over the occupied cells. - Rook moves any number of cells horizontally or vertically, but it also can't "leap" over the occupied cells. - Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't "leap".
Let's observe that the king can attack only pieces that lay in eight directions (up, down, left, right vertically and horizontally, and also up-left, up-right, down-left and down-right diagonally from the cell where the king stands). Also we can observe that from all the pieces that lay in the eight directions, only the nearest one to the king can attack it (the rest of the pieces must "leap" over the nearest one, but it's impossible). So, we'll keep for all the eight directions the nearest piece to the king, and then we'll check if one of the nearest pieces can attack the king (don't forget that bishops can attack only diagonally, rooks - vertically and horizontally, queens - in all the directions). Time complexity is $O(n)$.
[ "implementation" ]
1,700
#include <cstdio> #include <algorithm> using namespace std; inline char in_char() { char c = '\0'; while (c <= ' ') c = getchar(); return c; } inline int in_int() { int n; scanf("%d", &n); return n; } struct figurine { char kind; int x, y; }; int n; int x0, y0; figurine nearest[8]; inline int dist(int x1, int y1, int x2, int y2) { return max(abs(x1 - x2), abs(y1 - y2)); } inline void upd_nearest(figurine& was, const figurine& cur) { if (was.kind == '?' || dist(x0, y0, cur.x, cur.y) < dist(x0, y0, was.x, was.y)) was = cur; } inline int get_direction(const figurine& cur) { // vertical if (cur.x == x0 && cur.y < y0) return 0; if (cur.x == x0 && cur.y > y0) return 1; // horizontal if (cur.y == y0 && cur.x < x0) return 2; if (cur.y == y0 && cur.x > x0) return 3; // diagonal 1 if ((cur.y - y0) == (cur.x - x0) && cur.x < x0) return 4; if ((cur.y - y0) == (cur.x - x0) && cur.x > x0) return 5; // diagonal 2 if ((cur.y - y0) == (x0 - cur.x) && cur.y < y0) return 6; if ((cur.y - y0) == (x0 - cur.x) && cur.y > y0) return 7; // the piece doesn't lie on any of the eight directions return -1; } int main() { n = in_int(); x0 = in_int(); y0 = in_int(); for (int i = 0; i < 8; i++) nearest[i].kind = '?'; // read and update nearest for (int i = 0; i < n; i++) { figurine cur; cur.kind = in_char(); cur.x = in_int(); cur.y = in_int(); int dir = get_direction(cur); if (dir >= 0) upd_nearest(nearest[dir], cur); } bool ans = false; // check verticals and horizontals for (int i = 0; i < 4; i++) if (nearest[i].kind == 'R' || nearest[i].kind == 'Q') ans = true; // check diagonals for (int i = 4; i < 8; i++) if (nearest[i].kind == 'B' || nearest[i].kind == 'Q') ans = true; // output puts(ans ? "YES" : "NO"); return 0; }
734
E
Anton and Tree
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph. There are $n$ vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white). To change the colors Anton can use only operations of one type. We denote it as $paint(v)$, where $v$ is some vertex of the tree. This operation changes the color of all vertices $u$ such that all vertices on the shortest path from $v$ to $u$ have the same color (including $v$ and $u$). For example, consider the tree and apply operation $paint(3)$ to get the following: Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
At first, let's observe that if we unite some two vertices connected by an edge, that are the same color, in one vertex, the answer will not change. Let's do this. Then, for instance, the tree will look in this way: We'll also do such tree "compression" after every painting operation. Then, for instance, the tree will change after $paint(2)$ operation and the tree "compression" in this way: It's obvious that the tree will be painted in one color if and only if, when after such painting operations with the "compression" only one vertex remains. Let's call the tree diameter maximal possible shortest path between two vertices of the tree. It's not hard to observe that the tree will be painted in one color if and only if, when the tree diameter becomes equal to $0$, because the diameter is $0$ only in the tree with one vertex. Then, we'll see the following fact: the tree diameter can't be decreased more than by two per one painting operation with the "compression". So the answer cannot be less than $\textstyle{\frac{d+1}{2}}$, where $d$ is the tree diameter. Now, we'll prove that it's always possible to paint the tree in $\textstyle{\frac{d+1}{2}}$ operations. Find such vertex that the shortest path from it to any other vertex doesn't exceed $\textstyle{\frac{d+1}{2}}$. Such vertex can always be found, because otherwise the tree diameter won't be less that $d + 1$, which is impossible. Now see that if we paint this vertex $\textstyle{\frac{d+1}{2}}$ times, we will paint the tree in one color. Time complexity is $O(n)$.
[ "dfs and similar", "dp", "trees" ]
2,100
#include <iostream> #include <vector> #include <algorithm> using namespace std; int n; vector <int> color; vector < vector <int> > g; vector <char> used; vector <int> comp; int n1; vector < vector <int> > g1; vector <int> dp; int ans = 0; void dfs1(int v, int col, int cmp) { if (used[v]) return; if (color[v] != col) return; used[v] = true; comp[v] = cmp; for (int i = 0; i < g[v].size(); i++) { int to = g[v][i]; dfs1(to, col, cmp); } } void dfs2(int v, int p = -1) { int mx1 = 0, mx2 = 0; for (int i = 0; i < g1[v].size(); i++) { int to = g1[v][i]; if (to == p) continue; dfs2(to, v); int val = dp[to] + 1; mx2 = max(mx2, val); if (mx1 < mx2) swap(mx1, mx2); } dp[v] = mx1; ans = max(ans, mx1 + mx2); } int main() { ios_base::sync_with_stdio(false); cin >> n; color.resize(n); g.resize(n); comp.resize(n); used.assign(n, false); for (int i = 0; i < n; i++) cin >> color[i]; for (int i = 1; i < n; i++) { int a, b; cin >> a >> b; a--, b--; g[a].push_back(b); g[b].push_back(a); } for (int i = 0; i < n; i++) if (!used[i]) dfs1(i, color[i], n1++); g1.resize(n1); dp.resize(n1); for (int i = 0; i < n; i++) for (int j = 0; j < g[i].size(); j++) { int to = g[i][j]; if (comp[i] != comp[to]) g1[comp[i]].push_back(comp[to]); } dfs2(0); cout << (ans + 1) / 2 << endl; return 0; }
734
F
Anton and School
Anton goes to school, his favorite lessons are arraystudying. He usually solves all the tasks pretty fast, but this time the teacher gave him a complicated one: given two arrays $b$ and $c$ of length $n$, find array $a$, such that: $\begin{array}{l}{{\displaystyle\int b_{i}=(a_{i}~a n d~a_{1})+(a_{i}~a n d~a_{2})+\cdot\cdot\cdot+(a_{i}~a n d~a_{n}),}}\\ {{\displaystyle\left(c_{i}=(a_{i}~o r~a_{1})+(a_{i}~o r~a_{2})+\cdot\cdot\cdot+(a_{i}~o r~a_{n}),}}\end{array}\right.$ where $a and b$ means bitwise AND, while $a or b$ means bitwise OR. Usually Anton is good in arraystudying, but this problem is too hard, so Anton asks you to help.
We'll prove that $(a\;a n d\;b)+(a\;o r\;b)=(a+b)$. At first, let's prove that it's true when $a\in0.1$ and $b\in0.1$. To do it, let's consider all the possible values of $a$ and $b$: $\left[\begin{array}{l l l}{{\frac{\alpha}{1}\left[\begin{array}{l l l}{{0}}&{{\mid\alpha{\mathrm{~and~}}\underbrace{{\mathrm{b}}}{0}}\right]}}\\ {{\frac{\mid\scriptstyle0}{\mid\begin{array}{l}{{\frac{{\mathrm{a}}}{{\mathrm{1}}}}{{\frac{{\mathrm{\small0}}}{{\mathrm{\small0}}}{{\frac{{\mathrm{\small1}}}{{\frac{{\mathrm{\small1}}{{\mathrm{\small1}}}{{\mathrm{\small1}}}{{\mathrm{\small1}}}{{\mathrm{\small1}}}{{\mathrm{\small1}}}{{\frac{{\mathrm{\small1}}}}}}}}\end{array}}}}}}}\end{array}\right]$ Here we can see that the equality is true. Now, we'll prove it for any positive integers. To do it, let's divide $a$ and $b$ into bits: $a=b a_{0}\cdot2^{0}+b a_{1}\cdot2^{1}+\cdot\cdot\cdot$ $b=b b_{0}\cdot2^{0}+b b_{1}\cdot2^{1}+\cdot\cdot\cdot$ Here $ba_{0}, ba_{1}, ...$ mean the bits of $a$ and $bb_{0}, bb_{1}, ...$ mean the bits of $b$. Now, let's divide $(a and b)$ and $(a or b$) into bits: $(a~a n d~b)=(b a_{0}~a n d~b b_{0})\cdot2^{0}+(b a_{1}~a n d~b b_{1})\cdot2^{1}+\cdot\cdot\cdot$ $(a~o r~b)=(b a_{0}~o r~b b_{0})\cdot2^{0}+(b a_{1}~o r~b b_{1})\cdot2^{1}+\cdot\cdot\cdot$ Rewrite the initial equality: $\begin{array}{c}{{(b a_{0}\ a n d\ b_{0})\cdot2^{0}+(b a_{1}\,a n d\ b_{1})\cdot2^{1}+\cdot\cdot\cdot+(b a_{0}\ o r\ b b_{0})\cdot2^{0}+(b a_{1}\ o r\ b b_{1})\cdot2^{0}+(b a_{1}\ o r\ b b_{1})\cdot2^{-1}+(b a_{0}\ o n\ d\cdot b b_{0})\cdot2^{-1}+(b a_{0}\circ n\ d\cdot2^{-1}+\cdot\cdot\cdot)}}\\ {{2^{1}+\cdot\cdot\cdot=b a_{0}\cdot2^{0}+b a_{1}\cdot2^{1}+\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot}}\end{array}$ Now it's not hard to observe that $(b a_{0}\ a n d\ b b_{0})\cdot2^{0}+(b a_{0}\ \ o r\ b b_{0})\cdot2^{0}=b a_{0}\cdot2^{0}+b b_{0}\cdot2^{0}$ is true because the equality $(a\;a n d\;b)+(a\;o r\;b)=(a+b)$ is true for bits. Similarly, we see that $(b a_{1}\ a n d\ b_{1})\cdot2^{1}+(b a_{1}\ o r\ b b_{1})\cdot2^{1}=b a_{1}\cdot2^{1}+b b_{1}\cdot2^{1}$ is true and so on. From all this it follows that the equality $(a\;a n d\;b)+(a\;o r\;b)=(a+b)$ is true. Let's create an array $d_{i}$ where $d_{i}=b_{i}+c_{i}$. It's obvious that $\begin{array}{c}{{d_{i}=\left(a_{i}\,a n d\,a_{1}\right)+\left(a_{i}\,a n d\,a_{2}\right)+\cdot\cdot\cdot+\left(a_{i}\,a n d\,a_{n}\right)+\left(a_{i}\,o r\,\,a_{1}\right)+\left(a_{i}\,o r\,\,a_{2}\right)+\cdot\cdot u_{n}(x_{i})+\cdot\cdot u_{n}(x_{i})+\cdot u_{1}(x)\,.}}\\ {{\cdot\cdot\cdot+\left(a_{i}\,o r\,\,a_{n}\right)=n\cdot a_{i}+a_{1}+a_{2}+\cdot\cdot+a_{n}.}}\end{array}$ See that $\begin{array}{c}{{d_{1}+d_{2}+\cdot\cdot\cdot+d_{n}=n\cdot(a_{1}+a_{2}+\cdot\cdot\cdot\cdot+a_{n})+n\cdot a_{1}+n\cdot a_{2}+\cdot\cdot\cdot\cdot+n\cdot a_{n}=}}\\ {{2\cdot n\cdot(a_{1}+a_{2}+\cdot\cdot\cdot\cdot+a_{n}),}}\end{array}$ from where $a_{1}+a_{2}+\cdot\cdot\cdot+a_{n}={\frac{d_{1+d_{2}+\cdots+d_{n}}}{2n}}.$ Now it's not hard to find $a_{i}$: $\theta_{i}={\frac{d_{i}-(a_{1}+a_{2}+\cdots+a_{n})}{n}}.$ Now, we only must check the answer for correctness. It's obvious then, if answer exists, it's alway unique, because it's explicitly derived from the formula above. To check if the answer exists, let's build arrays $b$ and $c$ from the found array $a$ and compare it with the arrays given in the input. We'll do this separately for every bit. Let's calculate $k_{j}$ - amount of numbers in array $a$ that has a one in the $j$-th bit. Let's denote the $j$-th bit of $a_{i}$ as $A_{i, j}$. Now, let's count $B_{i, j}$ and $C_{i, j}$ such as $B_{i j}=(A_{1,j}~a n d~A_{i,j})+(A_{2,j}~a n d~A_{i,j})+\cdots+(A_{n,j}~a n d~A_{i,j}),$ $C_{i,j}=(A_{1,j}~o r~A_{i,j})+(A_{2,j}~o r~A_{i,j})+\cdot\cdot\cdot+(A_{n,j}~o r~A_{i,j}),$ It's not hard to do since we know $k_{j}$: $\begin{array}{l c r}{{B_{i,j}=0,\,i f\,\,A_{i,j}=0,}}\\ {{B_{i,j}=k_{j},\,i f\,\,A_{i,j}=1.}}\\ {{C_{i,j}=k_{j},\,i f\,\,A_{i,j}=0,}}\\ {{C_{i,j}=n,\,i f\,\,A_{i,j}=1.}}\end{array}$ See that if we calculate $B_{i, j}$ and $C_{i, j}$, it will be easy to find $b_{i}$ and $c_{i}$: $b_{i}=B_{i.0}\cdot2^{0}+B_{i.1}\cdot2^{1}+\cdot\cdot\cdot$ $c_{i}=C_{i\alpha}\cdot2^{0}+C_{i\cdot1}\cdot2^{1}+\dots$ Time complexity is $O(n\cdot\log v a l)$, where $v a l=\operatorname*{max}(a_{1},a_{2},\cdot\cdot\cdot,a_{n})$.
[ "bitmasks", "constructive algorithms", "implementation", "math" ]
2,500
#include <iostream> using namespace std; const int max_n = 300000; int n; int b[max_n]; int c[max_n]; int a[max_n]; int d[max_n]; int b1[max_n]; int c1[max_n]; int bits[31][max_n]; int kbit[31]; int main() { // input ios_base::sync_with_stdio(false); cin >> n; for (int i = 0; i < n; i++) cin >> b[i]; for (int i = 0; i < n; i++) cin >> c[i]; for (int i = 0; i < n; i++) d[i] = b[i] + c[i]; // searching for answer long long sum = 0; for (int i = 0; i < n; i++) sum += d[i]; sum /= (2 * n); for (int i = 0; i < n; i++) a[i] = (d[i] - sum) / n; // checking the answer for (int i = 0; i < n; i++) if (a[i] < 0) { cout << -1 << endl; return 0; } for (int i = 0; i < 31; i++) for (int j = 0; j < n; j++) if ((a[j] & (1LL << i)) == 0) bits[i][j] = 0; else bits[i][j] = 1; for (int i = 0; i < 31; i++) { kbit[i] = 0; for (int j = 0; j < n; j++) kbit[i] += bits[i][j]; } for (int i = 0; i < n; i++) b1[i] = 0; for (int i = 0; i < n; i++) c1[i] = 0; for (int i = 0; i < 31; i++) for (int j = 0; j < n; j++) { int bbase = bits[i][j] ? kbit[i] : 0; int cbase = bits[i][j] ? n : kbit[i]; b1[j] += bbase << i; c1[j] += cbase << i; } for (int i = 0; i < n; i++) if (b1[i] != b[i] || c1[i] != c[i]) { cout << -1 << endl; return 0; } // output for (int i = 0; i < n; i++) cout << a[i] << " "; cout << endl; return 0; }
735
A
Ostap and Grasshopper
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length $n$ such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect. Ostap knows that grasshopper is able to jump to any empty cell that is \textbf{exactly} $k$ cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if $k = 1$ the grasshopper can jump to a neighboring cell only, and if $k = 2$ the grasshopper can jump over a single cell. Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.
Problem on programming technique. You have to find at which positions are grasshoper and insect. If k does not divide the difference of position, then answer is NO. Otherwise we have to check positions pos+k, pos+2k, ..., where pos is the minimal poisiton of grasshoper and insect. If somewhere is an obstacle, then answer is NO, otherwise the answer is YES.
[ "implementation", "strings" ]
800
null
735
B
Urbanization
Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are $n$ people who plan to move to the cities. The wealth of the $i$ of them is equal to $a_{i}$. Authorities plan to build two cities, first for $n_{1}$ people and second for $n_{2}$ people. Of course, each of $n$ candidates can settle in only one of the cities. Thus, first some subset of candidates of size $n_{1}$ settle in the first city and then some subset of size $n_{2}$ is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home. To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that \textbf{the sum of arithmetic mean} of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth $a_{i}$ among all its residents divided by the number of them ($n_{1}$ or $n_{2}$ depending on the city). The division should be done in real numbers without any rounding. Please, help authorities find the optimal way to pick residents for two cities.
First of all, note that n1+n2 chosen ones should be people with top (n1+n2) coeficients. Secondly, if the person with intelegence C will be in the first city then he will contribute to our overall IQ with C/n1 points. So, if n1<n2, then top-n1 ratings should be in the small city and the top-n2 from others - in the big city.
[ "greedy", "number theory", "sortings" ]
1,100
null
735
C
Tennis Championship
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be $n$ players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately. Organizers are still arranging tournament grid (i.e. the order games will happen and who is going to play with whom) but they have already fixed one rule: two players can play against each other only if the number of games one of them has already played \textbf{differs by no more than one} from the number of games the other one has already played. Of course, both players had to win all their games in order to continue participating in the tournament. Tournament hasn't started yet so the audience is a bit bored. Ostap decided to find out what is the maximum number of games the winner of the tournament can take part in (assuming the rule above is used). However, it is unlikely he can deal with this problem without your help.
Let us solve the inverse problem: at least how many competitors should be, if the champion will have n matches. Then there's obvious reccurrent formula: f(n+1)=f(n)+f(n-1) (Let us make the draw in a way, where the champion will play n matches to advance to finals and the runner-up played (n-1) matches to advance the final). So, we have to find the index of maximal fibunacci number which is no more that number in the input.
[ "combinatorics", "constructive algorithms", "greedy", "math" ]
1,600
null
735
D
Taxes
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to $n$ ($n ≥ 2$) burles and the amount of tax he has to pay is calculated as the maximum divisor of $n$ (not equal to $n$, of course). For example, if $n = 6$ then Funt has to pay $3$ burles, while for $n = 25$ he needs to pay $5$ and if $n = 2$ he pays only $1$ burle. As mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial $n$ in several parts $n_{1} + n_{2} + ... + n_{k} = n$ (here $k$ is arbitrary, even $k = 1$ is allowed) and pay the taxes for each part separately. He can't make some part equal to $1$ because it will reveal him. So, the condition $n_{i} ≥ 2$ should hold for all $i$ from $1$ to $k$. Ostap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split $n$ in parts.
The first obvious fact is that the answer for prime numbers is 1. If the number is not prime, then the answer is at least 2. When is it possible? It is possible in 2 cases; when it is sum of 2 primes of its maximal divisor is 2. If 2 divides n, then so does integer n/2. n/2<=2=>n<=4=>n=4, where n is prime. According to Goldbach's conjecture, which is checked for all numbers no more than 10^9, every number is a sum of two prime numbers. Odd number can be sum of two primes, if (n-2) is prime (the only even prime number is 2). Otherwise, the answer is 3 - n=3+(n-3), (n-3) is sum of 2 primes, because it is even.
[ "math", "number theory" ]
1,600
null
735
E
Ostap and Tree
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has $n$ vertices. He wants to paint some vertices of the tree black such that from any vertex $u$ there is at least one black vertex $v$ at distance no more than $k$. \underline{Distance} between two vertices of the tree is the minimum possible number of edges of the path between them. As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo $10^{9} + 7$. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
Problem can be solved by the method of dynamic programming. Let dp[v][i][j] be the number of possibilities to color subtree of vertex v in such a way that the closest black vertex is on depth i, and the closest white vertex - on depth j (we also store dp[v][-1][j] and dp[v][i][-1] in the cases where there are no black and white vertexes in diapason k of v respectively). In order to connect two subtrees, we can check all pairs (i,j) in both subtrees (by brute-force algorithm). Then let we have pair (a,c) in the first subtree and pair (b,d) in the second one. If min(a,c)+max(b,d)<=k, then we update value of current vertex. Complexity of the algorithm O(n*k^4), which is acceptable for this particular problem (n - the number of vertexes, k^4 brute force search of pairs (a,b); (c,d)).
[ "dp", "trees" ]
2,500
null
736
D
Permutations
Ostap Bender is worried that people started to forget that he is the Great Combinator. Now he wants to show them his skills in combinatorics. Now he studies the permutations of length $n$. He has a list of $m$ valid pairs, pair $a_{i}$ and $b_{i}$ means that he is allowed to place integers $b_{i}$ at position $a_{i}$. He knows that the number of permutations that use only valid pairs is \textbf{odd}. Now, for each pair he wants to find out, will the number of valid permutations be \textbf{odd} if he \textbf{removes} this pair (and only it) from the list.
This problem consists of 3 ideas. Idea 1: remainder modulo 2 of the number of permutation is equal to the remainder modulo 2 of the determinant of the matrix whose entries are 1 if (ai,bi) is in our list and 0 otherwise. Idea 2: If we cahnge 1 by 0, then the determinant will differ by algebraic compliment. That is, if we count inverse matrix, than it will reflect reminders modulo 2 (B(m,n)=A'(m,n)/detA, detA is odd). Idea 3: Inverse matrix can be counted for O((n/32)^3) time. However, we can work is field of integers modulo 2. The summation can be replaced by XOR. So if we store in one "int" not a single but 32 numbers, then we can reduce our assymptocy to O(n^3/32), which is OK.
[ "math", "matrices" ]
2,800
null
736
E
Chess Championship
Ostap is preparing to play chess again and this time he is about to prepare. Thus, he was closely monitoring one recent chess tournament. There were $m$ players participating and each pair of players played exactly one game. The victory gives $2$ points, draw — $1$ points, lose — $0$ points. Ostap is lazy, so he never tries to remember the outcome of each game. Instead, he computes the total number of points earned by each of the players (the sum of his points in all games which he took part in), sort these value in non-ascending order and then remembers first $n$ integers in this list. Now the Great Strategist Ostap wonders whether he remembers everything correct. He considers that he is correct if there exists at least one tournament results table such that it will produce the given integers. That means, if we count the sum of points for each player, sort them and take first $n$ elements, the result will coincide with what Ostap remembers. Can you check if such table exists?
Suppose set (a1,a2,...,am). Then the list is valid if set {2m-2, 2m-4, 2m-6, ..., 0} majorizes the set {a1,a2,...,am}. Let us prove it! Part 1: Suppose n<=m. Top n players will play n(n-1)/2 games with each other and n(m-n) games with low-ranked contestants. In these games they will collect 2*n(n-1)/2 points (in each game there is exactly 2 points) for sure and at most 2*n*(m-n) points in games with others. So they will have at most 2*(n*(n-1)/2+n*(m-n))=2*((m-1)+(m-2)+...+(m-n)) points. Now construction: Let's construct results of participant with most points and then use recursion. Suppose the winner has even number of points (2*(m-n) for some n). Then we consider that he lost against contestants holding 2,3,4,...,n places and won against others. If champion had odd number of points (2*(m-n)-1 for some n), then we will construct the same results supposing that he draw with (n+1)th player instead of winning agianst him. It is easy to check that majorization is invariant, so in the end we will have to deal with 1 men competition, when set of scores {a1} is majorized by set {0}. So a1=0, and there is obvious construction for this case. So we have such an algorithm: we search for a compiment set which is majorized by {2m-2,2m-4,...,0}. If there is no such set answer is NO. Otherwise answer is YES and we construct our table as shown above. Assymptosy is O(m^2logm) (calling recursion m times, sorting the array (we can lose non-decreasing order because of poor results) and then passing on it linearly.
[ "constructive algorithms", "flows", "greedy", "math" ]
2,900
null
737
E
Tanya is 5!
Tanya is now five so all her friends gathered together to celebrate her birthday. There are $n$ children on the celebration, including Tanya. The celebration is close to its end, and the last planned attraction is gaming machines. There are $m$ machines in the hall, they are numbered $1$ through $m$. Each of the children has a list of machines he wants to play on. Moreover, for each of the machines he knows the exact time he wants to play on it. For every machine, no more than one child can play on this machine at the same time. It is evening already, so every adult wants to go home. To speed up the process, you can additionally rent second copies of each of the machines. To rent the second copy of the $j$-th machine, you have to pay $p_{j}$ burles. After you rent a machine, you can use it for as long as you want. How long it will take to make every child play according to his plan, if you have a budget of $b$ burles for renting additional machines? There is only one copy of each machine, so it's impossible to rent a third machine of the same type. The children can interrupt the game in any moment and continue it later. If the $i$-th child wants to play on the $j$-th machine, it is allowed after you rent the copy of the $j$-th machine that this child would play some part of the time on the $j$-th machine and some part of the time on its copy (each of these parts could be empty). The interruptions and changes take no time and can be performed in any integer moment of time. Of course, a child can't play on more than one machine at the same time. Remember, that it is not needed to save money (no one saves money at the expense of children happiness!), it is needed to minimize the latest moment of time some child ends his game.
The problem was invented by the recollections of the recent celebration of the fifth birthday of Tanya Mirzayanova. At first let's solve this problem in simplified form: let there is no duplicate machines (in the other word it does not enough the budget $b$ to rent any duplicate). We consider, that each kid would like to play in each machine. Let $t_{i, j} = 0$ in such case. So, we consider, that the values of $t$ is a rectangular table - for each pair kid/machine in the cell written down the time of the game. Note that minimal time when all games will ended does not less than sum of values in each row $R_{i} = t_{i, 1} + t_{i, 2} + ... + t_{i, m}$. Similarly, the minimal time when all games will ended does not less than the sum in each column $C_{j} = t_{1, j} + t_{2, j} + ... + t_{n, j}$, because on each machine in one moment of time can play no more than one kid. Because of that the minimal time does not less than $max(R_{1}, R_{2}, ..., R_{n}, C_{1}, C_{2}, ..., C_{m})$. Note that there is always such a schedule that needed minimal time equals to maximum of all rows sums and all columns sums. Let's call this value $T$. Now we need to show this fact and consider the way to get this schedule. Let's build the weighted bipartite graph. In each part of this graph is $n + m$ vertices. Let's assume that each machine has a fake kid (i. e. now we have $n + m$ kids) - $n$ real and $m$ fake kids. The vertices from the first part will for kids: $u_{1}, u_{2}, ..., u_{n}$ - for real kids and $u_{n + 1}, u_{n + 2}, ..., u_{n + m}$ - for fake kids, and $u_{n + j}$ is a fake kid for the machine $j$. Similarly, let consider that each kid has a fake machine (totally there will be $n$ machines). The vertices from the second part will for machines: the first $m$ vertices is for real machines ($v_{1}, v_{2}, ..., v_{m}$), and following $n$ for fakt machines ($v_{m + 1}, v_{m + 2}, ..., v_{m + n}$). The vertex $v_{m + i}$ will for the fake machine of kid $i$. Let's make the edges. We will have 4 types of edges: between the real kids and the real machines, between the fake kids and the real machines, between the real kids and the fake machines, between the fake kids and the fake machines. We need to make the edges in such a way that the sum of weights of incident edges for each vertex is equals to $T$. The edges of type 1. Let's add the edge between $u_{i}$ and $v_{j}$, if $t_{i, j} > 0$. the weight is $t_{i, j}$. This edge means that the kid must play on the machine needed number of minutes. The edges of type 2. This edges mean that the machine will has downtime equals to some number of minutes (in the other words in downtime the fake kid will play on this machine). For all $j$ from 1 to $m$ let's find $a - C_{j}$. If such vertices is positive, then we need to add edge between $u_{n + j}$ and $v_{j}$ with such weight. The edges of type 3. This edges mean that the kid will have time, when he does not play (we consider that in this time the kid play on the fake machine). For all $i$ from 1 to $n$ let's find $a - R_{i}$. If this value is positive we add edge between $u_{i}$ and $v_{m + i}$ with such weight. The edges of type 4. After we added the edges of types 1-3 it is easy to show that the sum of weights of incident edges equal to $T$. For the vertices $u_{n + 1}, u_{n + 2}, ..., u_{n + m}, v_{m + 1}, v_{m + 2}, ..., v_{m + n}$ this sum now less or equal to $T$. Let's add remaining edges to make this sums equal to $T$. It's always possible if we add this edges in greedy way. We know the following fact: in any regular bipartite graph there is a perfect matching (a consequence of the Hall's theorem). If we look on the given graph like on the unweighted multigraph where the weight of the edge in our graph equals to the number of edges between the pair of vertices, then the resulting graph will be regular graph and for it will be correct described fact (i. e. there is perfect matching in this graph). Let's find the perfect matching with help of the Kuhn's algorithm in weighted graph. Let's choose the weight of the minimal edge and it is equals to $M$. Then let's appoint kids on machines for each edge between the vertices $u_{1}, u_{2}, ..., u_{n}$ and $v_{1}, v_{2}, ..., v_{m}$ on the time $M$. Also let's subtract $M$ from the weight of each edge of the matching. If the weight of the edge became 0, we delete this edge. After that it is correct the sum for each vertices is a constant. It means that the remaining graph has the perfect matching. We need to make with this graph similar operations, which was described above. Let's do it until the graph contains at least one edge. So we found needed schedule. To make the solution faster we can rebuild the matching from the unsaturated vertices from the first part if such vertices exist. This algorithm will works totally in $O(e^{2})$, where $e$ is the number of edges in the beginning, i. e. $e = O(nm)$, so the asymptotic behavior is $O(n^{2}m^{2}$). In this problem there were small restricts so we could build the matching with Kuhn's algorithm. By the way we build the optimal painting of the bipartite graph. Here we can use the well known algorithm (read about the optimal painting of the bipartite graph). So, we solved the problem without rent the duplicates. Besides it, the value of the answer is a maximum from all sums of rows and columns of the table with times for pairs kid/machine. If we have a duplicated it equals to adding the column in which we can partially distribute the values from this column. Of course, it is profitably to make it with columns which sum $C_{j} = T$ (i. e. the answer rests in this column). This operation makes sense only if we make it for all columns with $C_{j} = T$ simultaneously. The algorithm to choose of machines to rent follows. Let's find the sum of rent for all machines with $C_{j} = T$. If this value less or equal to the budget $b$ than we must rent this machines. Then add the appropriate columns in the table and put as evenly as possible the values of the duplicated columns. Recalculate $T$. Repeat the process and end it when the sum of rent for each operation became more than $b$.
[ "graph matchings", "graphs", "greedy", "schedules" ]
3,300
null
737
F
Dirty plates
After one of celebrations there is a stack of dirty plates in Nikita's kitchen. Nikita has to wash them and put into a dryer. In dryer, the plates should be also placed in a stack also, and the plates sizes should increase down up. The sizes of all plates are distinct. Nikita has no so much free space, specifically, he has a place for only one more stack of plates. Therefore, he can perform only such two operations: - Take any number of plates from $1$ to $a$ from the top of the dirty stack, wash them and put them to the intermediate stack. - Take any number of plates from $1$ to $b$ from the top of the intermediate stack and put them to the stack in the dryer. Note that after performing each of the operations, the plates are put in the same order as they were before the operation. You are given the sizes of the plates $s_{1}, s_{2}, ..., s_{n}$ in the down up order in the dirty stack, and integers $a$ and $b$. All the sizes are distinct. Write a program that determines whether or not Nikita can put the plates in increasing down up order in the dryer. If he is able to do so, the program should find some sequence of operations (not necessary optimal) to achieve it.
At first we wil try to solve the problem without taking the restrictions placed on $a$ and $b$ into consideration. If we can't solve the new problem, we surely can't solve the original one with the restrictions on $a$ and $b$. Let's examine the operations we can and can't do. It's easy to understand that we can't place any plates into the dryer which wouldn't fit the sequence, because they can't be removed from that stack. It is also clear that if we are able to take a sequence of plates from the top of the intermediate stack onto the top of the dryer stack and they would fit the proper sequence in the dryer stack, it can be done immediately. This statement is also right for the top of dirty stack, but it would take two operations for the plates to end up in the drier. Alos, it's easy to notice a situation which makes it impossible to reach the answer: if there is a plate with the size $y$ right above the plate with the size $x$ in the intermediate stack, and $y < x - 1$. Indeed, no sequence of operations will allow us to insert the <<missing>> plates in between them. Let's call the state of the stacks a dead-end if this situation happens. Let's call the operation which moves the plates into the dryer in the right sequence an output. Because the output can be done at any moment, let's check the possibility of the output when we finish performing any operation and perform the output whenever we can. In the following paragraphs, we will examine the situations where the output is impossible. Let's call the sequence of the plates an almost decreasing sequence if it consists of one or more sections and in every section the sizes of the plates are consecutive natural numbers, and all plates in the following sections are smaller than in the previous ones. To describe it in another way, this is how an almost decreasing sequence looks like: $x_{1}, x_{1} + 1, x_{1} + 2, ..., y_{1}, x_{2}, x_{2} + 1, x_{2} + 2, ..., y_{2}, x_{3}, ...$, where $x_{1} > y_{2}$, $x_{2} > y_{3}$ and so on. Let's examine the maximum almost decreasing sequence on the top of the dirty stack. It's easy to see that before we move all plates from that sequence to the intermediate stack the operation which moves a plate that does not belong to that sequence to the intermediate stack would create a dead-end, because the size of the last plate in this sequence is at least $2$ less than the size of the next plate. It's also clear that we can't perform an output before moving all of the sequence into the intermediate stack. This means that the only actions we can perform will lead to all of the plates of this sequence ending up in the intermediate stack, but the question is in the order in which they will be placed. There are two cases possible: The sizes of the plates in this sequence form an continious segment of the natural number sequence, which means that $y_{2} = x_{1} - 1$, $y_{3} = x_{2} - 1$ and so on. In this situation we can move sections one-by-one onto the intermediate stack to be able to move all of it to the dryer later at once. It's obvious that there wouldn't be a dead-end inside of the sequence. If the dead-end situation happened on a junction with the lower plates in this stack, it would have happened no matter the way we move the sequence. A similiar statement can be said about the junction with the plates that would later appear on the top of this sequence. This means that our way of moving plates is optimal, therefore let's perform it. There are <<holes>> in the set of plate sizes in the sequence. Then we can notice that if we won't move the sequence to the intermediate stack with one operation, we will arrive at the dead-end if we try to move this sequence with any other set of operations. This can be shown more formally by assuming we moved a part of sequence that was higher than <<hole>> below it or vice-versa, the part that was below the <<hole>> above it. In this situation, we have no choice but to move a sequence as a whole. We found an optimal operation for every situation and that means we can solve the problem with $a = b = \infty $ by modelling an optimal turn by using $O(n^{2})$ time, or $O(n)$ if we want so. If all plates end up in the dryer, our order of operations is the solution, otherwise there's no solution. Let's now discuss how to incorporate our solution for $a = b = \infty $ to our problem with finite $a$ and $b$. The output from the dirty stack can still be performed by moving plates one-by-one to the intermediate stack and then moving them from the intermediate stack one-by-one. Output from the intermediate stack isn't always possible, and because of this you have to keep an eye on the size of the sections in the intermediate stack. However, if an output exists that is possible to perform, we must perform it, and if it isn't possible, we won't be able to put the plates into the correct order. Due to this we assume that all possible outputs are done. Again we will examine the maximum almost decreasing sequence on the top of the dirty stack and there are again two similiar cases:: If <<holes>> exist, the only possible operation, as discussed earlier, is to move the whole sequence. If the length of this sequence exceeds $a$, we have no way to place the plates in the right order at all. If there are no <<holes>>, there are several possibilities. The length of the sections is now important and that means it isn't always optimal to put the plates into the ascending order. Let's consider several cases: If $a$ and $b$ are big enough to be able to do the same operations with it as if they were infinite. Then we need to do it because if any other section would join this one from above or below this would be the only situation that wouldn't be a dead-end. Otherwise we would be able to output this sequence by using a single operation, and because of the fact that its size does not exceed $b$ it would be a possible and optimal operation. In any other situation we have to move this sequence to the intermediate stack in some other way. Let's consider the case where the length of the sequence exceeds $b$. There are several cases: If the sequence consists of a lone section, we need to move it so the sizes of plates in the section would form a descending sequence in the intermediate stack by moving the plates one-by-one. Indeed, there's no way to make the smallest plate the top one or to make the biggest plate the bottom one (it would allow our sequence to join other blocks) without meeting a dead-end or making a section with its length bigger than $b$, so it's optimal to make all sections as short as possible (length $1$) so we would certainly be able to output them. In the case of the sequence having more than two sections, the only way to move them without creating a dead-end is to move the section as a whole. If it's impossible, there's no solution. The only case left here is the case of the sequence consisting of two sections. There are only two ways to move those sections without meeting a dead-end - we either move the part of the top section and then we move everything else, or we move the first section and the part of the second and then we move the remaining part of the second section. We have to make the length of the parts we move to be no more than $a$ and the length of the resulting sections to be no more than $b$. It's easy to write the inequalities which describe whether these operations are possible. It's also easy to check that we can't make the smallest plate the top one or to make the biggest plate the bottom one and that means our sections wouldn't join any other sections. Because of this, any sequence of moves which satisfies the inequalities would suit us. Let's now assume that $b$ is large enough to move the whole sequence at once, but $a$ is smaller than the size of a particular section and so we are unable to sort the sequence into the ascending order. If there is only one section, we can just move them one-by-one as discussed earlier. If there are more than two sections, we are unable to move them without meeting a dead-end If there are two sections, the situation is similiar to the situation where we couldn't perform our operations due to $b$ being too small, although we don't have to limit the length of the section after moving our plates to the intermediate stack (because it would be less than $b$). As we can see, there's an optimal operation on an every step. The solution is to model the optimal operations. A program that would solve this problem in $O(n)$ time could be written, but the constraints were set which allowed to write the solution which would run in $O(n^{2})$ time so as not to complicate matters with extra operations. As we can see, there's an optimal operation on an every step. The solution is to model the optimal operations. A program that would solve this problem in $O(n)$ time could be written, but the constraints were set which allowed to write the solution which would run in $O(n^{2})$ time so as not to complicate matters with extra operations.
[ "constructive algorithms", "math" ]
3,300
null
739
A
Alyona and mex
Alyona's mother wants to present an array of $n$ non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects $m$ of its subarrays. Subarray is a set of some subsequent elements of the array. The $i$-th subarray is described with two integers $l_{i}$ and $r_{i}$, and its elements are $a[l_{i}], a[l_{i} + 1], ..., a[r_{i}]$. Alyona is going to find mex for each of the chosen subarrays. Among these $m$ mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible. You are to find an array $a$ of $n$ elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible. The mex of a set $S$ is a minimum possible non-negative integer that is not in $S$.
Obviously, the answer to the problem can not be greater than the minimum length among the lengths of the sub-arrays. Suppose that the minimum length of all the sub-arrays is equal to len. Then the desired array is: $0, 1, 2, 3, ..., len - 1, 0, 1, 2, 3, ... len - 1...$. Not hard to make sure that mex of any subarray will be at least len.
[ "constructive algorithms", "greedy" ]
1,700
null
739
B
Alyona and a tree
Alyona has a tree with $n$ vertices. The root of the tree is the vertex $1$. In each vertex Alyona wrote an positive integer, in the vertex $i$ she wrote $a_{i}$. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges). Let's define $dist(v, u)$ as the sum of the integers written on the edges of the simple path from $v$ to $u$. The vertex $v$ controls the vertex $u$ ($v ≠ u$) if and only if $u$ is in the subtree of $v$ and $dist(v, u) ≤ a_{u}$. Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex $v$ what is the number of vertices $u$ such that $v$ controls $u$.
Let's fix a vertex $v$. This node adds +1 to all the ancestors whose depth $depth[v] - a[v] \le depth[p]$ ($depth[v]$ = the sum of the weights of edges on the path from the root to the vertex $v$). It's a segment of the ancestors, ending in v, as the depth increases when moving to the leaves. It remains to find the first ancestor on the way up, it does not hold for him - so you can make a binary lifting or binary search, if you will be storing the path to the root in dfs. With the partial sums you can calculate the answer for each vertices.
[ "binary search", "data structures", "dfs and similar", "graphs", "trees" ]
1,900
null
739
C
Alyona and towers
Alyona has built $n$ towers by putting small cubes some on the top of others. Each cube has size $1 × 1 × 1$. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row. Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from $l_{i}$ to $r_{i}$ and adds $d_{i}$ cubes on the top of them. Let the sequence $a_{1}, a_{2}, ..., a_{n}$ be the heights of the towers from left to right. Let's call as a segment of towers $a_{l}, a_{l + 1}, ..., a_{r}$ a hill if the following condition holds: there is integer $k$ ($l ≤ k ≤ r$) such that $a_{l} < a_{l + 1} < a_{l + 2} < ... < a_{k} > a_{k + 1} > a_{k + 2} > ... > a_{r}$. After each addition of $d_{i}$ cubes on the top of the towers from $l_{i}$ to $r_{i}$, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it.
Let's consider the difference between two adjacent elements of array: $a[i] = arr[i + 1] - arr[i]$. Let us add $d$ in the segment from $l$ to $r$. Then it is clear that in the array $a$ will change no more than two values (at the ends of the addition of the segment), because if $l < i < r$, then $a[i] = arr[i + 1] + d - (arr[i] + d) = arr[i + 1] - arr[i]$. Note that the answer is a sequence of positive elements of $a$ + a sequence of negative elements of $a$ (i.e., ... +1 +1 +1 +1 -1 -1 ..., as the mountain first increases and then decreases). To solve this problem it's enough to take the tree segments and store at each vertex response to the prefix, suffix, and the middle. Two segments [l; m] and [m + 1; r] can be merged in case $sign(a[m + 1]) \le sign(a[m])$ and they are not equal to zero. suffix $+ 1 + 1 + 1 + 1 - 1 - 1 - 1 - 1$ and $- 1 - 1 - 1 - 1$ can be merged with prefix $- 1 - 1 - 1 - 1$ suffix $+ 1 + 1 + 1 + 1$ can be merged with prefix $- 1 - 1 - 1 - 1$ or prefix $+ 1 + 1 + 1 + 1 - 1 - 1 - 1 - 1$ Author's solution: http://codeforces.com/contest/739/submission/22453451
[ "data structures" ]
2,500
#pragma comment(linker, "/stack:20000000") #define _CRT_SECURE_NO_WARNINGS # include <iostream> # include <cstdio> using namespace std; template<class T> int sign(T x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } struct Node { int lval, mval, rval; }; Node tr[2340400]; long long a[1010101]; inline void recalc(int cur, int l, int r) { int m = (l + r) / 2; int dcur = cur + cur; tr[cur].mval = max(tr[dcur].mval, tr[dcur + 1].mval); if (!a[m] || !a[m + 1] || sign(a[m]) < sign(a[m + 1])) { tr[cur].lval = tr[dcur].lval; tr[cur].rval = tr[dcur + 1].rval; } else { tr[cur].mval = max(tr[cur].mval, tr[dcur].rval + tr[dcur + 1].lval); if (tr[dcur].mval == m - l + 1) { tr[cur].lval = tr[dcur].lval + tr[dcur + 1].lval; } else { tr[cur].lval = tr[dcur].lval; } if (tr[dcur + 1].mval == r - m) { tr[cur].rval = tr[dcur + 1].rval + tr[dcur].rval; } else { tr[cur].rval = tr[dcur + 1].rval; } } } void build(int cur, int l, int r) { if (l == r) { int x = !!a[l]; tr[cur] = {x, x, x}; } else { int m = (l + r) / 2; int dcur = cur + cur; build(dcur, l, m); build(dcur + 1, m + 1, r); recalc(cur, l, r); } } void update(int cur, int l, int r, int pos, int val) { if (l == r) { a[pos] += val; int x = !!a[l]; tr[cur] = {x, x, x}; } else { int m = (l + r) / 2; int dcur = cur + cur; if (pos <= m) { update(dcur, l, m, pos, val); } else { update(dcur + 1, m + 1, r, pos, val); } recalc(cur, l, r); } } int arr[1010101]; int main() { #ifdef LOCAL freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d", &arr[i]); } for (int i = 0; i < n - 1; ++i) { a[i] = arr[i + 1] - arr[i]; } if (n > 1) { build(1, 0, n - 2); } int m; scanf("%d", &m); while (m--) { int l, r, d; scanf("%d%d%d", &l, &r, &d); if(n == 1) { puts("1"); continue; } if (l != 1) { update(1, 0, n - 2, l - 2, d); } if (r != n) { update(1, 0, n - 2, r - 1, -d); } printf("%d\n", tr[1].mval + 1); } return 0; }
739
D
Recover a functional graph
Functional graph is a directed graph in which all vertices have outdegree equal to $1$. Loops are allowed. Some vertices of a functional graph lay on a cycle. From the others we can come to a cycle by making a finite number of steps along the edges (we consider only finite functional graphs in this problem). Let's compute two values for each vertex. $precycle_{i}$ is the amount of edges we should pass to get to a vertex which is a part of some cycle (zero, if $i$ itself lies on a cycle), $cycle_{i}$ is the length of the cycle we get to. You are given the information about these values for some functional graph. For each vertex you know the values $precycle_{i}$ and $cycle_{i}$, however, instead of some values there can be the question mark. It means that these values are unknown. Build any functional graph that suits the description or determine that there is no such graph.
Let's think what has to hold after we put numbers in place of question marks: number of vertices with $precycle = 0$ and $cycle = y$ should be divisible by $y$. if there exists a vertex with $precycle = x > 0$ and $cycle = y$, then there should also exist a vertex with $precycle = x - 1$ and $cycle = y$. Now looking at vertices without question marks, let's count for every cycle length $y$ how many vertices have to be added for condition 1 to hold (keeping in mind that this number cannot be $0$ if there exist vertices of the form $(x, y)$ or $(?, y)$) and which precycle lengths are missing for condition 2 to hold. Here it's important that for 2 we have to consider vertices of the form $(x, ?)$. Specifically, in order for everything to be univocally determined, it is necerrary to try all the cycle lengths for the vertex of this form with maximal $x$. Some contestants tried to assign cycle lengths for such vertices greedily and got WA#15. Let's build the network for the flow which will have two parts. Vertices of the left part will correspond to the vertices of the functional graph that have at least one question mark. Vertices of the right part are the requirements of the form "need $k$ vertices of the form $(0, y)$" (for 1 to hold) and "need one vertex of the from $(x, y)$" (for 2 to hold). Add edges from the source to the left part, form the right part to the sink, and between requirements and vertices that satisfy them. If done correctly, with only one vertex created in the left part for all vertices of the same form in the functional graph, there will be $O(n)$ nodes and $O(n)$ edges in the network and the maximum flow will also be $O(n)$. Edmonds-Karp algorithm, which works in $O(E * flow)$ will work in $O(n^{2})$ on this network. Accounting for the bruteforce of the cycle length for the maximal vertex of the form $(x, ?)$ we get $O(n^{3})$ for the whole solution. In practice, any decent algorithm for finding maximum flow would most likely pass the system testing. Dinic works in 15 ms. If all of the vertices in the right part are saturated - the answer is found. Rolling back the flow, we will find which vertices in the left part saturated which ones in the right part. Now we can change the question marks to numbers for those vertices in the left part, that were used, but some question marks might still remain. This is no big deal. Let's change all vertices of the form $(x, ?)$ to $(x, maxc)$, where $maxc$ is that cycle length we bruteforce in the outermost loop. Instead of vertices of the form $(?, y)$ we can write $(1, y)$. Remember, that we created at least one cycle for all such $y$'s. Instead of $(?, ?)$ simply put $(0, 1)$. Now it's quite simple to get the answer to the problem. First create cycles out of the vertices of the form $(0, y)$, and then add edges $(x, y)$ -> $(x - 1, y)$.
[ "graph matchings" ]
3,400
null
739
E
Gosha is hunting
Gosha is hunting. His goal is to catch as many Pokemons as possible. Gosha has $a$ Poke Balls and $b$ Ultra Balls. There are $n$ Pokemons. They are numbered $1$ through $n$. Gosha knows that if he throws a Poke Ball at the $i$-th Pokemon he catches it with probability $p_{i}$. If he throws an Ultra Ball at the $i$-th Pokemon he catches it with probability $u_{i}$. He can throw at most one Ball of each type at any Pokemon. The hunting proceeds as follows: at first, Gosha chooses no more than $a$ Pokemons at which he will throw Poke Balls and no more than $b$ Pokemons at which he will throw Ultra Balls. After that, he throws the chosen Balls at the chosen Pokemons. If he throws both Ultra Ball and Poke Ball at some Pokemon, he is caught if and only if he is caught by any of these Balls. The outcome of a throw doesn't depend on the other throws. Gosha would like to know what is the expected number of the Pokemons he catches if he acts in an optimal way. In other words, he would like to know the maximum possible expected number of Pokemons can catch.
Let's divide Pokemons into 4 types: $0, A, B$ and $AB$ depending on Balls that we throw to them. Let's sort them by $u$ in descending order. Let's iterate over last Pokemon in which we throw Ultra Ball (his type is $B$ or $AB$). Let $i$ be the index of this Pokemon. It is not hard to prove that there are no Pokemons to the left of $i$ that have type $0$ and all Pokemons to the right of $i$ have type $0$ or $A$. Let's sort all Pokemons to the left of $i$ by $(1 - p) * u$ in descending order. Let's iterate last Pokemon of type $AB$. Let $j$ be his index. We can prove that to the left of $j$ every Pokemon has type $AB$ or $B$ (Let's call this group of Pokemons $X$). Between $j$ and $i$ every Pokemon has type $A$ or $B$ (will call them $Y$). To the right of $i$ only $0$ and $A$ (will call them $Z$). We know that we throw an Ultra Ball to every Pokemon in $X$. So let's add to our answer sum of $u$ of all Pokemons in $X$. Number of Pokemons in $Y$ of type $B$ equals to the difference between $b$ (number of Ultra Balls) and size of $X$. Therefore we know number of Pokemons in $Y$ of type $A$ and we know how many Poke Balls are left for $X$ and $Z$ summarily. Not hard to prove that in group $Y$ we should throw Poke Balls to Pokemons with greatest $u - p$. Now we have to understand in which Pokemons in $X$ and $Z$ we should throw Poke Balls. If we throw Poke Ball to Pokemon from $X$, it adds to the answer $p * (1 - u)$, from $Z$ - adds $p$. So we should throw Poke Balls to Pokemons with greatest values. When we iterate over $j$, each iteration one Pokemon moves from $Y$ to $X$. We can keep structure that can add and delete one element, find minimum and keep sum of all elements in the structure. For example, treap or map (in c++). Let's keep 2 such structures: for calculating answer for $Y$ and for calculating answer for throwing Poke Balls to Pokemons in $X$ and $Z$. The complexity - O($n^{2} \cdot logn$).
[ "brute force", "data structures", "dp", "flows", "math", "probabilities", "sortings" ]
3,000
null
740
A
Alyona and copybooks
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for $a$ rubles, a pack of two copybooks for $b$ rubles, and a pack of three copybooks for $c$ rubles. Alyona already has $n$ copybooks. What is the minimum amount of rubles she should pay to buy such number of copybooks $k$ that $n + k$ is divisible by $4$? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase.
Let $k$ - is the smallest non-negative integer such that $n + k$ is a multiple of 4. If $k$ is 0, then, obviously, the answer is 0. If $k$ is equal to 1, then you can buy one set of one notebook, you can buy 3 sets of three notebooks, you can buy 1 set of three notebooks and 1 set of two notebooks. Take the most optimal response. If $k$ equals 2, you can buy 2 sets of one notebook, 1 set of two notebooks, two sets of three notebooks. Take the most optimal response. If $k$ is equal to 3, you can buy 3 sets of one book, 1 set of single and 1 set of two notebooks, one set of three notebooks. Take the most optimal response.
[ "brute force", "implementation" ]
1,300
null
740
B
Alyona and flowers
Little Alyona is celebrating Happy Birthday! Her mother has an array of $n$ flowers. Each flower has some mood, the mood of $i$-th flower is $a_{i}$. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in. For example, consider the case when the mother has $5$ flowers, and their moods are equal to $1, - 2, 1, 3, - 4$. Suppose the mother suggested subarrays $(1, - 2)$, $(3, - 4)$, $(1, 3)$, $(1, - 2, 1, 3)$. Then if the girl chooses the third and the fourth subarrays then: - the first flower adds $1·1 = 1$ to the girl's happiness, because he is in one of chosen subarrays, - the second flower adds $( - 2)·1 = - 2$, because he is in one of chosen subarrays, - the third flower adds $1·2 = 2$, because he is in two of chosen subarrays, - the fourth flower adds $3·2 = 6$, because he is in two of chosen subarrays, - the fifth flower adds $( - 4)·0 = 0$, because he is in no chosen subarrays. Thus, in total $1 + ( - 2) + 2 + 6 + 0 = 7$ is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this! Alyona can choose any number of the subarrays, even $0$ or all suggested by her mother.
If you restate the problem, it is clear that you need to take sub-arrays that have positive sum.
[ "constructive algorithms" ]
1,200
null
741
A
Arpa's loud Owf and Mehrdad's evil plan
As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from $1$ to $n$. Everyone has exactly one crush, $i$-th person's crush is person with the number $crush_{i}$. Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person $x$ wants to start a round, he calls $crush_{x}$ and says: "Oww...wwf" (the letter w is repeated $t$ times) and cuts off the phone immediately. If $t > 1$ then $crush_{x}$ calls $crush_{crushx}$ and says: "Oww...wwf" (the letter w is repeated $t - 1$ times) and cuts off the phone immediately. The round continues until some person receives an "Owf" ($t = 1$). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest $t$ ($t ≥ 1$) such that for each person $x$, if $x$ starts some round and $y$ becomes the Joon-Joon of the round, then by starting from $y$, $x$ would become the Joon-Joon of the round. Find such $t$ for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. $crush_{i} = i$).
Make a directed graph and put edge from $i$ and $crush_{i}$. If the graph has vertex such that its in-degree is 0 then obviously answer doesn't exist. Otherwise, the graph consists of some cycles. For each cycle suppose that its length is $len$. If it has odd length, add $len$ to $S$, otherwise, add $len / 2$. The answer is the LCM of numbers in $S$. Time complexity: ${\cal O}(n)$.
[ "dfs and similar", "math" ]
1,600
null
741
B
Arpa's weak amphitheater and Mehrdad's valuable Hoses
Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight $w_{i}$ and some beauty $b_{i}$. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses $x$ and $y$ are in the same friendship group if and only if there is a sequence of Hoses $a_{1}, a_{2}, ..., a_{k}$ such that $a_{i}$ and $a_{i + 1}$ are friends for each $1 ≤ i < k$, and $a_{1} = x$ and $a_{k} = y$. Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most $w$ weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than $w$ and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed $w$.
It's a simple knapsack problem. Let's solve this version of knapsack problem first: we have $n$ sets of items, each item has value and weight, find the maximum value we can earn if we can choose at most one item from each set and the sum of the chosen items must be less than or equal to $W$. Let $dp_{w}$ be the max value we can earn if the sum of weights of chosen items is less than or equal to $w$. Now iterate on sets one by one and update $dp$ as follows: for each item $X$, and for each weight $w$, $newDp_{w} = max(newDp_{w}, oldDp_{w - X.weight} + X.value)$. Run dfs and find groups at first. The problem is same with above problem, each group is some set in above problem, just add the whole group as an item to the set that related to this group. Time complexity: $O(n\cdot W)$.
[ "dfs and similar", "dp", "dsu" ]
1,600
null
741
C
Arpa’s overnight party and Mehrdad’s silent entering
Note that girls in Arpa’s land are really attractive. Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw $n$ pairs of friends sitting around a table. $i$-th pair consisted of a boy, sitting on the $a_{i}$-th chair, and his girlfriend, sitting on the $b_{i}$-th chair. The chairs were numbered $1$ through $2n$ in clockwise direction. There was exactly one person sitting on each chair. There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that: - Each person had exactly one type of food, - No boy had the same type of food as his girlfriend, - Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs $2n$ and $1$ are considered consecutive. Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.
Build a graph and put an edge between each $2 \cdot i, 2 \cdot i + 1$ and each BF and GF. This graph doesn't have cycles with odd length. So it is a bipartite graph. Now give Kooft to some part and Zahre-mar to other. Time complexity: ${\cal O}(n)$.
[ "constructive algorithms", "dfs and similar", "graphs" ]
2,600
null
741
D
Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths
Just in case somebody missed it: we have wonderful girls in Arpa’s land. Arpa has a rooted tree (connected acyclic graph) consisting of $n$ vertices. The vertices are numbered $1$ through $n$, the vertex $1$ is the root. There is a letter written on each edge of this tree. Mehrdad is a fan of Dokhtar-kosh things. He call a string Dokhtar-kosh, if we can shuffle the characters in string such that it becomes palindrome. He asks Arpa, for each vertex $v$, what is the length of the longest simple path in subtree of $v$ that form a Dokhtar-kosh string.
Please read my dsu on tree (sack) tutorial before you read. Let's calculate for each vertex such $v$, length of longest Dokhtar-kosh path that starts in some vertex of subtree of $v$, passes from $v$, and ends in some other vertex of subtree of $v$ using sack (explained below); then we can sum up this values and get answer for each vertex. First keep a mask for each vertex, $i$-th bit of $mask_{v}$ is $true$ if the number of edges on the path from the root to $v$ such that the letter $i$ is written on them is odd. Now if the number of bits in $m a s k_{n}\oplus m a s k_{n}$ is $0$ or $1$, the path between $v$ and $u$ is Dokhtar-kosh. Let's use sack, assume $bag_{Mask}$ is the maximum height for a vertex that is present in our sack and its $mask$ is equal to $Mask$. Let's define two functions used in sack: $AddToSack$($vertex$ $x$) : If $bag_{maskx}$ is less than $h_{x}$, set $bag_{maskx} = h_{x}$. $UpdateCurrentAnswer$ ($vertex$ $x$, $vertex$ $root$) : For each $Mask$ such that $M a s k\oplus m a s k_{*}$ has at most one bit, update the $CurrentAnswer$, with $h_{x} + bag_{Mask} - 2 \cdot h_{root}$ (updating means if $CurrentAnswer$ is less than $h_{x} + bag_{Mask} - 2 \cdot h_{root}$, set $CurrentAnswer$ to it). Suppose dfs function arrives to vertex $v$. Call dfs for each child of $v$ except the biggest one (which has more vertices in its subtree than others) and clear the sack each time. Call dfs for big child of $v$ and don't clear the sack. Then for each other child $u$ and for each vertex $x\in s u b T r e e(u)$, call $UpdateCurrentAnswer(x, v)$. Then for each vertex $x\in s u b T r e e(u)$, call $AddToSack(x)$. After the addition of the children is done, call $UpdateCurrentAnswer(v, v)$ and $AddToSack(v)$. Now the answer for this vertex is $CurrentAnswer$. To clear the sack, for each vertex $x\in s u b T r e e(v)$ set $bag_{maskx} = - inf$ (i.e. $- 10^{9}$) and set $CurrentAnswer$ to 0. Note that there exists another solution using centroid decomposition, but it's harder. Time complexity: $O(n\cdot\log n\cdot z)$ ($z$ is number of characters which is equal to 22). Corner case: You must use an array, no map or unordered map for $bag$, these solutions got TLE.
[ "data structures", "dfs and similar", "trees" ]
2,900
null
741
E
Arpa’s abnormal DNA and Mehrdad’s deep interest
All of us know that girls in Arpa’s land are... ok, you’ve got the idea :D Anyone knows that Arpa isn't a normal man, he is ... well, sorry, I can't explain it more. Mehrdad is interested about the reason, so he asked Sipa, one of the best biology scientists in Arpa's land, for help. Sipa has a DNA editor. Sipa put Arpa under the DNA editor. DNA editor showed Arpa's DNA as a string $S$ consisting of $n$ lowercase English letters. Also Sipa has another DNA $T$ consisting of lowercase English letters that belongs to a normal man. Now there are $(n + 1)$ options to change Arpa's DNA, numbered from $0$ to $n$. $i$-th of them is to put $T$ between $i$-th and $(i + 1)$-th characters of $S$ ($0 ≤ i ≤ n$). If $i = 0$, $T$ will be put before $S$, and if $i = n$, it will be put after $S$. Mehrdad wants to choose the most interesting option for Arpa's DNA among these $n + 1$ options. DNA $A$ is more interesting than $B$ if $A$ is lexicographically smaller than $B$. Mehrdad asked Sipa $q$ questions: Given integers $l, r, k, x, y$, what is the most interesting option if we only consider such options $i$ that $l ≤ i ≤ r$ and $x\leq(i{\mathrm{~mod~}}k)\leq y$? If there are several most interesting options, Mehrdad wants to know one with the smallest number $i$. Since Sipa is a biology scientist but not a programmer, you should help him.
First sort all of the options. Use suffix array to compare two options. Give rank to each option. Then problem is to find minimum rank in each query. Use sqrt decomposition and divide queries into two groups: - $K\geq{\sqrt{n}}$ There are less than $\sqrt{n}$ segments that satisfy the conditions. Keep all of them, solve them at the end together with some method (it's a simple RMQ). - $K<{\sqrt{n}}$ Keep the query in some vector assigned to this $K$. Now for each $K$ from $1$ to ${\sqrt{n}}-1$: Break array into $K$ arrays. $i$-th of them contains indexes $j$ such that $j\;{\mathrm{mod}}\;K=i$. Then break each query assigned to this $K$ into these arrays and solve them with some method (it's a simple RMQ). Time complexity : $O(n\cdot{\sqrt{n}})$ (if you use some ${\cal O}(n)$ method for solving RMQ part).
[ "data structures", "string suffix structures" ]
3,400
null
742
A
Arpa’s hard exam and Mehrdad’s naive cheat
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do. Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given $n$, print the last digit of $1378^{n}$. Mehrdad has become quite confused and wants you to help him. Please help, although it's a naive cheat.
You know $1378^{n}\;\;\mathrm{mod}\;10=8^{n}\;\;\mathrm{mod}\;10$. If $n = 0$ answer is 1, otherwise, you can prove with induction that if: - $n\ \mathrm{\mod}\ 4=0$ then answer is 6. - $n\ \mathrm{\mod}\ 4=1$ then answer is 8. - $n\ \mathrm{\mod}\ 4=2$ then answer is 4. - $n\ \mathrm{\mod}\ 4=3$ then answer is 2. Time complexity: $O(1)$. Corner case: Solutions that forget to add $n = 0$ case got failed system testing.
[ "implementation", "math", "number theory" ]
1,000
null
742
B
Arpa’s obvious problem and Mehrdad’s terrible solution
There are some beautiful girls in Arpa’s land as mentioned before. Once Arpa came up with an obvious problem: Given an array and a number $x$, count the number of pairs of indices $i, j$ ($1 ≤ i < j ≤ n$) such that $a_{i}\oplus a_{j}=x$, where $\mathbb{C}$ is bitwise xor operation (see notes for explanation). Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.
Note that if $a_{i}\oplus a_{j}=X$ then $a_{i}\oplus X=a_{j}$. Keep in $num_{x}$ the number of repetitions of number $x$. Now for each $x$, add $\scriptstyle n=n\,m_{X\in X}$ to answer. Then divide answer by 2 (if $X$ is 0, don't). Time complexity: ${\mathcal{O}}(n)$. Corner case #1: Some codes got WA when $X$ is 0. Corner case #2: Some codes got RE because $x\oplus y$ can be as large as $max(x, y) \cdot 2$.
[ "brute force", "math", "number theory" ]
1,500
null
743
A
Vladik and flights
Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad. Vladik knows $n$ airports. All the airports are located on a straight line. Each airport has unique id from $1$ to $n$, Vladik's house is situated next to the airport with id $a$, and the place of the olympiad is situated next to the airport with id $b$. It is possible that Vladik's house and the place of the olympiad are located near the same airport. To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport $a$ and finish it at the airport $b$. Each airport belongs to one of two companies. The cost of flight from the airport $i$ to the airport $j$ is zero if both airports belong to the same company, and $|i - j|$ if they belong to different companies. Print the minimum cost Vladik has to pay to get to the olympiad.
The answer is $0$, if airports with numbers $a$ and $b$ belong to one company. Otherwise there are two adjacent airports, that belong to different companies. We can get to one of them for free, then pay $1$ to fly from one to another and then fly to airport number $b$ for free. So, in this case the answer is $1$. Complexity $O(n)$.
[ "constructive algorithms", "greedy", "implementation" ]
1,200
int n, a, b; string s; cin >> n >> a >> b >> s; a--, b--; cout << ((s[a] - '0') ^ (s[b] - '0'));
743
B
Chloe and the sequence
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to $1$. Then we perform $(n - 1)$ steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence $[1, 2, 1]$ after the first step, the sequence $[1, 2, 1, 3, 1, 2, 1]$ after the second step. The task is to find the value of the element with index $k$ (the elements are numbered from $1$) in the obtained sequence, i. e. after $(n - 1)$ steps. Please help Chloe to solve the problem!
Consider the string after $n$ steps of algorithm. We can split it into three parts: string from previous step, new character, another one string from previous step. Lets find the part, where our $k$-th character is, and reduce our string to the string from the previous step. The complexity is $O(n)$.
[ "binary search", "bitmasks", "constructive algorithms", "implementation" ]
1,200
int go(ll l, ll r, ll need, int alphSize) { ll m = l + (r - l) / 2LL; if (need < m) return go(l, m - 1, need, alphSize - 1); else if (need > m) return go(m + 1, r, need, alphSize - 1); else return alphSize; } void solveABig() { int n; ll k; cin >> n >> k; ll sz = 1; for (int i = 1; i < n; i++) sz = sz * 2LL + 1LL; cout << go(1, sz, k, n); }
743
C
Vladik and fractions
Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer $n$ he can represent fraction $\frac{2}{n}$ as a sum of three distinct positive fractions in form $\frac{1}{m}$. Help Vladik with that, i.e for a given $n$ find three distinct positive integers $x$, $y$ and $z$ such that ${\frac{2}{n}}={\frac{1}{x}}+{\frac{1}{y}}+{\frac{1}{z}}$. Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding $10^{9}$. If there is no such answer, print -1.
Note that for $n = 1$ there is no solution, and for $n > 1$ there is solution $x = n, y = n + 1, z = n \cdot (n + 1)$. To come to this solution, represent ${\frac{2}{n}}={\frac{1}{n}}+{\frac{1}{n}}$ and reduce the problem to represent $\frac{1}{n}$ as a sum of two fractions. Let's find the difference between $\frac{1}{n}$ and $\frac{1}{n+1}$ and get a fraction $\frac{1}{n\cdot(n+1)}$, so the solution is ${\frac{2}{n}}={\frac{1}{n}}+{\frac{1}{n+1}}+{\frac{1}{n\cdot(n+1)}}$
[ "brute force", "constructive algorithms", "math", "number theory" ]
1,500
int n; cin >> n; if (n == 1) cout << -1 << endl; else cout << n << ' ' << n + 1 << ' ' << n * (n + 1) << endl;
743
D
Chloe and pleasant prizes
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took $n$ prizes for the contestants and wrote on each of them a unique id (integer from $1$ to $n$). A gift $i$ is characterized by integer $a_{i}$ — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift $1$ on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with $n$ vertices. The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts. Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible. Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.
Our task is to choose two disjoint subtrees, such that sum of numbers in the first plus the sum in the second is maximal. Lets calculate for each vertex this dynamic programming using dfs seach: $sum_{v}$ - sum of all the numbers in subtree of vertex $v$, and $mx_{v}$ - maximal value from all $sum_{k}$ in subtree of vertex $v$ ($k$ belongs to subtree of $v$). We can calculate the answer using another dfs search, maintaining the value of maximal subtree, which is outside of current subtree. For example, if we are in vertex $v$, to update this value when going to call $dfs(s)$ (where $s$ is some son of $v$) we have to find maximal $mx_{v}$ from all other sons of $v$. The complexity is $O(n)$.
[ "dfs and similar", "dp", "graphs", "trees" ]
1,800
int a[maxn]; vector<int> g[maxn]; ll sum_subTree[maxn], mx_subTree[maxn]; void dfs1(int v, int p) { sum_subTree[v] = a[v]; mx_subTree[v] = -llinf; for (int i = 0; i < g[v].size(); i++) { int to = g[v][i]; if (to == p) continue; dfs1(to, v); sum_subTree[v] += sum_subTree[to]; mx_subTree[v] = max(mx_subTree[v], mx_subTree[to]); } mx_subTree[v] = max(mx_subTree[v], sum_subTree[v]); } ll ans = -llinf; void dfs2(int v, int p, ll out) { if (out != -llinf) ans = max(ans, sum_subTree[v] + out); vector<pair<ll, int> > miniset; for (int i = 0; i < g[v].size(); i++) { int to = g[v][i]; if (to == p) continue; miniset.pb(mp(mx_subTree[to], to)); sort(miniset.rbegin(), miniset.rend()); if (miniset.size() == 3) miniset.pop_back(); } miniset.pb(mp(-llinf, -1)); for (int i = 0; i < g[v].size(); i++) { int to = g[v][i]; if (to == p) continue; ll cur = miniset[0].s == to ? miniset[1].f : miniset[0].f; dfs2(to, v, max(out, cur)); } } int main() { for (int i = 0; i + 1 < n; i++) { int u, v; read(u, v); u--, v--; g[u].pb(v); g[v].pb(u); } dfs1(0, -1); dfs2(0, -1, -llinf); cout << ((ans == -llinf) ? ("Impossible") : to_string(ans)); return 0; }
743
E
Vladik and cards
Vladik was bored on his way home and decided to play the following game. He took $n$ cards and put them in a row in front of himself. Every card has a positive integer number not exceeding $8$ written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: - the number of occurrences of each number from $1$ to $8$ in the subsequence doesn't differ by more then $1$ from the number of occurrences of any other number. Formally, if there are $c_{k}$ cards with number $k$ on them in the subsequence, than for all pairs of integers $i\in[1,8],j\in[1,8]$ the condition $|c_{i} - c_{j}| ≤ 1$ must hold. - if there is at least one card with number $x$ on it in the subsequence, then all cards with number $x$ in this subsequence must form a continuous segment in it (\textbf{but not necessarily a continuous segment in the original sequence}). For example, the subsequence $[1, 1, 2, 2]$ satisfies this condition while the subsequence $[1, 2, 2, 1]$ doesn't. Note that $[1, 1, 2, 2]$ doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions.
Suppose we have taken at least $len$ cards of each color and $b$ colors of them have $len + 1$ cards. Then the answer will look like: $(8 - b) * len + b * (len + 1)$. Obviously, if our sequence of cards allows us to take $len$ cards of each color, then it allows to take $len - 1$, and $len - 2$, so on. Lets binary search for $len$ value, and check allowability this way: Define bitmask dynamic programming $dp[pos][mask]$ ($1 \le pos \le n, 0 \le mask \le 2^{8} - 1$) as the number of colors, for which we have taken $len + 1$ element, if we passed $pos$ cards in the sequence and the colors, which has bit equal to one in bitmask mask. We will have two different transitions. Iterate the new color, which has zero bit in the mask, to make the first transition, and find its occurrence number $len$ in subarray $[pos + 1, n]$. The second transition is completely the same, but we have to find occurrence number $(len + 1)$. To find the occurrence number $len$ of some color in subarray we should maintain an array of the remaining cards for each color. Finally, find the maximal allowable $len$, and in dp calculated for $len$ find the maximal additional cards in $dp[n][2^{8} - 1]$. This solution for $k$ colors of cards (8 in our case) has complexity $O(log(n) * n * k * 2^{k})$.
[ "binary search", "bitmasks", "brute force", "dp" ]
2,200
int can(int len) { for (int i = 0; i < 8; i++) cur[i] = 0; for (int i = 0; i <= n; i++) for (int j = 0; j < (1 << 8); j++) dp[i][j] = -inf; dp[0][0] = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < (1 << 8); j++) { if (dp[i][j] == -inf) continue; for (int k = 0; k < 8; k++) { if (j & (1 << k)) continue; int it = cur[k] + len - 1; if (it >= in[k].size()) continue; amax(dp[in[k][it] + 1][j | (1 << k)], dp[i][j]); it++; if (it >= in[k].size()) continue; amax(dp[in[k][it] + 1][j | (1 << k)], dp[i][j] + 1); } } cur[a[i]]++; } int ans = -inf; for (int i = 0; i <= n; i++) ans = max(ans, dp[i][(1 << 8) - 1]); if (ans == -inf) return -1; return ans * (len + 1) + (8 - ans) * len; } int main() { for (int i = 0; i < n; i++) { in[a[i]].push_back(i); } int l = 1, r = n / 8; while (r - l > 1) { int m = (l + r) >> 1; if (can(m) != -1) l = m; else r = m; } int ans = max(can(l), can(r)); if (ans == -1) { ans = 0; for (int i = 0; i < 8; i++) if (!in[i].empty()) ans++; } cout << ans; return 0; }
744
A
Hongcow Builds A Nation
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries. The world can be modeled as an undirected graph with $n$ nodes and $m$ edges. $k$ of the nodes are home to the governments of the $k$ countries that make up the world. There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, \textbf{there is no path between those two nodes}. Any graph that satisfies all of these conditions is stable. Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
First, let's make all connected components cliques. This graph is still stable. Now, there are some components without special nodes. Where should we connect them? If there is a component with size A and a component with size B, we can add A*B edges if we connect these two components. So, it makes sense to choose the largest component.
[ "dfs and similar", "graphs" ]
1,500
n,m,k = map(int, raw_input().split()) special = map(int, raw_input().split()) root = range(n+1) def par(p): if p != root[p]: root[p] = par(root[p]) return root[p] def c2(n): return n * (n - 1) / 2 for __ in xrange(m): u,v = map(par, map(int, raw_input().split())) root[v] = u sz = [0 for i in range(n+1)] for i in range(n+1): sz[par(i)] += 1 leftover = n ans = 0 largest = 0 for x in special: d = par(x) largest = max(largest, sz[d]) ans += c2(sz[d]) leftover -= sz[d] ans -= c2(largest) ans += c2(largest + leftover) ans -= m print ans
744
B
Hongcow's Game
\textbf{This is an interactive problem. In the interaction section below you will see the information about flushing the output.} In this problem, you will be playing a game with Hongcow. How lucky of you! Hongcow has a hidden $n$ by $n$ matrix $M$. Let $M_{i, j}$ denote the entry $i$-th row and $j$-th column of the matrix. The rows and columns are labeled from $1$ to $n$. The matrix entries are between $0$ and $10^{9}$. In addition, $M_{i, i} = 0$ for all valid $i$. Your task is to find the minimum value along each row, excluding diagonal elements. Formally, for each $i$, you must find $\mathrm{min}_{j\neq i}\,M_{i,j}$. To do this, you can ask Hongcow some questions. A question consists of giving Hongcow a subset of distinct indices ${w_{1}, w_{2}, ..., w_{k}}$, with $1 ≤ k ≤ n$. Hongcow will respond with $n$ integers. The $i$-th integer will contain the minimum value of $min_{1 ≤ j ≤ k}M_{i, wj}$. You may only ask Hongcow at most $20$ questions — he thinks you only need that many questions answered. When you are ready to answer, print out a single integer $ - 1$ on its own line, then $n$ integers on the next line. The $i$-th integer should be the minimum value in the $i$-th row of the matrix, excluding the $i$-th element. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question. You will get Wrong Answer verdict if - Your question or answers are not in the format described in this statement. - You ask strictly more than $20$ questions. - Your question contains duplicate indices. - The value of $k$ in your question does not lie in the range from $1$ to $n$, inclusive. - Your final answer is not correct. You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).
For the bits solution: We want to create 20 questions where for every i != j, there exists a question that contains j and not i, and also a qusetion that contains i and not j. If we can do this, we can find the min for each row. Note that i != j implies that there exists a bit index where i and j differ. So, let's ask 2 questions for each bit position, one where all indices have a value of 0 in that position, and one where all indices have a value of 1 in that position. This is a total of at most 20 questions, and we can show that this satisfies the condition above, so this solves the problem. Parallelization will basically reduce to the above solution, but is another way of looking at the problem. First, let's ask {1,2,...,n/2} and {n/2+1,...,n} This handles the case where the min lies on the opposite half. For example, this handles the case where the min lies in the X part of the matrix, and we split it into two identical problems of size n/2 within the O matrix. Now, we can ask questions for each submatrix, but we can notice that these two don't interact so we can combine all the questions at this level. However, we should ask the questions in parallel, as we don't have that many questions For example, for n=8, we should ask As you can see, this reduces to the bit approach above if N is a power of 2.
[ "bitmasks", "divide and conquer", "interactive" ]
1,900
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class HiddenMatrix { public static void main (String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] min = new int[n+1]; Arrays.fill(min, 1 << 30); for (int bit = 0; bit < 10; bit++) { for (int val = 0; val <= 1; val++) { ArrayList<Integer> query = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (((i >> bit) & 1) == val) { query.add(i); } } if (query.size() != n && query.size() != 0) { out.println(query.size()); for (int j = 0; j < query.size(); j++) { if (j != 0) out.print(" "); out.print(query.get(j)); } out.println(); out.flush(); for (int i = 1; i <= n; i++) { int d = in.nextInt(); if (((i >> bit) & 1) == 1 - val) { min[i] = Math.min(min[i], d); } } } } } out.println(-1); for (int i = 1; i <= n; i++) { if (i != 1) out.print(" "); out.print(min[i]); } out.println(); out.flush(); System.exit(0); } }
744
C
Hongcow Buys a Deck of Cards
One day, Hongcow goes to the store and sees a brand new deck of $n$ special cards. Each individual card is either red or blue. He decides he wants to buy them immediately. To do this, he needs to play a game with the owner of the store. This game takes some number of turns to complete. On a turn, Hongcow may do one of two things: - Collect tokens. Hongcow collects $1$ red token \textbf{and} $1$ blue token by choosing this option (thus, $2$ tokens in total per one operation). - Buy a card. Hongcow chooses some card and spends tokens to purchase it as specified below. The $i$-th card requires $r_{i}$ red resources and $b_{i}$ blue resources. Suppose Hongcow currently has $A$ red cards and $B$ blue cards. Then, the $i$-th card will require Hongcow to spend $max(r_{i} - A, 0)$ red tokens, and $max(b_{i} - B, 0)$ blue tokens. Note, only tokens disappear, but the cards stay with Hongcow forever. Each card can be bought only once. Given a description of the cards and their costs determine the minimum number of turns Hongcow needs to purchase all cards.
Also note that if r_i or b_i >= n, we need to collect tokens no matter what since those costs can't be offset. So, we can assume that r_i, b_i <= n. Let's only buy tokens when we need them. Note that after buying a card, you will have either 0 red tokens or 0 blue tokens, so our dp state can be described by [mask][which one is zero][how many of the other] The dimensions of this dp table are 2^n * 2 * (n^2) (n^2 because the costs to buy cards is at most n). See the code for more details on how to update this dp.
[ "bitmasks", "brute force", "dp" ]
2,400
import java.util.Arrays; import java.util.Scanner; public class RedAndBlueCards { public static int n; public static char[] color; public static int[] r,b; public static int[] countred, countblue; public static void main (String[] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); color = new char[n]; r = new int[n]; b = new int[n]; int base = 0; int needred = 0, needblue = 0; for (int i = 0; i < n; i++) { color[i] = in.next().charAt(0); r[i] = in.nextInt(); b[i] = in.nextInt(); needred += Math.max(0, r[i] - n); needblue += Math.max(0, b[i] - n); r[i] = Math.min(n, r[i]); b[i] = Math.min(n, b[i]); } base = Math.max(needred, needblue); countred = new int[1<<n]; countblue = new int[1<<n]; for (int i = 1; i < 1 << n; i++) { int lowbit = Integer.numberOfTrailingZeros(i & -i); countred[i] = countred[i ^ (1 << lowbit)]; countblue[i] = countblue[i ^ (1 << lowbit)]; if (color[lowbit] == 'R') countred[i]++; else countblue[i]++; } dp = new int[2][n*n+1][1<<n]; for (int[][] x : dp) for (int[] y : x) Arrays.fill(y, -1); int ans = base + n; if (needred < needblue) { ans += solve(0, 0, needblue - needred); } else { ans += solve(0, 1, needred - needblue); } System.out.println(ans); System.exit(0); } public static int[][][] dp; public static int solve(int mask, int redempty, int other) { other = Math.min(other, n*n); if (mask == (1<<n)-1) return 0; if (dp[redempty][other][mask] != -1) return dp[redempty][other][mask]; int ret = 1 << 29; for (int i = 0; i < n; i++) { if (((mask>>i)&1) == 1) continue; int pmask = mask | (1 << i); int havered = redempty == 1 ? 0 : other; int haveblue = redempty == 0 ? 0 : other; int cardred = countred[mask], cardblue = countblue[mask]; int nred = Math.max(0, r[i]-(cardred+havered)); int nblue = Math.max(0, b[i]-(cardblue+haveblue)); int needmoves = Math.max(nred, nblue); int nextred = havered + needmoves - Math.max(0, r[i] - cardred); int nextblue = haveblue + needmoves - Math.max(0, b[i] - cardblue); if (nextred == 0) { ret = Math.min(ret, needmoves + solve(pmask, 1, nextblue)); } if (nextblue == 0) { ret = Math.min(ret, needmoves + solve(pmask, 0, nextred)); } } return dp[redempty][other][mask] = ret; } }
744
D
Hongcow Draws a Circle
Hongcow really likes the color red. Hongcow doesn't like the color blue. Hongcow is standing in an infinite field where there are $n$ red points and $m$ blue points. Hongcow wants to draw a circle in the field such that this circle contains at least one red point, and no blue points. Points that line exactly on the boundary of the circle can be counted as either inside or outside. Compute the radius of the largest circle that satisfies this condition. If this circle can have arbitrarily large size, print $ - 1$. Otherwise, your answer will be accepted if it has relative or absolute error at most $10^{ - 4}$.
First to check if an answer can be arbitrarily large, we can see if there is any red point that is on the convex hull of all our points. So from now on, we can assume the answer is finite. We can show that the optimal circle must touch a blue point. To see this, consider any optimal circle that doesn't touch a blue point. We can make it slightly bigger so that it does touch one. So, let's binary search for the answer. However, you have to very careful and notice that the binary search isn't monotonic if we only consider circles touching blue points. However, if we consider circles that touch either a red or blue point, then the binary search is monontonic, so everything works out. To check if a radius works, we can do a angle sweep around our center point. We have a fixed radius and fixed center, so each other point has at most two angles where it enters and exits the circle as we rotate it about the center point. We can keep track of these events and find an interval where the circle only contains red points. For the inversion solution, let's fix the blue point that our circle touches. Then, let's take the inversion around this point (i.e. https://en.wikipedia.org/wiki/Inversive_geometry). Now, circles that pass through our center points become lines, and the interior of those circles are in the halfplane not containing the center point. The radius of the circle is inversely proportional to the distance between our center point to the line after inversion. So, we can say we want to solve the following problem after inversion. Find the closest line that contains no blue points in the halfplane facing away from our center point and at least one red point. We can notice that we only need to check lines that contain a blue point on the convex hull after inversion. To make implementation easier, you can make the additional observation that the sum of all convex hull sizes will be linear through the process of the algorithm. Some intuition behind this observation is that only adjacent nodes in a delaunay triangluation can appear on the convex hull after inversion, so the sum is bounded by the number of edges in such a triangulation (of course, we do not need to explicitly find the triangulation).
[ "geometry" ]
3,200
#pragma comment(linker, "/STACK:1000000000") #include <cstdio> #include <cmath> #include <cstdlib> #include <cassert> #include <ctime> #include <cstring> #include <string> #include <set> #include <map> #include <vector> #include <list> #include <deque> #include <queue> #include <sstream> #include <iostream> #include <algorithm> using namespace std; #define pb push_back #define mp make_pair #define fs first #define sc second #define double long double const double pi = acos(-1.0); const double eps1 = 1e-7; const double eps2 = 1e-14; double sqr(double x) { return x * x; } struct pt { double x, y; pt(double x_ = 0.0, double y_ = 0.0) : x(x_), y(y_) {} }; pt operator + (const pt& a, const pt& b) { return pt(a.x + b.x, a.y + b.y); } pt operator - (const pt& a, const pt& b) { return pt(a.x - b.x, a.y - b.y); } pt operator * (const pt& a, double k) { return pt(a.x * k, a.y * k); } struct line { double a, b, c; line(double a_ = 1.0, double b_ = 0.0, double c_ = 0.0): a(a_), b(b_), c(c_) { norm(); } line(const pt& p1, const pt& p2) { a = p2.y - p1.y; b = p1.x - p2.x; c = -a * p1.x - b * p1.y; norm(); } void norm() { double k = sqrt(sqr(a) + sqr(b)); a /= k; b /= k; c /= k; } double dist(const pt& p) const { return a * p.x + b * p.y + c; } }; bool cmp (pt a, pt b) { return (a.x < b.x) || (a.x == b.x && a.y < b.y); } bool cw (pt a, pt b, pt c) { return a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y) < -eps2; } bool ccw (pt a, pt b, pt c) { return a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y) > eps2; } void convex_hull (vector<pt> & a) { if (a.size() == 1) return; if (a.size() == 2) return; sort (a.begin(), a.end(), &cmp); pt p1 = a[0], p2 = a.back(); vector<pt> up, down; up.push_back (p1); down.push_back (p1); for (size_t i=1; i<a.size(); ++i) { if (i==a.size()-1 || cw (p1, a[i], p2)) { while (up.size()>=2 && !cw (up[up.size()-2], up[up.size()-1], a[i])) up.pop_back(); up.push_back (a[i]); } if (i==a.size()-1 || ccw (p1, a[i], p2)) { while (down.size()>=2 && !ccw (down[down.size()-2], down[down.size()-1], a[i])) down.pop_back(); down.push_back (a[i]); } } a.clear(); for (size_t i=0; i<up.size(); ++i) a.push_back (up[i]); for (size_t i=down.size()-2; i>0; --i) a.push_back (down[i]); } int sign(double x) { if (fabs(x) < eps2) return 0; if (x > 0) return 1; return -1; } int main() { //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); int n, m; cin >> n >> m; vector <pt> red(n), blue(m); for (int i = 0; i < n; i++) { cin >> red[i].x >> red[i].y; } for (int i = 0; i < m; i++) { cin >> blue[i].x >> blue[i].y; } if (m == 1) { cout << -1 << endl; return 0; } vector <pt> cvx_blue = blue; convex_hull(cvx_blue); int k = cvx_blue.size(); for (int i = 0; i < n; i++) { bool flag = true; for (int j = 0; j < k; j++) { line hl(cvx_blue[j % k], cvx_blue[(j + 1) % k]); if (hl.dist(red[i]) > eps1) { flag = false; } } if (flag) { cout << -1 << endl; return 0; } } double ans = 0.0; for (int i = 0; i < m; i++) { vector <pt> new_blue; for (int j = 0; j < i; j++) { new_blue.pb(blue[j] - blue[i]); double d = sqr(new_blue.back().x) + sqr(new_blue.back().y); new_blue.back().x /= d; new_blue.back().y /= d; } new_blue.pb(pt(0.0, 0.0)); for (int j = i + 1; j < m; j++) { new_blue.pb(blue[j] - blue[i]); double d = sqr(new_blue.back().x) + sqr(new_blue.back().y); new_blue.back().x /= d; new_blue.back().y /= d; } vector <pt> new_red; for (int j = 0; j < n; j++) { new_red.pb(red[j] - blue[i]); double d = sqr(new_red.back().x) + sqr(new_red.back().y); new_red.back().x /= d; new_red.back().y /= d; } convex_hull(new_blue); int k = new_blue.size(); int p = new_red.size(); for (int j = 0; j < k; j++) { bool flag = false; line hl(new_blue[j], new_blue[(j + 1) % k]); for (int q = 0; q < p; q++) { if (hl.dist(new_red[q]) < eps2) flag = true; } if (flag) { if (abs(hl.dist(pt(0.0, 0.0))) < eps2) { cout << -1 << endl; return 0; } // cerr << hl.dist(pt(0.0, 0.0)) << endl; /* if (fabs(hl.dist(pt(0.0, 0.0))) < eps) { cout << -1 << endl; return 0; } */ ans = max(ans, 1.0 / abs(hl.dist(pt(0.0, 0.0)))); } } for (int q = 0; q < p; q++) { for (int j = 0; j < k; j++) { line hl(new_red[q], new_blue[j]); if (sign(hl.dist(new_blue[(j + 1) % k])) * sign(hl.dist(new_blue[(j + k - 1) % k])) >= 0) { if (abs(hl.dist(pt(0.0, 0.0))) < eps2) { cout << -1 << endl; return 0; } // cerr << hl.dist(pt(0.0, 0.0)) << endl; ans = max(ans, 1.0 / abs(hl.dist(pt(0.0, 0.0)))); } } } } cout.precision(20); cout << ans / 2.0 << endl; return 0; }
744
E
Hongcow Masters the Cyclic Shift
Hongcow's teacher heard that Hongcow had learned about the cyclic shift, and decided to set the following problem for him. You are given a list of $n$ strings $s_{1}, s_{2}, ..., s_{n}$ contained in the list $A$. A list $X$ of strings is called stable if the following condition holds. First, a message is defined as a concatenation of some elements of the list $X$. You can use an arbitrary element as many times as you want, and you may concatenate these elements in any arbitrary order. Let $S_{X}$ denote the set of of all messages you can construct from the list. Of course, this set has infinite size if your list is nonempty. Call a single message good if the following conditions hold: - Suppose the message is the concatenation of $k$ strings $w_{1}, w_{2}, ..., w_{k}$, where each $w_{i}$ is an element of $X$. - Consider the $|w_{1}| + |w_{2}| + ... + |w_{k}|$ cyclic shifts of the string. Let $m$ be the number of these cyclic shifts of the string that are elements of $S_{X}$. - A message is good if and only if $m$ is exactly equal to $k$. The list $X$ is called stable if and only if every element of $S_{X}$ is good. Let $f(L)$ be $1$ if $L$ is a stable list, and $0$ otherwise. Find the sum of $f(L)$ where $L$ is a nonempty \textbf{contiguous sublist} of $A$ (there are $\textstyle{\frac{n(n+1)}{2}}$ contiguous sublists in total).
Let M denote the total number of characters across all strings. Consider how long it takes to compute f(L) for a single list. Consider a graph where nodes are suffixes of strings. This means we already spelled out the prefix, and still need to spell out the suffix. There are at most M nodes in this graph. Now, draw at most N edges connecting suffixes to each other. We can find the edges efficiently by doing suffix arrays or z algorithm or hashes. Now, we claim is the list is good if and only if there is no cycle in this graph. You can notice that a cycle exists => we can construct a bad word. Also, if a bad word exists => we can form a cycle. So, we can check if there is a cycle, which takes O(N*M) time. Next step is to notice that extending a bad list will never make it good. So we can do two pointers to find all good intervals, which requires O(n) calls to the check function. So, overall this runs in O(N^2*M) time. You might be wondering why this problem asks for sublists rather than the entire list. To be honest, it's just to make tests slightly stronger (i.e. I get ~30^2x the number of tests in the same amount of space).
[ "strings", "two pointers" ]
3,200
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class CyclicShiftsAgainAgain { public static int n; public static String[] s; public static int[] len; public static void main (String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out, true); n = in.nextInt(); s = new String[n+1]; len = new int[n+1]; s[0] = ""; len[0] = 0; for (int i = 1; i <= n; i++) { s[i] = in.next(); len[i] = len[i-1] + s[i].length(); } int ans = 0; int front = 0; for (int i = 1; i <= n; i++) { while (!isGood(front+1, i)) front++; ans += i - front; } out.println(ans); out.close(); System.exit(0); } public static boolean isGood(int from, int to) { if (from > to) return true; int numnodes = len[to] - len[from - 1]; ArrayList<Integer>[] graph = new ArrayList[numnodes+1]; for (int i = 0; i <= numnodes; i++) graph[i] = new ArrayList<>(); for (int startword = from; startword <= to; startword++) { graph[numnodes].add(len[startword-1] - len[from-1]); StringBuilder sb = new StringBuilder(); sb.append(s[startword]); sb.append("$"); for (int k = from; k <= to; k++) { if (k == startword) continue; sb.append(s[k]); sb.append("#"); } int[] z = zz(sb.toString().toCharArray()); int curchar = 0; for (int i = 1; i < s[startword].length(); i++) { if (z[i] + i >= s[startword].length()) { graph[i + len[startword-1] - len[from -1]].add(z[i] + len[startword-1] - len[from-1]); } } int curword = startword == from ? (from+1) : from; for (int i = s[startword].length()+1; i+1 < z.length; i++) { if (sb.charAt(i) == '#') { i++; curword++; if (curword == startword) curword++; curchar = 0; } int curnode = curchar + len[curword-1] - len[from-1]; if (z[i] + curchar >= s[curword].length()) { if (z[i] == s[startword].length()) { if (curchar != 0) graph[curnode].add(numnodes); } else { graph[curnode].add(z[i] + len[startword-1] - len[from-1]); } } else if (z[i] == s[startword].length()) { graph[curnode].add(curnode + z[i]); } curchar++; } } return isDAG(graph); } public static int[] zz(char[] let) { int N = let.length; int[] z = new int[N]; int L = 0, R = 0; for (int i = 1; i < N; i++) { if (i > R) { L = R = i; while (R < N && let[R - L] == let[R]) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < N && let[R - L] == let[R]) R++; z[i] = R - L; R--; } } } z[0] = N; return z; } private static boolean isDAG(ArrayList<Integer>[] graph) { int n = graph.length; int[] indeg = new int[n]; for (int i = 0; i < n; i++) for (int x : graph[i]) indeg[x]++; int[] queue = new int[n]; int front = 0, back = 0, idx = 0; for (int i = 0; i < indeg.length; i++) if (indeg[i] == 0) queue[back++] = i; while (front != back) { int node = queue[front++]; for (int next : graph[node]) { if (--indeg[next] == 0) { queue[back++] = next; } } } return front == n; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
745
A
Hongcow Learns the Cyclic Shift
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word. Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on. Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
We only need to consider at most |s| cyclic shifts (since |s| cyclic shifts returns us back to the original string). So, we can put these all in a set, and return the size of the set.
[ "implementation", "strings" ]
900
print (lambda s: len(set(s[i:] + s[:i] for i in range(len(s)))))(raw_input())
745
B
Hongcow Solves A Puzzle
Hongcow likes solving puzzles. One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an $n$ by $m$ grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified. The puzzle pieces are very heavy, so Hongcow \textbf{cannot rotate or flip} the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also \textbf{cannot overlap}. You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
I really apologize for the ambiguity of this problem. We worked hard to make it concise and accurate, but we left out too many details. Basically, the idea is we want to overlay two of these pieces together so that no square has more than 1 X, and the region of X's forms a rectangle. Now for the solution: First, let's look at it backwards. I have a rectangle, and I cut it in two pieces. These two pieces have the same exact shape. What shapes can I form? A necessary and sufficient condition is that the piece itself is a rectangle itself! There are a few ways to check this. One is, find the min/max x/y coordinates, and make sure the number of X's match the bounding box of all the points.
[ "implementation" ]
1,400
n,m = map(int, raw_input().split()) piece = [raw_input().rstrip() for i in range(n)] maxx, minx, maxy, miny = -1, n, -1, m count = 0 for i in range(n): for j in range(m): if piece[i][j] == 'X': maxx = max(maxx, i) minx = min(minx, i) maxy = max(maxy, j) miny = min(miny, j) count += 1 print ((maxx - minx + 1) * (maxy - miny + 1) == count) * "YES" or "NO"
746
A
Compote
Nikolay has $a$ lemons, $b$ apples and $c$ pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio $1: 2: 4$. It means that for each lemon in the compote should be exactly $2$ apples and exactly $4$ pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits. Your task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print $0$.
At first let's calculate how many portions of stewed fruit (in one portion - $1$ lemon, $2$ apples and $4$ pears) we can cook. This number equals to $min(a, b div 2, c div 4)$, where $x div y$ is integer part of $x / y$. After that we need to multiply this number of 7, because there is 7 fruits in 1 portion, and print the result.
[ "implementation", "math" ]
800
null
746
B
Decoding
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: {con\textbf{\underline{t}}est}, {i\textbf{\underline{n}}fo}. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva. You are given an encoding $s$ of some word, your task is to decode it.
To find the answer we can iterate through the given string from the left to the right and add each letter in the answer string - one letter to the begin, next letter to the end, next letter to begin and so on. If $n$ is even than the first letter must be added to the begin and the second letter to the end. In the other case, the first letter - to the end, second - to the begin. We need to make it until we do not add all letters from the given string.
[ "implementation", "strings" ]
900
null
746
C
Tram
The tram in Berland goes along a straight line from the point $0$ to the point $s$ and back, passing $1$ meter per $t_{1}$ seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points $x = 0$ and $x = s$. Igor is at the point $x_{1}$. He should reach the point $x_{2}$. Igor passes $1$ meter per $t_{2}$ seconds. Your task is to determine the minimum time Igor needs to get from the point $x_{1}$ to the point $x_{2}$, if it is known where the tram is and in what direction it goes at the moment Igor comes to the point $x_{1}$. Igor can enter the tram unlimited number of times at any moment when his and the tram's positions coincide. It is \textbf{not obligatory} that points in which Igor enter and exit the tram are integers. Assume that any boarding and unboarding happens instantly. Igor can move arbitrary along the line (but not faster than $1$ meter per $t_{2}$ seconds). He can also stand at some point for some time.
It is easy to show that if Igor faster than the tram the answer is $|x_{1} - x_{2}| \cdot t_{2}$. In the other case we need to use the following hint: the time of arrive does not depend on how much Igor walk before enter the tram, if the tram will reach the finish point faster than Igor. So Igor can wait the tram in the point $x_{1}$. The answer is minimum of the following values: the time during which Igor will reach the point $x_{2}$ by foot and the time during which the tram will reach at first the point $x_{1}$ and than the point $x_{2}$.
[ "constructive algorithms", "implementation", "math" ]
1,600
null
746
D
Green and Black Tea
Innokentiy likes tea very much and today he wants to drink exactly $n$ cups of tea. He would be happy to drink more but he had exactly $n$ tea bags, $a$ of them are green and $b$ are black. Innokentiy doesn't like to drink the same tea (green or black) more than $k$ times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink $n$ cups of tea, without drinking the same tea more than $k$ times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.
Let's use greedy to solve this problem. On the current step we choose tea, which left more, but if the last $k$ cups were equal we need to use the other tea. If we can't use the other tea - there is no answer and we need to print <<NO>>. So, we need to store the number of last cups, which were equals and how many of green and black tea left we greedily build the answer. If we use all tea with this algorithm - we found the answer and it is guaranteed that it is correct answer.
[ "constructive algorithms", "greedy", "math" ]
1,500
null
746
E
Numbers Exchange
Eugeny has $n$ cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be \textbf{distinct}. Nikolay has $m$ cards, distinct numbers from $1$ to $m$ are written on them, one per card. It means that Nikolay has exactly one card with number $1$, exactly one card with number $2$ and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.
Because of all resulting numbers must be distinct we necessarily need to change all numbers with meet more than once in the given sequence $a$. We will use two pointers: pointer on next even number in the sequence $b$ (at first this pointer equals to 2) and pointer on next odd number in the sequence $b$ (at first it is 1). Also we will store the number of odd and even numbers in $a$. At first let brute the numbers in $a$. If current number meets more than once we have two ways: if the number of numbers with it parity less or equal to the number of numbers with other parity in $a$, we change this number to the number with same parity from $b$ and move needed pointer; in the other case - change this number to number with different parity and move needed parity. After we finished iterations all numbers will be different but the number of odd numbers can be not equal to the number of even numbers. We need to make similar iterations and change only numbers for which the number of numbers with such parity more. If in some moment we can not change next number - the answer is -1.
[ "greedy", "implementation", "math" ]
1,900
null
746
F
Music in Car
Sasha reaches the work by car. It takes exactly $k$ minutes. On his way he listens to music. All songs in his playlist go one by one, after listening to the $i$-th song Sasha gets a pleasure which equals $a_{i}$. The $i$-th song lasts for $t_{i}$ minutes. Before the beginning of his way Sasha turns on some song $x$ and then he listens to the songs one by one: at first, the song $x$, then the song $(x + 1)$, then the song number $(x + 2)$, and so on. He listens to songs until he reaches the work or until he listens to the last song in his playlist. Sasha can listen to each song to the end or partly. In the second case he listens to the song for integer number of minutes, at least half of the song's length. Formally, if the length of the song equals $d$ minutes, Sasha listens to it for no less than $\textstyle{\left[{\frac{d}{2}}\right]}$ minutes, then he immediately switches it to the next song (if there is such). For example, if the length of the song which Sasha wants to partly listen to, equals $5$ minutes, then he should listen to it for at least $3$ minutes, if the length of the song equals $8$ minutes, then he should listen to it for at least $4$ minutes. It takes no time to switch a song. Sasha wants to listen partly no more than $w$ songs. If the last listened song plays for less than half of its length, then Sasha doesn't get pleasure from it and that song is not included to the list of partly listened songs. It is not allowed to skip songs. A pleasure from a song does not depend on the listening mode, for the $i$-th song this value equals $a_{i}$. Help Sasha to choose such $x$ and no more than $w$ songs for partial listening to get the maximum pleasure. Write a program to find the maximum pleasure Sasha can get from the listening to the songs on his way to the work.
This problem can be solved with help of two pointers. We will store two sets - set with songs with full time and set with songs with partly time. How to move left and right pointers and recalculate current answer? Let left end of the current segment is $l$ and right end of the segment is $r$. Let the set of songs with partly time is $half$ and with full time - $full$. In this sets we will store pairs - time of listening each song and it number. Right end we will move in the following way: if we can add partly song and we have enough time to listen it - we take it (also add this song to $half$) and add to time $(t_{r} + 1) / 2$ and add to the answer $a_{r}$. In the other case we have two cases. First - we add current song as full song, second - we add current song as partly song. Here we need to choose case with less with the total time. Also here we need to correctly add song to sets and update total time and the answer. If total time became more than $k$ we are not allowed to move $r$. Now we need to update global answer with the current value of answer. Left end we will move in the following way: if we took song as full song we delete it from $full$, subtract from total time length of this song. In the other case we delete it from $half$ and subtract from the total time the $(t_{l} + 1) / 2$. After that we try to take some song from $full$. If the size of $full$ is 0, we can not do that. If we done it we need to change total time on the songs on the current segment.
[ "data structures", "greedy", "two pointers" ]
2,200
null
746
G
New Roads
There are $n$ cities in Berland, each of them has a unique id — an integer from $1$ to $n$, the capital is the one with id $1$. Now there is a serious problem in Berland with roads — there are no roads. That is why there was a decision to build $n - 1$ roads so that there will be exactly one simple path between each pair of cities. In the construction plan $t$ integers $a_{1}, a_{2}, ..., a_{t}$ were stated, where $t$ equals to the distance from the capital to the most distant city, concerning new roads. $a_{i}$ equals the number of cities which should be at the distance $i$ from the capital. The distance between two cities is the number of roads one has to pass on the way from one city to another. Also, it was decided that among all the cities except the capital there should be exactly $k$ cities with exactly one road going from each of them. Such cities are dead-ends and can't be economically attractive. In calculation of these cities the capital is not taken into consideration regardless of the number of roads from it. Your task is to offer a plan of road's construction which satisfies all the described conditions or to inform that it is impossible.
The statement of this problem equals to: we need to build rooted tree with $k$ leafs and for each $i$ from 1 to $n$ on the depth $i$ there are $a_{i}$ vertices. Let $m$ is sum of all numbers from $a$ - the number of vertices in the tree without root. At first let build the path from the root to the leaf on the depth $n$, i. e. on each level we create one vertex which connect with vertex on previous level. In resulting tree we necessarily have such path. Let $c$ is the number of vertices (do not consider already created vertices) which we need to make "not leafs". It is equals to $c = m - k - n + 1$. If now $c < 0$ there is no answer - we can not make less number of leafs which we already have. In the other case we need to each level $i$ until $c > 0$ and on the level $i - 1$ we have leafs and the level $i$ does not filled we will add new vertex to random vertex from the level $i - 1$, which does not a leaf. Other vertices on the level $i$ we can add to vertex which has been created when we built path from the root to the depth $n$. If on the current step $c > 0$ - there is no solution. In the other case we built needed tree and can print the answer.
[ "constructive algorithms", "graphs", "trees" ]
2,100
null
747
A
Display Size
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly $n$ pixels. Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels $a$ and the number of columns of pixels $b$, so that: - there are exactly $n$ pixels on the display; - the number of rows does not exceed the number of columns, it means $a ≤ b$; - the difference $b - a$ is as small as possible.
We can iterate through the values of $a$ from 1 to $n$. For each $i$ if $n mod i = 0$ and if $abs(i - n / i)$ is less than already found different we need to update answer with values $min(i, n / i)$ and $max(i, n / i)$ (because $a$ must be less than $b$).
[ "brute force", "math" ]
800
null