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
223
D
Spider
A plane contains a not necessarily convex polygon without self-intersections, consisting of $n$ vertexes, numbered from 1 to $n$. There is a spider sitting on the border of the polygon, the spider can move like that: - Transfer. The spider moves from the point $p_{1}$ with coordinates $(x_{1}, y_{1})$, lying on the polygon border, to the point $p_{2}$ with coordinates $(x_{2}, y_{2})$, also lying on the border. The spider can't go beyond the polygon border as it transfers, that is, the spider's path from point $p_{1}$ to point $p_{2}$ goes along the polygon border. It's up to the spider to choose the direction of walking round the polygon border (clockwise or counterclockwise). - Descend. The spider moves from point $p_{1}$ with coordinates $(x_{1}, y_{1})$ to point $p_{2}$ with coordinates $(x_{2}, y_{2})$, at that points $p_{1}$ and $p_{2}$ must lie on one vertical straight line ($x_{1} = x_{2}$), point $p_{1}$ must be not lower than point $p_{2}$ ($y_{1} ≥ y_{2}$) and segment $p_{1}p_{2}$ mustn't have points, located strictly outside the polygon (specifically, the segment can have common points with the border). Initially the spider is located at the polygon vertex with number $s$. Find the length of the shortest path to the vertex number $t$, consisting of transfers and descends. The distance is determined by the usual Euclidean metric $|p_{1}p_{2}|={\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}}}$.
You were given a polygon consisting of $n$ vertices, you had to find the shortest way from one of its vertices to another. You were allowed to move along the border and go stricktly down without going outside the polygon All the sides of the polygon can be divided into three groups: top, bottom and vertical. The side is vertical if and only if the $x$ coordinates of its ends are equal. The side is bottom if and only if the polygon's interior is above the side. The side it top if and only if the polygon's interior is below the side. We can descend only from points of the top sides to the points of the bottom sides. Vertical sides can be ignored because every descend that has common points with a vertical side can be splitted into two descends and one transfer. One can prove that it is useless to descend from a side's interior to side's interior. Len one of the descends in the optimal solution start in the inner point and end in the inner point. We can slightly change the $x$ coordinate of the descend. The path's lenght is monotonically (possibly not strictly) depends on $x$, so we can move $x$ in order to improve the answer. In case of not strictly monotone dependance the answer do not depend on $x$, so we also can move it. This proof is wrong if the descend passes through a vertex, therefore we have to examine all possible descends from the vertices and to the vertices. We can solve this problem using scan-line method. We well move a vertical straight line from the left to the right and keep set $S$ of the sides that intersect the line. We store the segments in the $S$ in the sorted by $y$ order. Let $X$ be an abscissa of the line. The events happen during the moving: some segments are added to the $S$ set, some are deleted. We can make an array of events, each events is described by its $x$ coordinate that is equal to $X$ of the line when the corresponding event happens, the number of the segment and a kind of event: adding or deleting. There are two events for every side, their $x$ coordinates correspond to abscissas of their ends. The vertical sides can be ignored. Let us proceed the events in non-decreasing order of $x$ coords. If the current event is adding we add the side to $S$ set. Then we check on its closest neighbours in the set. If the current segment is a top segment we can make a descend from its left vertex down to the intersection with it's lower neighbor. We find the point of the intersection, remember the segment where the point is located and remember that there can be a descend from a vertex to the new point. If the current side is the bottom side we make a descand from the upper neighbour to the left end of the current segment and do the same things. If the current event is deleting we analize its neighbours in the same way, but the descends start or end on the right end of the segment we are going to delete. It is important that if there are many events of one kind we should proceed them simultaneously, i.e. if there are many addings in the same $x$ coordinate we must add all the segments and then examine their neighbours. It is the same for deletings: firstly we analize the neighbours for all the segments and only then we delete them. Also in the case of equal $x$ coords of the events the adding events must be first, otherwise the solution is wrong for the case of two angles separated by a vertical line with vertices lying on this line. Set $S$ is easy to keep in container such as "set". We have to write a comparator for segments. We can do it in following way: two segments can be in $S$ simultaneously if and only if there is a vertical line that intersects both of them. In common case such a line is not the unique, all the possible values of $X$ are in segment $[l, r]$ that can be easily found if we know the coors of the ends of the segments. Then we can choose an arbitrary $X$ inside of $[l, r]$ and compare the ordinates of the intersection points. Is better to choose inner point because in this case we don't have to examine special cases of segments having a common point. After this we can build a graph. It's vertices are the vertices of the polygon and the ends of possible descends. The edges of the graphs are the sides of the polygon and the descends. The shortest path can be found using Dijkstra algorithm. The complexity of the solution is $O(n\log n)$.
[ "geometry", "graphs" ]
3,000
null
223
E
Planar Graph
A graph is called planar, if it can be drawn in such a way that its edges intersect only at their vertexes. An articulation point is such a vertex of an undirected graph, that when removed increases the number of connected components of the graph. A bridge is such an edge of an undirected graph, that when removed increases the number of connected components of the graph. You've got a connected undirected planar graph consisting of $n$ vertexes, numbered from $1$ to $n$, drawn on the plane. The graph has no bridges, articulation points, loops and multiple edges. You are also given $q$ queries. Each query is a cycle in the graph. The query response is the number of graph vertexes, which (if you draw a graph and the cycle on the plane) are located either inside the cycle, or on it. Write a program that, given the graph and the queries, will answer each query.
In the problem we were given an undirected planar graph without bridges, cutpoints, loops and multiedge laid on the plane. We get requests of the following type: to calculate the number of vertices inside the cycle or on it. Let us take an arbitrary vertex on the border of the graph, for example a vertex that has the least absciss. Let's add a new vertex with an edge to the chosen vertex in such way that the edge is outside the outer border of the graph. We'll call this new vertex a sink. Let's create a $1$ value flow running to the sink from each vertex except the sink. Flow can be created using breadth-first or depth-first search. This operation will take the $O(E)$ time. Let's examine any request. We assume that the cycle is oriented counter-clockwise (if it is not so, we can just reorient it). Let's make a cut on the graph. The first part will contain the vertices laying on the cycle or inside it, the second one - all remaining vertices including the sink. We'll now prove that the flow value through the cut is equal to the vertices number in the first part. It's obvious that we can calculate contribution from every vertex to the flow value independently. Let's assume that the vertex is situated in the first part. A unit flow runs from it to the sink along some path. As soon as this vertex and the sink are situated in different parts the flow passes the edges of the cut an odd number of times, that's why the contribution of this vertex to the flow through the cut is equal to $1$. Let's take now a vertex situated in the second part. As soon as it's situated in the same part as the sink the flow passes the edges of the cut an even number of times, that's why the contribution of this vertex to the flow through the cut is zero. In order to calculate the flow value through the cut we need to sum up flow values passing through the cut's edges. It's important to notice that every edge of the cut is incident to only one vertex lying on the cycle, that's why we can sum up flows passing though edges going outside the cycle for each vertex in the cycle. In order to find all edges going outside the cycle we'll sort all edges going from each vertex counter-clockwise by angle. In this case all edges going outside the cycle will be placed after the previous vertex of the cycle and before the following vertex of the cycle. That's why the sum of flow values over the edges going outside reduces to a sum over an segment which is easily calculated using partial sums. The complexity of the solution is $O(V\log V)$ for graph sorting plus $(U\log E)$ for the request where $l$ is the cycle length. There is $\log E$ in complexity because we have to know a position of a vertex in the adjacency list of another vertex.
[ "flows", "geometry", "graphs" ]
3,000
null
224
A
Parallelepiped
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.
You were given areas of three faces of a rectangular parallelepiped. Your task was to find the sum of lengths of it's sides. Let $a$, $b$ and $c$ be the lengths of the sides that have one common vertex. Then the numbers we are given are $s_{1} = ab$, $s_{2} = bc$ and $s_{3} = ca$. It is easy to find the lengths in terms of faces areas: $a={\sqrt{s_{1}s_{3}/s_{2}}}$, $b={\sqrt{s_{1}s_{2}/s_{3}}}$, $c={\sqrt{s_{2}s_{3}/s_{1}}}$. The answer is $4(a + b + c)$, because there are four sides that have lengths equal to $a$, $b$ and $c$. The complexity is $O(1)$.
[ "brute force", "geometry", "math" ]
1,100
null
224
B
Array
You've got an array $a$, consisting of $n$ integers: $a_{1}, a_{2}, ..., a_{n}$. Your task is to find a minimal by inclusion segment $[l, r]$ $(1 ≤ l ≤ r ≤ n)$ such, that among numbers $a_{l},  a_{l + 1},  ...,  a_{r}$ there are exactly $k$ distinct numbers. Segment $[l, r]$ ($1 ≤ l ≤ r ≤ n;$ $l, r$ are integers) of length $m = r - l + 1$, satisfying the given property, is called minimal by inclusion, if there is no segment $[x, y]$ satisfying the property and less then $m$ in length, such that $1 ≤ l ≤ x ≤ y ≤ r ≤ n$. Note that the segment $[l, r]$ doesn't have to be minimal in length among all segments, satisfying the given property.
You were given an array $a$ consisting of $n$ integers. Its elements $a_{i}$ were positive and not greater than $10^{5}$ for each $1 \le i \le n$. Also you were given positive integer $k$. You had to find minimal by inclusion segment $[l, r]$ such that there were exactly $k$ different numbers among $a_{l}, ..., a_{r}$. The definition of the "minimal by inclusion" you can read in the statement. Let us make a new array $cnt$. In the beginning its element $cnt_{i}$ is equal to number of occurencies of number $i$ in array $a$. It is possible to make this array because elements of $a$ are not very large. Amount of nonzero elements in $cnt$ is equal to amount of different elements in $a$. There is no solution if this number is less then $k$. If it is not true, we have to find the answer segment $[l, r]$. In the beginning let $[l, r] = [1, n]$. We decrease its right end $r$ by 1 until amount of different elements on the segment $[l, r]$ is less than $k$. We can keep the amount of different numbers in following way: we decrease $cnt_{ar}$ by $1$ if we delete element number $r$. Then we have to decrease current number of different elements by $1$ if $cnt_{ar}$ becomes zero. After this we return the last deleted element back to the segment in order to make amount of different elements equal to $k$. Then we have to do the same with the left end $l$, but we have not to decrease but to increase its value by $1$ on each step. Finally, we get a segment $[l, r]$. The amount of different numbers on it is equal to $k$ and on every its subsegment is less than $k$. Therefore, this segment is an answer. The complexity is $O(n)$.
[ "bitmasks", "implementation", "two pointers" ]
1,500
null
225
A
Dice Tower
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). Alice and Bob play dice. Alice has built a tower from $n$ dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees). Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.
You should iterate over all dices from up to down and restore answer. You can easily find number of the bottom side of the 1st dice. Using known sides of the 2nd dice you can find pair of numbets on top and bottom side of the 2nd dice. If one of them equal to number on bottom of the 1st dice, you can restore all numbers on the 2n dice. Then using this idea you can try restore numbers on the 3rd dice and so on. If you restored all numbers, you should write YES. If for some dice you cannot uniquely determine order of numbers on the top and botton sides, there will be at least 2 placing of numbers. In this case you shoyld write NO.
[ "constructive algorithms", "greedy" ]
1,100
null
225
B
Well-known Numbers
Numbers $k$-bonacci ($k$ is integer, $k > 1$) are a generalization of Fibonacci numbers and are determined as follows: - $F(k, n) = 0$, for integer $n$, $1 ≤ n < k$; - $F(k, k) = 1$; - $F(k, n) = F(k, n - 1) + F(k, n - 2) + ... + F(k, n - k)$, for integer $n$, $n > k$. Note that we determine the $k$-bonacci numbers, $F(k, n)$, only for integer values of $n$ and $k$. You've got a number $s$, represent it as a sum of several (at least two) \textbf{distinct} $k$-bonacci numbers.
Firstly you should generate all k-bonacci numbers less than $n$. For $k \le 32$ you can do it straightforward, for bigger $k$ you can see that all $k$-bonacci numbers less $10^{9}$ are powers of two only (and 0). So you will have no more then 100 numbers. Then you should use greedy algo. You should substract from $n$ maximal possible $k$-bonacci numbers. You should repeat this operation while $n$ is not decomposed. And in the end you will have answer. Why all numbers will be different? One of possible proves: $F(k, n) = F(k, n - 1) + F(k, n - 2) + ... + F(k, n - k)$ $F(k, n - 1) = F(k, n - 2) + F(k, n - 3) + ... + F(k, n - k - 1)$ You can substract the 2nd equation from the 1st one and you will recieve $F(k, n) + F(k, n - k - 1) = 2F(k, n - 1)$, that equal to $2F(k, n - 1) \ge F(k, n)$. This unequation also holds for $n \le k$. Suppose than greedy also constricted 2 equal numbers $F(k, x)$ in decomposition. But then in virtue of unequation we should take number $F(k, x + 1)$ insead these 2 numbers. Contradiction. But you didn't need prove than greedy algo works, you might believe that it works:)
[ "binary search", "greedy", "number theory" ]
1,600
null
225
C
Barcode
You've got an $n × m$ pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture. A picture is a barcode if the following conditions are fulfilled: - All pixels in each column are of the same color. - The width of each monochrome vertical line is at least $x$ and at most $y$ pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than $x$ or greater than $y$.
Firstly you should calculate number of white and black pixels in every column. After that you should calculate number of white and black pixels for every prefix in sequence of columns. Now you can calculate number of black or white pixels in every vertical line of any width in $O(1)$. Now you should use dynamic programming. Let's $dp[i][j]$ will store numbers of repainted pixels in prefix from the 1st column to the $j$-th and color of the last column will be white for $i = 0$ and black for $i = 1$. Than you can recalculate $dp$ using forlulas: $dp[0][0] = dp[1][0] = 0$ $d p[0][i]=m i n_{a\in[x,y]}(d p[1][i-a]+s u m-o f-w h i t e s(i-a+1,i))$ $d p[1][i]=m i n_{a\in[x,y]}(d p[0][i-a]+s u m-o f-b l a c k s(i-a+1,i))$ Answer will be $min(dp[0][m], dp[1][m])$. This solution works in $O(nm + m * (y - x))$.
[ "dp", "matrices" ]
1,700
null
225
D
Snake
Let us remind you the rules of a very popular game called "Snake" (or sometimes "Boa", "Python" or "Worm"). The game field is represented by an $n × m$ rectangular table. Some squares of the field are considered impassable (walls), all other squares of the fields are passable. You control a snake, the snake consists of segments. Each segment takes up exactly one passable square of the field, but any passable square contains at most one segment. All segments are indexed by integers from $1$ to $k$, where $k$ is the snake's length. The $1$-th segment is the head and the $k$-th segment is the tail. For any $i$ ($1 ≤ i < k$), segments with indexes $i$ and $i + 1$ are located in the adjacent squares of the field, that is, these squares share a common side. One of the passable field squares contains an apple. The snake's aim is to reach the apple and eat it (that is, to position its head in the square with the apple). The snake moves throughout the game. During one move the snake can move its head to an adjacent field square. All other segments follow the head. That is, each segment number $i$ $(1 < i ≤ k)$ moves to the square that has just had segment number $i - 1$. Consider that all segments including the head move simultaneously (see the second test sample). If the snake's head moves to an unpassable square or to the square, occupied by its other segment, the snake dies. That's why we will consider such moves unvalid. Your task is to determine the minimum number of valid moves that the snake needs to reach the apple.
There is just BFS. State is head place and mask that store place of tail: using 2 bits you can code position of every segment in relation to previous segment. Mask will contain no more than 16 bits, and number of all states will be no more than $4^{8} \times 15 \times 15$ (also you can try understand that number of states no more than $3^{8} \times 15 \times 15$). Then you should just carefully implement it.
[ "bitmasks", "dfs and similar", "graphs", "implementation" ]
2,200
null
225
E
Unsolvable
Consider the following equation: \[ z=\left[{\frac{x}{2}}\right]+y+x y, \] where sign $[a]$ represents the integer part of number $a$.Let's find all integer $z$ $(z > 0)$, for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers $x$ and $y$ $(x, y > 0)$, for which the given above equation holds. Let's write out all such $z$ in the increasing order: $z_{1}, z_{2}, z_{3}$, and so on $(z_{i} < z_{i + 1})$. Your task is: given the number $n$, find the number $z_{n}$.
You have $z = [x / 2] + y + xy$. That is equivalent to $z = [2k / 2] + y + 2ky$, where $x = 2k, k > 0$ or $z = [(2k + 1) / 2] + y + (2k + 1)y$, where $x = 2k + 1, k \ge 0$. $z = k + y + 2ky, k > 0$ or $z = k + y + (2k + 1)y, k \ge 0$. Still more steps: $2z + 1 = 2k + 2y + 4ky + 1, k > 0$ or $z + 1 = k + 2y + 2ky + 1, k \ge 0$. $2z + 1 = (2k + 1)(2y + 1), k > 0$ or $z + 1 = (2y + 1)(k + 1), k \ge 0$. From the 2nd equation you can see than $z$ should be $2^{t} - 1$ because otherwise $z + 1$ will have odd divisor and we can build solution. From the 1st equation you can see that $2^{t + 1} - 1$ should be prime, otherwise we also can build solution. If $z = 2^{t} - 1$ and $2^{t + 1} - 1$ is prime, obliviously there are no solutions. Prime numbers like $2^{a} - 1$ are Mersenne primes. Only about 46 such numbers are found now. Powers of 2 for the firts 40 numbers you can find for example here.
[ "math", "number theory" ]
2,100
null
226
A
Flying Saucer Segments
An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!). The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one — to the 1-st and the 3-rd ones, the 3-rd one — only to the 2-nd one. The transitions are possible only between the adjacent sections. The spacecraft team consists of $n$ aliens. Each of them is given a rank — an integer from $1$ to $n$. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section $a$ to section $b$ only if it is senior in rank to all aliens who are in the segments $a$ and $b$ (besides, the segments $a$ and $b$ are of course required to be adjacent). Any alien requires exactly $1$ minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship. Alien $A$ is senior in rank to alien $B$, if the number indicating rank $A$, is more than the corresponding number for $B$. At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task. Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo $m$.
Let $F_{n}$ be the answer for the task, where $n$ is equal to the amount of aliens. Let's assume, that we've solved problem for $n - 1$ aliens, i.e. we know the value of $F_{n - 1}$. Let's try to find value of $F_{n}$. Notice, that the most junior alien in rank will be able to leave the $3^{rd}$ section, if and only if all other aliens are in the $1^{st}$ section. So, now we know first $F_{n - 1}$ actions. Then the most junior alien may go to the $2^{nd}$ section. To make for him entrance to the $1^{st}$ section possible, it's necessary for all other aliens to return to the first one. So, $F_{n - 1}$ more actions are necessary. At last, after the most junior alien will go to the $1^{st}$ section, $F_{n - 1}$ more actions are required for $n - 1$ other aliens to return to the $1^{st}$ section from the $3^{rd}$. So, $F_{n} = F_{n - 1} + 1 + F_{n - 1} + 1 + F_{n - 1}$. It allows to count $F_{n}$ using matrix exponentiation in $O(log n)$, but we'll improve current solution. Let's add $1$ to both parts of the equality and after elementary operations we'll have $F_{n} = 3 \cdot (F_{n - 1} + 1) - 1$. Now it's easy to solve this reccurence: $F_{n} = 3^{n} - 1$. To count $F_{n}$ quickly you should use binary power method. Solution's complexity - $O(log n)$. Don't forget that if $3^{n}$ $mod$ $m = 0$, answer is equal to $m - 1$, but not $- 1$. And, in conclusion, notice that the task is equal to Hanoi Towers problem with a slight modification (it's impossible to move disks between one pair of rods).
[ "math" ]
1,400
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <cstdio> #include <vector> #include <cctype> #include <string> #include <ctime> #include <cmath> #include <set> #include <map> typedef long double LD; typedef long long LL; using namespace std; #define sz(A) (A).size() #define mp make_pair #define pb push_back int n, m; LL power(int num, int deg) { if (!deg) return 1; if (deg % 2) { return (power(num, deg - 1) * num) % m; } else { LL sqrt_res = power(num, deg / 2); return (sqrt_res * sqrt_res) % m; } } int main() { cin >> n >> m; LL res = power(3, n); res--; if (res < 0) res += m; cout << res << endl; return 0; }
226
B
Naughty Stone Piles
There are $n$ piles of stones of sizes $a_{1}, a_{2}, ..., a_{n}$ lying on the table in front of you. During one move you can take one pile and add it to the other. As you add pile $i$ to pile $j$, the size of pile $j$ increases by the current size of pile $i$, and pile $i$ stops existing. The cost of the adding operation equals the size of the added pile. Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than $k$ times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you $q$ variants (not necessarily distinct) of what $k$ might equal. Your task is to find the minimum cost for each of $q$ variants.
Consider the following interpretation of the problem: stone piles are graph vertices. Operation "add pile $a$ to pile $b$" changes to operation of suspencion of subtree of vertice $b$ to vertice $a$. Numbers, written on vertices, - piles' sizes. Your task is to get such tree configuration, that each vertice has no more than $k$ subtrees suspended to it, and sum of the products of numbers, written on vertices, and vertices' depth (where root's depth is 0) is minimal. In order to minimize the sum, at first, vertice with a larger number must be not deeply than vertice with smaller number (otherwise it's possible to change them and to get less sum), at second, each inner vertice, besides, maybe, one, has exactly $k$ successors (the second condition is also proved using proof by contradiction). Now you are to learn how to calculate sum (described above) for this configuration quickly. In order do to it, let's sort piles' size array, and then let's do the following: at first, let's add to answer sum of sizes of piles from $1^{st}$ to $k^{th}$ (in 0-indexed array, sorted in non-increasing order), multiplied by 1; then sum of sizes of next $k^{2}$ piles, multiplied by 2; and so on till the end of array. In order to answer for the query about the sum of segment, precalculate sums of prefixes immediately after array sorting. Now in the case $k > 1$ we can find answer in $O(log n)$. If you follow the same considerations for $k = 1$, answer for query will get $O(n)$ operations that's why solution will get TL, if $k$ is equal to $1$ in most of the queries. So you should calculate the answer for $k = 1$ beforehand and memorize it, in order to response such queries in $O(1)$. Complexity - $O(n \cdot log$ $n$ $+$ $q$ $ \cdot log$ $n)$.
[ "greedy" ]
1,900
#include <algorithm> #include <iostream> #include <cstring> #include <cassert> #include <cstdlib> #include <cstdio> #include <vector> #include <string> #include <cmath> #include <set> #include <map> using namespace std; typedef long long LL; typedef long double LD; #define pb push_back #define mp make_pair #define sz(A) (int)(A).size() const int N = int(1e5 + 5); LL s[N], a[N]; LL sum(LL l, LL r) { r = min(r, LL(N - 1)); return s[r] - s[l - 1]; } int main() { int n; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; sort(a, a + n); reverse(a, a + n); s[0] = a[0]; for (int i = 1; i < N; i++) s[i] = s[i - 1] + a[i]; int q; cin >> q; LL res_1 = 0; for (int i = 1; i < n; i++) res_1 += a[i] * i; for (int i = 0; i < q; i++) { int k; cin >> k; if (k == 1) { cout << res_1 << " "; continue; } LL res = 0, sz = 1; for (LL j = 1, t = 1; j < n; j += sz, t++) { sz *= k; cerr << j + sz - 1 << endl; res += sum(j, j + sz - 1) * t; } cout << res << " "; } cout << endl; return 0; }
226
C
Anniversary
There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations. Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set $A$, consisting of numbers $l$, $l + 1$, $l + 2$, $...$, $r$; let's consider all its $k$-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one. Dima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where $F_{1} = 1$, $F_{2} = 1$, $F_{n} = F_{n - 1} + F_{n - 2}$ for $n ≥ 3$. Dima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by $m$.
At first, let's prove the statement: $GCD(F_{n}, F_{m}) = F_{GCD(n, m)}$. Let's express $F_{n + k}$ using $F_{n}$ and $F_{k}$. We'll get the formula: $F_{n + k} = F_{k} \cdot F_{n + 1} + F_{k - 1} \cdot F_{n}$, which is easy to prove by induction. Then use the derived formula and notice, that $GCD(F_{n + k}, F_{n}) = GCD(F_{k}, F_{n})$. Now you are to notice an analogy with Euclidean algorithm and to understand, that we've got necessary equality for $GCD$ of two Fibonacci numbers. So, our current task is to find in the given set subset of $k$ (or at least of $k$) elements with maximal possible $GCD$. To be exactly, to find this $GCD$. Let the answer be equal to $q$. Then $\left|{\frac{r}{q}}\right|$ $-$ $\textstyle{\left[{\frac{L}{q}}\right]}$$ \rceil + 1 \ge k$ (1) must be true. Notice, that for each summand from left part of inequality $O($ $\sqrt{n u m e r a t o r}$ $)$ segments exist, in which its value is constant. Moreover, we can find all these segments and values in $O(\sqrt{r})$. To be more precise, we are intersted in such $q$, that in the point $q - 1$ value of at least one summand changes (obviously, increases). There are also $O(\sqrt{r})$ such values. Go over all of them and try to use each of them as the answer (i.e., check inequality (1) for each of them), and choose maximum from all satisfying numbers. The answer always exists, as $q = 1$ is true for any input. So, we've found index of required Fibonacci number. The number itself can be calculated by matrix exponentiation. - $O({\sqrt{r}}+l o g~r)$.
[ "data structures", "implementation", "math", "matrices", "number theory" ]
2,400
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <complex> #include <cstdio> #include <vector> #include <cctype> #include <string> #include <ctime> #include <cmath> #include <set> #include <map> typedef long double LD; typedef long long LL; using namespace std; #define sz(A) (int)(A).size() #define mp make_pair #define pb push_back int m; vector<LL> dif_pos; struct matr { LL m[2][2]; }; matr operator * (matr a, matr b) { matr res; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) { res.m[i][j] = 0; for (int k = 0; k < 2; k++) { res.m[i][j] = (res.m[i][j] + a.m[i][k] * b.m[k][j]) % m; } } return res; } matr power(matr m, LL p) { if (p == 1) return m; if (p % 2) return m * power(m, p - 1); return power(m * m, p / 2); } int fib(LL num) { if (num == 1) return 1; matr f; f.m[0][0] = 0; f.m[0][1] = f.m[1][0] = f.m[1][1] = 1; f = power(f, num); return f.m[0][1]; } int main() { LL l, r, k; cin >> m >> l >> r >> k; if(m == 1){ cout << 0 << endl; exit(0); } for (LL d = 1; d * d <= r; d++) { LL d2 = r / d; dif_pos.pb(d); dif_pos.pb(d2); } for (LL d = 1; d * d <= l; d++) { if (l % d == 0) dif_pos.pb(l / d); else { if (d) { dif_pos.pb(l / (d - 1)); } } } LL ans = 0; for (int i = 0; i < sz(dif_pos); i++) { LL d_b = l / dif_pos[i] + LL(l % dif_pos[i] != 0); LL u_b = r / dif_pos[i]; if (u_b - d_b + 1 >= k) ans = max(ans, dif_pos[i]); } cout << fib(ans) << endl; return 0; }
226
D
The table
Harry Potter has a difficult homework. Given a rectangular table, consisting of $n × m$ cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second — in the selected column. Harry's task is to make non-negative the sum of the numbers in each row and each column using these spells. Alone, the boy can not cope. Help the young magician!
Let's get the required table. Act in the following way: find any row or column with negative sum and invert it. Notice, that sum of numbers in the entire table will always increase (at least, by $2$). It can't increase permanently, because its maximal possible summary change is $200 \cdot n \cdot m$. So we'll get the required table anyway. It takes us not more than $100 \cdot n \cdot m$ operations (applying of the spell), each of those is performed in $O(n)$ or $O(m)$. So, we've learned how to get required table in not more than ~ $100^{4}$ operations. Now let's restore the answer. It's easy to understand that it will contain those rows and columns, which we've inverted odd times.
[ "constructive algorithms", "greedy" ]
2,100
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <bitset> #include <sstream> #include <algorithm> #include <functional> #include <numeric> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #include <cassert> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); ++i) #define for1(i, n) for(int i = 1; i <= int(n); ++i) #define ford(i, n) for(int i = int(n) - 1; i >= 0; --i) #define fore(i, l, r) for(int i = int(l); i < int(r); ++i) #define sz(v) int((v).size()) #define all(v) (v).begin(), (v).end() #define pb push_back #define X first #define Y second #define mp make_pair #define debug(x) {cerr << #x << " = " << x << endl;} template<typename T> inline T abs(T a){ return ((a < 0) ? -a : a); } template<typename T> inline T sqr(T a){ return a * a; } typedef long long li; typedef long double ld; typedef pair<int, int> pt; const int INF = (int)1E9 + 7; const ld EPS = 1E-9; const ld PI = 3.1415926535897932384626433832795; const int NMAX = 2000; int a[NMAX][NMAX], r[NMAX], c[NMAX], mr[NMAX], mc[NMAX]; int n, m; int main() { #ifdef myproject freopen("input.txt", "rt", stdin); //freopen("output.txt", "wt", stdout); #endif srand(time(NULL)); scanf("%d%d", &n, &m); // n = rand()%100+1; // m = rand()%100+1; forn(i, n) forn(j, m){ scanf("%d", &a[i][j]); // a[i][j] = rand()%100 - 50; } forn(i, n){ forn(j, m){ r[i] += a[i][j]; c[j] += a[i][j]; } } forn(i, n) mr[i] = 1; forn(j, m) mc[j] = 1; #ifdef myproject cout << n << " " << m << endl; forn(i, n){ forn(j, m){ cout << a[i][j]*mr[i]*mc[j] << " "; } cout << endl; } #endif int iter = 0; while(true){ iter++; int rid = -1; forn(i, n){ if(r[i] < 0){ rid = i; break; } } if(rid != -1){ forn(j, m){ c[j] -= a[rid][j] * mr[rid] * mc[j]; } mr[rid] *= -1; forn(j, m){ c[j] += a[rid][j] * mr[rid] * mc[j]; } r[rid] *= -1; continue; } int cid = -1; forn(j, m){ if(c[j] < 0){ cid = j; break; } } if(cid != -1){ forn(i, n){ r[i] -= a[i][cid] * mc[cid] * mr[i]; } mc[cid] *= -1; forn(i, n){ r[i] += a[i][cid] * mc[cid] * mr[i]; } c[cid] *= -1; continue; } break; } vector<int> nr(n), nc(m); forn(i, n){ forn(j, m){ nr[i] += a[i][j] * mr[i] * mc[j]; nc[j] += a[i][j] * mr[i] * mc[j]; } } assert(*min_element(all(nr)) >= 0); assert(*max_element(all(nc)) >= 0); /* cout << endl; forn(i, n){ forn(j, m){ cout << a[i][j]*mr[i]*mc[j] << " "; } cout << endl; }*/ vector<int> rr, cc; forn(i, n) if(mr[i] == -1) rr.pb(i); forn(j, m) if(mc[j] == -1) cc.pb(j); cout << sz(rr) << " "; forn(i, sz(rr)) cout << rr[i]+1 << " "; cout << endl; cout << sz(cc) << " "; forn(i, sz(cc)) cout << cc[i]+1 << " "; cout << endl; #ifdef myproject cerr << "Iterations = " << iter << endl; #endif return 0; }
226
E
Noble Knight's Path
In Berland each feudal owns exactly one castle and each castle belongs to exactly one feudal. Each feudal, except one (the King) is subordinate to another feudal. A feudal can have any number of vassals (subordinates). Some castles are connected by roads, it is allowed to move along the roads in both ways. Two castles have a road between them if and only if the owner of one of these castles is a direct subordinate to the other owner. Each year exactly one of these two events may happen in Berland. - The barbarians attacked castle $c$. The interesting fact is, the barbarians never attacked the same castle twice throughout the whole Berlandian history. - A noble knight sets off on a journey from castle $a$ to castle $b$ (provided that on his path he encounters each castle not more than once). Let's consider the second event in detail. As the journey from $a$ to $b$ is not short, then the knight might want to stop at a castle he encounters on his way to have some rest. However, he can't stop at just any castle: his nobility doesn't let him stay in the castle that has been desecrated by the enemy's stench. A castle is desecrated if and only if it has been attacked after the year of $y$. So, the knight chooses the $k$-th castle he encounters, starting from $a$ (castles $a$ and $b$ aren't taken into consideration), that hasn't been attacked in years from $y + 1$ till current year. The knights don't remember which castles were attacked on what years, so he asked the court scholar, aka you to help them. You've got a sequence of events in the Berland history. Tell each knight, in what city he should stop or else deliver the sad news — that the path from city $a$ to city $b$ has less than $k$ cities that meet his requirements, so the knight won't be able to rest.
It's easy to guess that castles form a tree. Let's build heavy-light decomposition over it. Moreover, let's build persistent segment tree (with sum as the function) over each path. Tree's vertex will contain $0$, if castle wasn't attacked by barbarians, and $1$ otherwise. Each knight's path should be divided into not more than two subpaths each of them lays on the path from one of the route's end to tree's root (just use lca in order to do it). Now let's solve the problem for each of the subpaths separately. We should sequentially process paths from heavy-light decomposition and single vertices, which lay on subpath. We are going to count the amount of vertices, which was not visited since year $y + 1$ up to the current year, i.e. (in the case of a path of the decomposition) such vertices, that the difference between values in the current version of persistent segment tree and in the version corresponding to year $y$ (use binary search to find required version in the list of versions) is equal to zero (in case with single vertice it's enough to remember time when vertice was visited). As soon as the amount of appropriate vertices become not less than $k$, we should simultaneously walk down in two tree's versions in order to get the answer. If the $k^{th}$ vertex isn't found on the first subpath, you should pay attention on the fact, that as we always go from down to up, we should accurately recalculate required vertex's number, in order to know it's position in the second subpath from down to up. Complexity: $O(m \cdot log^{2}$ $n)$ - in each query of the first type it can be necessary to update some segment tree, this action takes $O(log$ $n)$ operations; in each query of the second type there are $O(log$ $n)$ decomposition's paths, each of them is processed in $O(log$ $n)$ (firstly, binary search through versions' list, then query to the tree/walking down).
[ "data structures", "trees" ]
2,900
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <complex> #include <cstdio> #include <vector> #include <cctype> #include <string> #include <ctime> #include <cmath> #include <set> #include <map> typedef long double LD; typedef long long LL; using namespace std; #define sz(A) (int)(A).size() #define mp make_pair #define pb push_back const int N = int(1e5 + 5), INF = int(1e9); struct node { int l, r, val; node() {} node(int a, int b, int c) { l = a, r = b, val = c; } }; vector<int> graph[N]; int n, root, m, par[N]; int sz[N], heavy[N], depth[N]; int first[N], t = 0, sz_lca; pair<int, int> times[2 * N], tree_lca[8 * N]; bool in_decomp[N]; int num_trees, num_tree_in[N], pos_tree_in[N], sz_ptree[N]; vector<int> tree[N]; vector< pair<int, int> > roots[N]; vector<node> ptree[N]; void dfs(int v, int d) { depth[v] = d; sz[v] = 1; heavy[v] = -1; int mx = 0; for (int i = 0; i < sz(graph[v]); i++) { int to = graph[v][i]; if (!first[v]) first[v] = t + 1; times[t++] = mp(d, v); if (!first[to]) first[to] = t + 1; times[t++] = mp(d + 1, to); dfs(to, d + 1); sz[v] += sz[to]; if (sz[to] > mx) { mx = sz[to]; heavy[v] = to; } } } void build_lca() { sz_lca = 1; while (sz_lca < t) sz_lca <<= 1; for (int i = sz_lca; i < sz_lca + t; i++) tree_lca[i] = times[i - sz_lca]; for (int i = sz_lca + t; i < 2 * sz_lca; i++) tree_lca[i] = mp(INF, -1); for (int i = sz_lca - 1; i > 0; i--) tree_lca[i] = min(tree_lca[i * 2], tree_lca[i * 2 + 1]); } pair<int, int> min_lca(int l, int r, int L, int R, int v) { if (r <= L || R <= l) return mp(INF, -1); if (l <= L && R <= r) return tree_lca[v]; int mid = (L + R) / 2; return min( min_lca(l, r, L, mid, v * 2), min_lca(l, r, mid, R, v * 2 + 1) ); } int lca(int v1, int v2) { if (first[v1] > first[v2]) swap(v1, v2); return min_lca(first[v1], first[v2] + 1, 1, sz_lca + 1, 1).second; } void dfs_heavy(int v) { if (!in_decomp[v]) { int now = v; while (now != -1) { tree[num_trees].pb(now); in_decomp[now] = 1; num_tree_in[now] = num_trees; pos_tree_in[now] = sz(tree[num_trees]); now = heavy[now]; } num_trees++; } for (int i = 0; i < sz(graph[v]); i++) dfs_heavy(graph[v][i]); } node create_node(int l, int r, int num_t) { return node(l, r, ptree[num_t][l].val + ptree[num_t][r].val); } int update_ptree(int num_t, int pos, int L, int R, int v, int new_val) { if (L + 1 == R) { ptree[num_t].pb( create_node(0, 0, num_t) ); ptree[num_t][ sz(ptree[num_t]) - 1 ].val = new_val; return sz(ptree[num_t]) - 1; } int mid = (L + R) / 2; if (pos < mid) { int new_v = update_ptree(num_t, pos, L, mid, ptree[num_t][v].l, new_val); ptree[num_t].pb( create_node(new_v, ptree[num_t][v].r, num_t) ); } else { int new_v = update_ptree(num_t, pos, mid, R, ptree[num_t][v].r, new_val); ptree[num_t].pb( create_node(ptree[num_t][v].l, new_v, num_t) ); } assert(R - L >= ptree[num_t][sz(ptree[num_t]) - 1].val); return sz(ptree[num_t]) - 1; } int sum_ptree(int num_t, int l, int r, int L, int R, int v1, int v2) { if (r <= L || R <= l) return 0; if (l <= L && R <= r) return (R - L) - (ptree[num_t][v1].val - ptree[num_t][v2].val); int mid = (L + R) / 2; return sum_ptree(num_t, l, r, L, mid, ptree[num_t][v1].l, ptree[num_t][v2].l) + sum_ptree(num_t, l, r, mid, R, ptree[num_t][v1].r, ptree[num_t][v2].r); } int num_version(int tree, int timer) { int l = 0, r = sz(roots[tree]); while (l + 1 < r) { int mid = (l + r) / 2; if (roots[tree][mid].first <= timer) l = mid; else r = mid; } return l; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &par[i]); if (par[i] == 0) root = i; else graph[ par[i] ].pb(i); } dfs(root, 1); build_lca(); dfs_heavy(root); for (int i = 0; i < num_trees; i++) { int number = sz(tree[i]); sz_ptree[i] = 1; while (sz_ptree[i] < number) sz_ptree[i] <<= 1; ptree[i].resize(sz_ptree[i] * 2); roots[i].pb(mp(0, 1)); for (int j = 1; j < sz_ptree[i]; j++) { ptree[i][j].l = j * 2; ptree[i][j].r = j * 2 + 1; } for (int j = sz_ptree[i]; j < 2 * sz_ptree[i]; j++) { if (j - sz_ptree[i] < number) ptree[i][j].val = 1; else ptree[i][j].val = 0; } for (int j = sz_ptree[i] - 1; j > 0; j--) { ptree[i][j].val = ptree[i][j * 2].val + ptree[i][j * 2 + 1].val; } } scanf("%d", &m); for (int i = 0; i < m; i++) { int type; scanf("%d", &type); if (type == 1) { int v; scanf("%d", &v); int t_num = num_tree_in[v]; int prev_sz = sz(roots[t_num]); roots[t_num].pb(mp(i + 1, update_ptree(t_num, pos_tree_in[v], 1, sz_ptree[t_num] + 1, roots[t_num][prev_sz - 1].second, 0))); } else { int v1, v2, k, start; scanf("%d%d%d%d", &v1, &v2, &k, &start); int v3 = lca(v1, v2), now; bool ans_given = 0; int num_t = num_tree_in[v3]; int vers = num_version(num_t, start), num_r = sz(roots[num_t]); int root_val = sum_ptree(num_t, pos_tree_in[v3], pos_tree_in[v3] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second); int start_pos = pos_tree_in[v3]; if (v3 == v2 || v3 == v1) start_pos++; now = par[v1]; while (depth[now] >= depth[v3] && now != v2) { int num_t = num_tree_in[now], num_r = sz(roots[num_t]), sum = 0; int vers = num_version(num_t, start); if (depth[v3] < depth[ tree[num_t][0] ]) { sum = sum_ptree(num_t, 1, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second); } else { sum = sum_ptree(num_t, start_pos, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second); } if (sum < k) { k -= sum; } else { k = sum - k + 1; int left_b = 1; if (num_t == num_tree_in[v3]) left_b = start_pos; int r1 = roots[num_t][num_r - 1].second, r2 = roots[num_t][vers].second, L = 1, R = sz_ptree[num_t] + 1; while (L + 1 < R) { int mid = (L + R) / 2; if ( sum_ptree(num_t, left_b, pos_tree_in[now] + 1, L, mid, ptree[num_t][r2].l, ptree[num_t][r1].l) < k) { k -= sum_ptree(num_t, left_b, pos_tree_in[now] + 1, L, mid, ptree[num_t][r2].l, ptree[num_t][r1].l); r1 = ptree[num_t][r1].r; r2 = ptree[num_t][r2].r; L = mid; } else { r1 = ptree[num_t][r1].l; r2 = ptree[num_t][r2].l; R = mid; } } printf("%d ", tree[num_t][L - 1]); ans_given = 1; break; } now = par[ tree[num_t][0] ]; } if (ans_given) continue; now = par[v2]; int sum_path = 0; if (v3 != v2 && v3 != v1) k += root_val; while (depth[now] >= depth[v3] && now != v1) { int num_t = num_tree_in[now], num_r = sz(roots[num_t]); int vers = num_version(num_t, start); if (depth[v3] < depth[ tree[num_t][0] ]) { sum_path += sum_ptree(num_t, 1, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second); } else { sum_path += sum_ptree(num_t, start_pos, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second); } now = par[ tree[num_t][0] ]; } if (sum_path < k) { printf("-1 "); continue; } k = sum_path - k + 1; now = par[v2]; while (depth[now] >= depth[v3] && now != v1) { int num_t = num_tree_in[now], num_r = sz(roots[num_t]), sum = 0; int vers = num_version(num_t, start); if (depth[v3] < depth[ tree[num_t][0] ]) { sum = sum_ptree(num_t, 1, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second); } else { sum = sum_ptree(num_t, start_pos, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second); } if (sum < k) { k -= sum; } else { k = sum - k + 1; int left_b = 1; if (num_t == num_tree_in[v3]) left_b = start_pos; int r1 = roots[num_t][num_r - 1].second, r2 = roots[num_t][vers].second, L = 1, R = sz_ptree[num_t] + 1; while (L + 1 < R) { int mid = (L + R) / 2; if ( sum_ptree(num_t, left_b, pos_tree_in[now] + 1, L, mid, ptree[num_t][r2].l, ptree[num_t][r1].l) < k) { k -= sum_ptree(num_t, left_b, pos_tree_in[now] + 1, L, mid, ptree[num_t][r2].l, ptree[num_t][r1].l); r1 = ptree[num_t][r1].r; r2 = ptree[num_t][r2].r; L = mid; } else { r1 = ptree[num_t][r1].l; r2 = ptree[num_t][r2].l; R = mid; } } printf("%d ", tree[num_t][L - 1]); break; } now = par[ tree[num_t][0] ]; } } } return 0; }
227
A
Where do I Turn?
Trouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point $C$ and began to terrorize the residents of the surrounding villages. A brave hero decided to put an end to the dragon. He moved from point $A$ to fight with Gorynych. The hero rode from point $A$ along a straight road and met point $B$ on his way. The hero knows that in this land for every pair of roads it is true that they are either parallel to each other, or lie on a straight line, or are perpendicular to each other. He also knows well that points $B$ and $C$ are connected by a road. So the hero must either turn 90 degrees to the left or continue riding straight ahead or turn 90 degrees to the right. But he forgot where the point $C$ is located. Fortunately, a Brave Falcon flew right by. It can see all three points from the sky. The hero asked him what way to go to get to the dragon's lair. If you have not got it, you are the falcon. Help the hero and tell him how to get him to point $C$: turn left, go straight or turn right. At this moment the hero is believed to stand at point $B$, turning his back to point $A$.
Let's consider cross product of vectors $\stackrel{\longrightarrow}{A B}$ and $\overline{{B C}}$, which is equal to $\overline{{{A B_{x}}}}\cdot\overline{{{B C_{u}}}}-\overline{{{A B_{y}}}}\cdot\overline{{{B C_{x}}}}$. Sign of cross product defines sign of a sine of oriented angle between vectors (because cross product is also equal to $|\overline{{{A B}}}|\cdot|\overline{{{B C}}}|\cdot s i n(\overline{{{A B}}},\overline{{{B C}}})$), and that sign leads us to the correct answer. If cross product is equal to zero, then $A, B$ and $C$ lay on the same straight line. So the answer is <>. If cross product is more than zero, then answer is <>. And, at last, if it's less than zero, the answer is <>. Also you should notice that the value of cross product doesn't fit 32-bit type, so you have to use 64-bit type in order to avoid integer overflow.
[ "geometry" ]
1,300
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <complex> #include <cstdio> #include <vector> #include <cctype> #include <string> #include <ctime> #include <cmath> #include <set> #include <map> typedef long double LD; typedef long long LL; using namespace std; #define sz(A) (int)(A).size() #define mp make_pair #define pb push_back struct vect { int x, y; vect() {} vect(int a, int b) { x = a, y = b; } void read() { cin >> x >> y; } }; vect operator - (vect a, vect b) { return vect(a.x - b.x, a.y - b.y); } LL operator % (vect a, vect b) { return LL(a.x) * b.y - LL(a.y) * b.x; } int main() { vect a, b, c; a.read(); b.read(); c.read(); vect ab = b - a, bc = c - b; if (ab % bc == 0) { puts("TOWARDS"); } else { if (ab % bc > 0) { puts("LEFT"); } else { puts("RIGHT"); } } return 0; }
227
B
Effective Approach
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is. Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the $1$-st one (in this problem we consider the elements of the array indexed from $1$ to $n$) and ending with the $n$-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the $n$-th and ending with the $1$-st one. Sasha argues that the two approaches are equivalent. To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from $1$ to $n$, and generated $m$ queries of the form: find element with value $b_{i}$ in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand. But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
Let's assume that number $t$ is on the $ind_{t}^{th}$ position in the original permutation. Then, obviously, during iterating from left to right this number will be found in $ind_{t}$ comparisons, and during iterating from right to left - in $n - ind_{t} + 1$ comparisons. Let's declare additional array, in $i^{th}$ element of each there will be such number $j$, that $a_{j} = i$. This array allows to process each query in $O(1)$ using formulas referred above. Additional array is built in $O(n)$ during iterating array $a$. So, the final complexity is $O(n + m)$.
[ "implementation" ]
1,100
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <cstdio> #include <vector> #include <cctype> #include <string> #include <ctime> #include <cmath> #include <set> #include <map> typedef long double LD; typedef long long LL; using namespace std; #define sz(A) (int)(A).size() #define mp make_pair #define pb push_back const int N = int(1e5 + 3); int n, m, pos[N]; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { int num; scanf("%d", &num); pos[num] = i + 1; } LL sum1 = 0, sum2 = 0; scanf("%d", &m); for (int i = 0; i < m; i++) { int q; scanf("%d", &q); sum1 += pos[q]; sum2 += n - pos[q] + 1; } printf("%I64d %I64d ", sum1, sum2); return 0; }
228
A
Is your horseshoe on the other hoof?
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.
In this problem you should count different numbers from input $cnt$ and print $4-cnt$. You could do it in different ways. For example, you could use set.
[ "implementation" ]
800
null
228
B
Two Tables
You've got two rectangular tables with sizes $n_{a} × m_{a}$ and $n_{b} × m_{b}$ cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the $i$-th row and the $j$-th column, as $a_{i, j}$; we will define the element of the second table, located at the intersection of the $i$-th row and the $j$-th column, as $b_{i, j}$. We will call the pair of integers $(x, y)$ a shift of the second table relative to the first one. We'll call the overlap factor of the shift $(x, y)$ value: \[ \sum_{i,j}a_{i,j}\cdot b_{i+x,j+y}, \] where the variables $i, j$ take only such values, in which the expression $a_{i, j}·b_{i + x, j + y}$ makes sense. More formally, inequalities $1 ≤ i ≤ n_{a}, 1 ≤ j ≤ m_{a}, 1 ≤ i + x ≤ n_{b}, 1 ≤ j + y ≤ m_{b}$ must hold. If there are no values of variables $i, j$, that satisfy the given inequalities, the value of the sum is considered equal to 0. Your task is to find the shift with the maximum overlap factor among all possible shifts.
In this problem you should carefully consider every shift $- N < = x, y < = N$, count the answer and find the maximum value. The complexity of solution is $O(N^{4})$.
[ "brute force", "implementation" ]
1,400
null
228
C
Fractal Detector
Little Vasya likes painting fractals very much. He does it like this. First the boy cuts out a $2 × 2$-cell square out of squared paper. Then he paints some cells black. The boy calls the cut out square a fractal pattern. Then he takes a clean square sheet of paper and paints a fractal by the following algorithm: - He divides the sheet into four identical squares. A part of them is painted black according to the fractal pattern. - Each square that remained white, is split into 4 lesser white squares, some of them are painted according to the fractal pattern. Each square that remained black, is split into 4 lesser black squares. In each of the following steps step 2 repeats. To draw a fractal, the boy can make an arbitrary positive number of steps of the algorithm. But he need to make at least two steps. In other words step 2 of the algorithm \textbf{must be done at least once}. The resulting picture (the square with painted cells) will be a fractal. The figure below shows drawing a fractal (here boy made three steps of the algorithm). One evening Vasya got very tired, so he didn't paint the fractal, he just took a sheet of paper, painted a $n × m$-cell field. Then Vasya paint some cells black. Now he wonders, how many squares are on the field, such that there is a fractal, which can be obtained as described above, and which is equal to that square. Square is considered equal to some fractal if they consist of the same amount of elementary not divided cells and for each elementary cell of the square corresponding elementary cell of the fractal have the same color.
This problem could be solved using dynamic programming. State $z[x][y][st][mask]$ means if the square with upper left corner $(x, y)$ is fractal with nesting level $st$ and colors $mask$. The value $z[x][y][st][mask]$ is $0$ or $1$. There are $O(N^{2} \cdot Log(N) \cdot 2^{4})$ states in this dynamic programming. The transitions from state to state are rather simple. If $st = 1$ you should fairly check that the square 2*2 with upper left corner $(x, y)$ matches colors of $mask$. If $st > 1$ you should divide the square into four parts and check them separately. If the value in $mask$ in one quarter means black color, you should check that the whole quarter is black. It could be done using partial sums on rectangles using $O(1)$ of time. If the quarter is white, you should check that it is a fractal with nesting level $st - 1$ with the same $mask$. So, there are less than $4$ transitions from every state. To get the answer to the problem you should consider every upper left corner of squares, every mask and every nesting level of fractal and check this square. It is done using your dynamic.
[ "dp", "hashing" ]
2,000
null
228
D
Zigzag
The court wizard Zigzag wants to become a famous mathematician. For that, he needs his own theorem, like the Cauchy theorem, or his sum, like the Minkowski sum. But most of all he wants to have his sequence, like the Fibonacci sequence, and his function, like the Euler's totient function. The Zigag's sequence with the zigzag factor z is an infinite sequence $S_{i}^{z}$ $(i ≥ 1; z ≥ 2)$, that is determined as follows: - $S_{i}^{z} = 2$, when $(i\mathrm{\boldmath~\mod~}2(z-1))=0$; - $S_{i}^{z}=(i\mathrm{~\mod~}2(z-1))$, when $0<(i\mathrm{~\mod~2(z-1))\leq:}$; - $S_{i}^{z}=2z-(i{\mathrm{~~mod~}}2(z-1))$, when $(i\mathrm{\boldmath~\mod~}2(z-1))>z$. Operation $x\ {\mathrm{mod}}\ y$ means taking the remainder from dividing number $x$ by number $y$. For example, the beginning of sequence $S_{i}^{3}$ (zigzag factor 3) looks as follows: 1, 2, 3, 2, 1, 2, 3, 2, 1. Let's assume that we are given an array $a$, consisting of $n$ integers. Let's define element number $i$ $(1 ≤ i ≤ n)$ of the array as $a_{i}$. The Zigzag function is function $Z(l,r,z)=\sum_{i=l}^{r}a_{i}\cdot S_{i-l+1}^{z}$, where $l, r, z$ satisfy the inequalities $1 ≤ l ≤ r ≤ n$, $z ≥ 2$. To become better acquainted with the Zigzag sequence and the Zigzag function, the wizard offers you to implement the following operations on the given array $a$. - The assignment operation. The operation parameters are $(p, v)$. The operation denotes assigning value $v$ to the $p$-th array element. After the operation is applied, the value of the array element $a_{p}$ equals $v$. - The Zigzag operation. The operation parameters are $(l, r, z)$. The operation denotes calculating the Zigzag function $Z(l, r, z)$. Explore the magical powers of zigzags, implement the described operations.
In this problem we will use that sequence $s$ is cyclic because of its structure. Also, it is important that $2 < = z < = 6$. For every $z$ we will write the sequence $s$ and note that its period is $2 * (z-1)$. So, for every $z$ and modulo $0 < = mod < 2 * (z-1)$ we will build separate segment tree or Fenwick tree. You should be careful with memory, it needs $O(Z \cdot (2 \cdot Z) \cdot N)$ of memory. So, if the query is to update some value, we should update $z$ values of trees with correct modules. If the query is to find sum, we should consider every $2 \cdot (z-1)$ modules, count the sum and multiply by correct coefficient from sequence $s$. The complexity is $O(Z \cdot N \cdot Log(N))$.
[ "data structures" ]
2,100
null
228
E
The Road to Berland is Paved With Good Intentions
Berland has $n$ cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not. The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. The valiant crew fulfilled the King's order in a day, then workers went home. Unfortunately, not everything is as great as Valera II would like. The main part of the group were gastarbeiters — illegal immigrants who are enthusiastic but not exactly good at understanding orders in Berlandian. Therefore, having received orders to asphalt the roads coming from some of the city, the group asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it. Upon learning of this progress, Valera II was very upset, but since it was too late to change anything, he asked you to make a program that determines whether you can in some way asphalt Berlandian roads in at most $n$ days. Help the king.
This problem can be solved in different ways. It was expected the solution that solved the system of modular equations using Gauss algorithm. Here is another simple solution. The vertices from the result call switched-on. Firstly, note that every vertex should be switched-on no more than once. Then, consider every edge $(x, y)$ of color $c$. We want to make its color $1$. So, if $c = 1$ we should switch on vertices $x$ and $y$ or don't switch them on simultaneously. If $c = 0$ we should switch on $x$ or $y$. So, consider some vertex $v$ and try to switch it on or not. Thus, we can uniquely determine the state of every vertex of the same connected component as $v$. If we face some collision, we can't get the solution, you should print Impossible. The solution can be realized using bfs with complexity $O(N + M)$.
[ "2-sat", "dfs and similar", "dsu", "graphs" ]
1,900
null
229
A
Shifts
You are given a table consisting of $n$ rows and $m$ columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To \underline{cyclically shift} a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1.
Let's compute the minimum number of operations needed to get all 1s in each of the $m$ columns. For this, traverse each row twice - one time to the left and one time to the right, recording the index of the nearest cell with 1 (in corresponding direction) for each column in this row. Then the number of operations for any particular column is the sum of the computed values over all rows. In turn, the answer to the problem is the minimal value of these sums. The complexity of the solution is $O(nm)$.
[ "brute force", "two pointers" ]
1,500
#include <algorithm> #include <climits> #include <iostream> using namespace std; const int maxn = 100, maxm = 10000; int d[maxn][maxm]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; string s; s.reserve(m); for (int i = 0; i < n; i++) { cin >> s; size_t pos = s.find('1'); if (pos == string::npos) { cout << -1 << ' '; return 0; } int dist = 0; for (int j = 0; j < m; j++) { if (s[(j+pos)%m] == '1') { dist = 0; } else { dist++; } d[i][(j+pos)%m] = dist; } for (int j = m; j > 0; j--) { if (s[(j+pos)%m] == '1') { dist = 0; } else { dist++; } d[i][(j+pos)%m] = min(d[i][(j+pos)%m], dist); } } int res = INT_MAX; for (int i = 0; i < m; i++) { int sum = 0; for (int j = 0; j < n; j++) { sum += d[j][i]; } res = min(res, sum); } cout << res << ' '; }
229
B
Planets
Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet. Overall the galaxy has $n$ planets, indexed with numbers from 1 to $n$. Jack is on the planet with index 1, and Apophis will land on the planet with index $n$. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0. It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time $t$ another traveller arrives to the planet, Jack can only pass through the stargate at time $t + 1$, unless there are more travellers arriving at time $t + 1$ to the same planet. Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index $n$.
Observe that when we visit some planet, the best strategy is to arrive as early as we can and then wait for the nearest free moment of time to move further. Hence this problem can be solved with the Dijkstra's algorithm by slightly altering the definition of a shortest distance. When we process a planet (meaning that we already know the minimum time needed to reach it), we need to check the array of arrival times for this planet and find the first moment of time in which we can leave this planet - this will be the distance that we will be adding to outgoing paths from this planet. It's clear that we will traverse each array of arrival times no more than once. Additionally, one must pay attention to these cases: when a traveller arrives to planet 1 at time 0 (then Jack has to wait) and when a traveller arrives to planet $n$ at the same time as Jack (then Jack needs not to wait). The complexity of the solution - $O((n+m)\log n+\sum_{i=1}^{n}k_{i})$.
[ "binary search", "data structures", "graphs", "shortest paths" ]
1,700
#include <algorithm> #include <climits> #include <iostream> #include <set> #include <utility> #include <vector> using namespace std; const int maxn = 100000, maxm = 100000; vector<pair<int, int> > edges[maxn]; vector<int> times[maxn]; int dist[maxn]; struct compar { bool operator ()(int v1, int v2) const { if (dist[v1] != dist[v2]) { return dist[v1] < dist[v2]; } else { return v1 < v2; } } }; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { int a, b, c; cin >> a >> b >> c; edges[a-1].push_back(make_pair(b-1, c)); edges[b-1].push_back(make_pair(a-1, c)); } for (int i = 0; i < n; i++) { int k; cin >> k; times[i].resize(k); for (int j = 0; j < k; j++) { cin >> times[i][j]; } } fill_n(dist+1, n-1, INT_MAX); set<int, compar> q; for (int i = 0; i < n; i++) { q.insert(i); } while (!q.empty()) { int v = *q.begin(); q.erase(q.begin()); if (v == n-1 || dist[v] == INT_MAX) { break; } vector<int>::const_iterator ti( lower_bound(times[v].begin(), times[v].end(), dist[v])); while (ti != times[v].end() && dist[v] == *ti) { dist[v]++; ++ti; } for (int i = 0; i < (int)edges[v].size(); i++) { const pair<int, int>& p = edges[v][i]; set<int, compar>::iterator qi(q.find(p.first)); if (qi != q.end()) { if (dist[v] + p.second < dist[p.first]) { q.erase(qi); dist[p.first] = dist[v] + p.second; q.insert(p.first); } } } } cout << (dist[n-1] < INT_MAX ? dist[n-1] : -1) << ' '; }
229
C
Triangles
Alice and Bob don't play games anymore. Now they study properties of all sorts of graphs together. Alice invented the following task: she takes a complete undirected graph with $n$ vertices, chooses some $m$ edges and keeps them. Bob gets the ${\frac{n(n-1)}{2}}-m$ remaining edges. Alice and Bob are fond of "triangles" in graphs, that is, cycles of length 3. That's why they wonder: what total number of triangles is there in the two graphs formed by Alice and Bob's edges, correspondingly?
Let's call Alice's edges simply edges, and Bob's edges the antiedges. For each edge pair of the initial complete graph that pass through the same vertices, assign a weight: for each pair of edges the weight +2, for each pair of edge and antiedge -1 and for each pair of antiedges +2. Now calculate the sum of all the weights. Observe that each Alice's or Bob's triangle adds exactly +6 to the sum, and each combination of three vertices that do not form the triangle in any of the two graphs adds exactly 0 to the sum. The sum itself is calculated by iterating over all vertices and adding the total weight of all the edge pairs that pass through this vertex. If the degree of the vertex is $d$, then we should add $\left.+2\cdot{\binom{d}{2}}-1\cdot d(n-1-d)+2\cdot{\binom{n-1-d}{2}}=\right.$ $d(d - 1) - d(n - d - 1) + (n - d - 1)(n - d - 2)$ to the final sum. Since each triangle adds +6 to the sum, then the answer is equal to the sum divided by 6. The complexity of the solution is $O(n + m)$.
[ "combinatorics", "graphs", "math" ]
1,900
#include<cstdio> using namespace std; int n, m, d[1000005]; int main() { scanf("%d %d", &n, &m); for(int i = 0; i < m; i++) { int a, b; scanf("%d %d", &a, &b); d[a]++; d[b]++; } long long res = 0; for(int v = 1; v <= n; v++) { long long a = d[v], b = n-1-a; res += a*(a-1)+b*(b-1)-a*b; } printf("%I64d ", res/6); }
229
D
Towers
The city of D consists of $n$ towers, built consecutively on a straight line. The height of the tower that goes $i$-th (from left to right) in the sequence equals $h_{i}$. The city mayor decided to rebuild the city to make it \underline{beautiful}. In a \underline{beautiful} city all towers are are arranged in non-descending order of their height from left to right. The rebuilding consists of performing several (perhaps zero) operations. An operation constitutes using a crane to take any tower and put it altogether on the top of some other neighboring tower. In other words, we can take the tower that stands $i$-th and put it on the top of either the $(i - 1)$-th tower (if it exists), or the $(i + 1)$-th tower (of it exists). The height of the resulting tower equals the sum of heights of the two towers that were put together. After that the two towers can't be split by any means, but more similar operations can be performed on the resulting tower. Note that after each operation the total number of towers on the straight line decreases by 1. Help the mayor determine the minimum number of operations required to make the city beautiful.
Let's calculate the dynamics d[i][k] - the minimal possible height of the last tower that we can obtain by merging the first $i$ left towers into at least $k$ towers. Assume we already have calculated the dynamics' values for the first $i$ towers. Now we iterate over the all possible tower intervals $[i + 1;j]$; say the sum in the pending interval is equal to $s$. Now we find the greatest $k$ such that d[i][k] is not greater than $s$. Then we update the value of d[j][k+1] to the minimum of $s$ and d[j][k+1]. Notice that when $k$ increases the values d[i][k] do not decrease. Because of that we can iterate over intervals in the decreasing value of $j$, and corresponding $k$ can be found using a single pointer over values of d[i][k]. When we arrive in the position $j$ during the dynamics, some of the d[j][k] values are updated, but some are still not. Using the same observation that along with the increasing of $k$ the values d[j][k] do not decrease as well, we can make a single run over the values of $k$ in the decreasing order and update the dynamics' values as follows: d[j][k] := min(d[j][k], d[j][k+1]). This is done in the beginning of the dynamics' iteration. In the end we can find the greatest $k$ for which there exists an answer among the values of d[n][k]. The answer to the problem then is $n - k$. The complexity of the solution is $O(n^{2})$.
[ "dp", "greedy", "two pointers" ]
2,100
#include<cstdio> #include<cstring> using namespace std; #define MAXN 5005 int dp[MAXN][MAXN], inf = 1000000000; int main() { int n, a[MAXN]; scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%d", &a[i]); } for(int i = 0; i <= n; i++) { for(int j = 0; j <= n; j++) { dp[i][j] = inf; } } dp[0][0] = 0; for(int i = 1; i <= n; i++) { int k = -1, s = 0; for(int j = i; j <= n; j++) { s += a[j]; while(k+1<=n && dp[i-1][k+1] <= s) { k++; } if(k>=0 && dp[j][k+1]>s) { dp[j][k+1]=s; } } for(int k = n-1; k >= 0; k--) { if(dp[i][k]>dp[i][k+1]) { dp[i][k]=dp[i][k+1]; } } } int res = inf; for(int k = 1; k <= n; k++) { if(dp[n][k] < inf) { res = k; } } printf("%d ", n-res); }
229
E
Gifts
Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with $n$ gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for $n$ names of items from the list. If the fish's list has $p$ occurrences of the given name, then the old man can't ask for this name of item more than $p$ times. The old man knows that if he asks for $s$ gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose $s$ gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the $n$ names in such a way that he can get $n$ gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly. The old man wondered, what is the probability that he can get $n$ most expensive gifts. As the old man isn't good at probability theory, he asks you to help him.
First let's establish some facts that we will use in the solution. With how much probability can the fisherman get a particular set of gifts, among which there are $a_{i}$ gifts of $i$-th name? In total there are ${\binom{k_{1}}{a_{1}}}\cdot\ {\binom{k_{2}}{a_{2}}}\cdot\ \cdot\ \cdot\ \cdot\ \cdot\ {\binom{k_{m}}{a_{m}}}$ such sets, since there are exactly $\binom{k_{i}}{a_{i}}$ subsets of gifts with $i$-th name of size $a_{i}$, and two different names are independent during the gold fish's choice. Then the described particular set of gifts we can get with the probability of $\displaystyle{\Bigg(}{\frac{1}{(a_{1})\cdot{\binom{k_{2}}{a_{2}}}}\cdots{\binom{k_{m}}{a_{m}}}}$, by asking $a_{i}$ gifts of $i$-th name. Now we know the probability $p$ of obtaining one particular gift set $A$. Now observe that from $p$ we can calculate the probabiltity $p'$ of obtaining the set $A$ along with some one other gift of $x$-th name in constant time. Say there are already $a_{x}$ elements of $x$-th name in $A$. Using the formula from the first paragraph, we can deduce that: $p^{\prime}\equiv p:\frac{1}{\binom{k_{x}}{a_{x}}}\cdot\frac{1}{\binom{k_{x}}{a_{x}+1}}$ $p^{\prime}=p\cdot{\frac{k_{x}!}{a_{x}!(k_{x}-a_{x})!}}:{\frac{k_{x}!}{(a_{x}+1)!!(k_{x}-a_{x}-1)!}}$ $p^{\prime}=p\cdot{\frac{a_{x+1}}{k_{x}-a_{x}}}$Let's solve the main problem now. We sort all the gifts in descending order of their prices. It is clear that the fisherman will definitely ask the names of all the gifts among the first $n$ ones whose prices are not equal to the price of the $n$-th gift in the list. Let's say that this set of gifts is the base, and it has $b$ elements. Then there is still $n - b$ unchosen gifts, and we know that all of them will have the price equal to the price of the $n$-th gift in the list. Say the price of the $n$-th gift is $d$, and there are exactly $s$ gifts with the price $d$ (keep in mind that each of them has a different name); also call these gifts dubious. We can also deduce that the fisherman can make $\binom{s}{l}$ different decisions, where $l = n - b$. So now we have some $s$ dubious gifts with the price of $d$; let's enumerate them in any order. We calculate the dynamics $f(x, y)$ - the cumulative probability of obtaining $n$ most valuable gifts, if there are $x$ chosen from the first $y$ in the list. It is clear that $f(0, 0) = p$, and $f(l, s)$ contains the answer to the problem. Using the coefficients we have deduced earlier, we get two transitions in the dynamics: $f(x+1,y+1)+=f(x,y)\cdot{\frac{b_{y}+1}{k_{y}-b_{y}}}\cdot{\frac{({\frac{y}{x+1}})}{({\frac{y+1}{x+1}})}}=f(x,y)\cdot{\frac{b_{y}+1}{k_{y}-b_{y}}}\cdot{\frac{x+1}{y+1}}$, if we add $y + 1$-th dubious gift to the set of $x$ chosen among the first $y$ dubious gifts; $f(x,y+1)+=f(x,y)\cdot{\frac{(y^{\circ})}{(y_{\circ}^{+1})}}=f(x,y)\cdot{\frac{y-x+1}{y+1}}$, otherwise, if do not put the $y + 1$-th dubious gift. This dynamics can be computed in $O(t^{2})$ time, where $t$ is the total number of gifts. The complexity of the solution is $O(t\log t+t^{2})=O(t^{2})$.
[ "combinatorics", "dp", "math", "probabilities" ]
2,600
#include<cstdio> #include<vector> #include<algorithm> #include<functional> #include<iostream> #include<iomanip> using namespace std; #define MAXN 1005 int Got[MAXN], Left[MAXN]; long double f[MAXN][MAXN]; int main() { int n, m; scanf("%d %d", &n, &m); vector<pair<int,int> > g; g.reserve(MAXN); for(int i = 0; i < m; i++) { scanf("%d", &Left[i]); for(int j = 0; j < Left[i]; j++) { int c; scanf("%d", &c); g.push_back(make_pair(c,i)); } } int t = g.size(); sort(g.begin(), g.end(), greater<pair<int,int> >()); int d = g[n-1].first, i; long double p = 1; for(i = 0; g[i].first != d; i++) { int name = g[i].second; p *= (Got[name]+1.)/(Left[name]?Left[name]:1); Got[name]++; Left[name]--; } vector<int> id; id.reserve(MAXN); int l = n-i; for(; i<t && g[i].first==d; i++) { id.push_back(g[i].second); } int s = id.size(); long double Q[MAXN]; for(int i = 0; i < s; i++) { Q[i] = (Got[id[i]]+1.)/(Left[id[i]]?Left[id[i]]:1); } f[0][0] = p; for(int y = 0; y < s; y++) { for(int x = 0; x <= y; x++) { f[x+1][y+1] += f[x][y]*Q[y]*(x+1.)/(y+1.); f[x][y+1] += f[x][y]*(y-x+1.)/(y+1.); } } cout << fixed << setprecision(9) << f[l][s] << endl; }
230
A
Dragons
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all $n$ dragons that live on this level. Kirito and the dragons have \underline{strength}, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals $s$. If Kirito starts duelling with the $i$-th ($1 ≤ i ≤ n$) dragon and Kirito's strength is not greater than the dragon's strength $x_{i}$, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by $y_{i}$. Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.
Observe that if Kirito fights a dragon whose strength is less than Kirito's strength, then Kirito does not lose anything - in fact, he even gains a nonnegative strength increase. Taking note of this, let's for each step choose some dragon whose strength is less than Kirito's current strength, and fight it. After performing some amount of these steps we'll eventually end up in one of these two situations: either all dragons are slain (then the answer is "YES"), or only dragons whose strength is not less than Kirito's strength remain (then the answer is "NO"). On each step we can choose a suitable dragon to fight either by searching through all dragons or by sorting the dragons by strength in non-descending order in advance. The complexity of the solution is $O(n^{2})$ or $O(n\log n)$.
[ "greedy", "sortings" ]
1,000
#include <algorithm> #include <iostream> #include <utility> using namespace std; const int maxn = 1000; pair<int, int> arr[maxn]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int s, n; cin >> s >> n; for (int i = 0; i < n; i++) { cin >> arr[i].first >> arr[i].second; } sort(arr, arr + n); for (int i = 0; i < n; i++) { if (s <= arr[i].first) { cout << "NO "; return 0; } else { s += arr[i].second; } } cout << "YES "; }
230
B
T-primes
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer $t$ \underline{Т-prime}, if $t$ has exactly three distinct positive divisors. You are given an array of $n$ positive integers. For each of them determine whether it is Т-prime or not.
It can be shown that only squares of prime numbers are T-primes, and that there are not too many of them - as many as there are prime numbers not greater than ${\sqrt{10^{12}}}=10^{6}$. Precompute these numbers (using, for example, the sieve of Eratosthenes) and store them in an array or an std::set, then we can answer each query by simply checking whether the number in question is amongst the precomputed numbers. The complexity of the solution is linear in relation to $n$ - $O({\sqrt{d}}\log\log{\sqrt{d}}+n\log{\sqrt{d}})$ or $O({\sqrt{d}}\log{\sqrt{d}}+n\log{\sqrt{d}})$, where $d = 10^{12}$ (one can also get a tighter bound).
[ "binary search", "implementation", "math", "number theory" ]
1,300
#include <iostream> #include <set> using namespace std; const int sqrt_lim = 1000001; set<long long> prime_squares() { static bool arr[sqrt_lim]; for (int i = 2; i*i < sqrt_lim; i++) { if (!arr[i]) { for (int j = i*i; j < sqrt_lim; j += i) { arr[j] = true; } } } set<long long> res; for (int i = 2; i < sqrt_lim; i++) { if (!arr[i]) res.insert((long long)i * i); } return res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); set<long long> sq(prime_squares()); int n; cin >> n; for (int i = 0; i < n; i++) { long long x; cin >> x; if (sq.find(x) != sq.end()) { cout << "YES "; } else { cout << "NO "; } } }
231
A
Team
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution. This contest offers $n$ problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.
It is needed just to implement actions described in statement. You had to read data and to calculate number of members of team, which were sure about the solution, for every task. If this number is greater than one, the answer must be increased by one.
[ "brute force", "greedy" ]
800
null
231
B
Magic, Wizardry and Wonders
Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones. This morning he has $n$ cards with integers lined up in front of him. Each integer is not less than 1, but not greater than $l$. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left. Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1. Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than $l$, the numbers on the appearing cards can be anything, no restrictions are imposed on them. It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were $n$ cards, they contained integers from 1 to $l$, and after all magical actions he was left with a single card containing number $d$. Help Vasya to recover the initial set of cards with numbers.
Let's see, what will be the last number of array after $i$ iterations. After the first iteration it will be $a_{n - 1}-a_{n}$ (and total number of elements will be decreased by one). After the second iteration the last number will be $a_{n - 2}-a_{n - 1} + a_{n}$. It is not hard to see, that after $n - 1$ iterations remain $a_{1}-a_{2} + a_{3}-a_{4} + ... + ( - 1)^{n + 1} \cdot a_{n}$. In a such way, our task is to put numbers from $1$ to $l$ in array so, that sum of numbers in odd positions minus sum of numbers in even positions will equal to given $d$. This means sum of numbers in odd positions must be equal $s=d+a_{2}+a_{4}+\cdot\cdot\cdot+a_{n-n}\,\,\,\mathrm{mod}\,2$. But the minimal sum can be $m i n v={\frac{n+1}{2}}$, and the maximal - $m a x v=l\cdot{\frac{n+1}{2}}$. Because of this we should choose $a_{2 \cdot k}$ so, that $s$ fits the boundaries. Constrains allow to do it in a such manner. Firstly, put ones on the even positions. If $s > maxv$ after that, the answer is $- 1$. Otherwise, let's increase each $a_{2 \cdot k}$ by one until $s = minv$. If we put $l$ in all even positions and $s < minv$, than answer is $- 1$ too. After we put numbers on even positions, let's write $1$ in all odd positions, and while sum of this elements is less than $s$ increase each one by fitting value.
[ "constructive algorithms", "greedy" ]
1,500
null
231
C
To Add or Not to Add
A piece of paper contains an array of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Your task is to find a number that occurs the maximum number of times in this array. However, before looking for such number, you are allowed to perform not more than $k$ following operations — choose an arbitrary element from the array and add $1$ to it. In other words, you are allowed to increase some array element by $1$ no more than $k$ times (you are allowed to increase the same element of the array multiple times). Your task is to find the maximum number of occurrences of some number in the array after performing no more than $k$ allowed operations. If there are several such numbers, your task is to find the minimum one.
One of the main observations, needed to solve this problem, is that the second number in answer always coincides with someone $a_{j}$. Let's see why it is true. Suppose, the second number of the answer is $a_{j} + d$ for someone $j$ and $a_{j} + d \neq a_{i}$ for all $i$. This means, we increased some numbers, which is less than $a_{j}$, so that they became equal to $a_{j}$, and then all this numbers and some numbers, which is equal to $a_{j}$, we increased to $a_{j} + d$. But if we didn't increase all this numbers to $a_{j} + d$ and remain they equal to $a_{j}$, we'd perform less operations and the answer would be better. Due to this fact we can solve problem in a such manner. Sort array in non-decreasing order. Iterate over $a_{i}$ and calculate, what is the maximal number of $a_{i}$ we can obtain. For maximizing first number of answer, we must increase some lesser numbers to $a_{i}$ and perform not greater than $k$ operations. It is obvious that firstly we should increase such $a_{j}$ that $a_{i}-a_{j}$ is minimal. So, if we can solve problem in $O(n^{2})$, we would iterate $j$ from $i$ to $0$ and increase $a_{j}$ to $a_{i}$, while we could. But the solution must be faster, and we will use binary search. We will brute the number of numbers, which we must do equal to $a_{i}$. Suppose we fix $cnt$ this value. Now we have to check if we can do $cnt$ numbers equal to $a_{i}$ by not greater than $k$ operations. For doing this, let's calculate $a_{i}\cdot c n t-\sum_{j=i-c n t+1}^{t}a_{j}$. If this value not greater than $k$, we can do it. For calculating sum quickly, we can save prefix sums and than $s_{i - cnt + 1, i} = s_{i}-s_{i-cnt}$. Finally we solved this problem in $O(n \cdot logn)$.
[ "binary search", "sortings", "two pointers" ]
1,600
null
231
D
Magic Box
One day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point $(0, 0, 0)$, and the opposite one is at point $(x_{1}, y_{1}, z_{1})$. The six faces of the box contain some numbers $a_{1}, a_{2}, ..., a_{6}$, exactly one number right in the center of each face. The numbers are located on the box like that: - number $a_{1}$ is written on the face that lies on the ZOX plane; - $a_{2}$ is written on the face, parallel to the plane from the previous point; - $a_{3}$ is written on the face that lies on the XOY plane; - $a_{4}$ is written on the face, parallel to the plane from the previous point; - $a_{5}$ is written on the face that lies on the YOZ plane; - $a_{6}$ is written on the face, parallel to the plane from the previous point. At the moment Vasya is looking at the box from point $(x, y, z)$. Find the sum of numbers that Vasya sees. Note that all faces of the box are not transparent and Vasya can't see the numbers through the box. The picture contains transparent faces just to make it easier to perceive. You can consider that if Vasya is looking from point, lying on the plane of some face, than he can not see the number that is written on this face. It is enough to see the center of a face to see the corresponding number for Vasya. Also note that Vasya always reads correctly the $a_{i}$ numbers that he sees, independently of their rotation, angle and other factors (that is, for example, if Vasya sees some $a_{i} = 6$, then he can't mistake this number for $9$ and so on).
The main subtask of this problem is to check whether we can observe the center of face of parallelepiped from point $p = (x, y, z)$. Let's see the case, when the face belongs to plane $z = z_{1}$. For performing all calculations in integer numbers, multiply all coordinates $x, y, z, x_{1}, y_{1}, z_{1}$ by $2$. Take the point $a=\left({\frac{x_{1}}{2}},{\frac{y_{1}}{2}},z_{1}\right)$ and normal to plane, containing the fixed face, which is directed out of interior of parallelepiped, that is ${\overline{{\vec{v}}}}=(0,0,1)$. Also take vector ${\overline{{\mathcal{W}}}}=p^{-a}$. If undirected angle between this vectors is less than $90$ degrees, we can observe $a$ from $p$. For checking this we can use scalar product. If scalar product of $\overline{{\u}}$ and $\overline{{\psi}}$ is strictly greater than zero, than that angle is fitting.
[ "brute force", "geometry" ]
1,600
null
231
E
Cactus
A connected undirected graph is called a \underline{vertex cactus}, if each vertex of this graph belongs to at most one simple cycle. A simple cycle in a undirected graph is a sequence of distinct vertices $v_{1}, v_{2}, ..., v_{t}$ $(t > 2)$, such that for any $i$ $(1 ≤ i < t)$ exists an edge between vertices $v_{i}$ and $v_{i + 1}$, and also exists an edge between vertices $v_{1}$ and $v_{t}$. A simple path in a undirected graph is a sequence of not necessarily distinct vertices $v_{1}, v_{2}, ..., v_{t}$ $(t > 0)$, such that for any $i$ $(1 ≤ i < t)$ exists an edge between vertices $v_{i}$ and $v_{i + 1}$ and furthermore each \textbf{edge occurs no more than once}. We'll say that a simple path $v_{1}, v_{2}, ..., v_{t}$ starts at vertex $v_{1}$ and ends at vertex $v_{t}$. You've got a graph consisting of $n$ vertices and $m$ edges, that is a vertex cactus. Also, you've got a list of $k$ pairs of interesting vertices $x_{i}, y_{i}$, for which you want to know the following information — the number of distinct simple paths that start at vertex $x_{i}$ and end at vertex $y_{i}$. We will consider two simple paths distinct if the sets of edges of the paths are distinct. For each pair of interesting vertices count the number of distinct simple paths between them. As this number can be rather large, you should calculate it modulo $1000000007$ ($10^{9} + 7$).
In this problem you should find the number of simple paths between some pair of vertices in vertex cactus. If you learn the structure of these graphs, it is not hard to see, that if we'll squeeze each cycle in one vertex, we get a tree. So let's squeeze all cycles in source graph and get this tree. Also every vertex of this tree we'll mark, if it is squeezed cycle (let's call this vertices 1-vertices) or single vertex in source graph (this vertices we'll call 0-vertices). Then, we'll do the following to find the number of paths between vertices $a$ and $b$ in source graph. Suppose $c$ is a vertex, corresponding to $a$ in obtained tree (it can be a single vertex or a vertex, corresponding to a squeezed cycle with $a$), and $d$ is a vertex, corresponding to $b$. Let's denote $deg$ is the number of 1-vertices in path from $c$ to $d$ in tree. Than it is easy to understand, that the answer for query is $2^{d e g}\;\;\mathrm{mod}\;10^{9}+7$, because every cycle (1-vertex) increase the number of possible ways twice (you can go from one vertex to other by two ways in cycle). It means that we need to count the number of 1-vertex on the path from one vertex to other in tree quickly to answer a query. We can do it in a following way. Hang our tree for one vertex, which we'll call a root. Denote for every vertex $cnt_{v}$ is the number of 1-vertex on the way to the root (including root and vertex itself). Suppose we want to find the number of 1-vertex on the path from $a$ to $b$. Denote $c$ is the least common ancestor of vertices $a$ and $b$. Than number of 1-vertex on the way from $a$ to $b$ is equal to $cnt_{a} + cnt_{b}-2 \cdot cnt_{c}$, if $c$ is 0-vertex and $cnt_{a} + cnt_{b}-2 \cdot cnt_{c} + 1$, if $c$ is 1-vertex. The least common ancestor can be found by standard method - binary method recovery. Finally we have $O(m + k \cdot logn)$ solution.
[ "data structures", "dfs and similar", "dp", "graphs", "trees" ]
2,100
null
232
A
Cycles
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly $k$ cycles of length $3$. A cycle of length $3$ is an unordered group of three distinct graph vertices $a$, $b$ and $c$, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed $100$, or else John will have problems painting it.
Let's add edge in order of increasing $a$ and for equal $b$ in order of increasing $b$ (here $a$ and $b$ - the least and the greatest vertices of the edge). If the new edge adds too much 3-cycles, we won't add it. We can count the number of new 3-cycles in $O(n)$ complexity (they all contain the new edge, so it's enough to check all variants of the third vertex). Obviously we will obtain some proper graph, because we can always add a vertex and two edges to make a new triangle. So, there is always an answer. The complexity of this solution is $O(n^{3})$. Let's proof that 100 vertices are always enough for the given restrictions on $n$. For some $p$ after first $p$ iterations we will have a complete graph of $p$ vertices. Now we have exactly $C(p, 3)$ triangles. Consider $p$ such that $C(p, 3) \le k$ and $C(p, 3)$ is maximal. For the given restrictions $p \le 85$. From this moment, if we add $u$ from some vertex, we increase the total number of 3-cycles on $C(u, 2)$. So we have to present a small number that is less than $C(85, 3)$ as sum of $C(i, 2)$. The first number we subtruct will differ $C(85, 1)$ on some value not greater than $C(85, 1) = 85$, because $C(n, k) - C(n - 1, k) = C(n - 1, k - 1)$. The second number we subtruct will differ the number we have on some value not greater than $C(14, 1) = 14$. and so on. For every $k$ it's enough to use not more that $90$ vertices.
[ "binary search", "constructive algorithms", "graphs", "greedy" ]
1,600
null
232
B
Table
John Doe has an $n × m$ table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size $n × n$ have exactly $k$ points. John Doe wondered, how many distinct ways to fill the table with points are there, provided that the condition must hold. As this number can be rather large, John Doe asks to find its remainder after dividing by $1000000007$ $(10^{9} + 7)$. You should assume that John always paints a point exactly in the center of some cell. Two ways to fill a table are considered distinct, if there exists a table cell, that has a point in one way and doesn't have it in the other.
Let $s_{i}$ number of points in the column $i$. Two neighboring squares are drawn at this picture, $A$ is the number of point it the left area (it is one column), $B$ is the number of points in the middle area and $C$ is the number of points in the right area (it is one column too). That's why by definition we have: $\left\{\begin{array}{l l}{A+B}&{=}&{k}\\ {B+C}&{=}&{k.}\end{array}\right.$ Therefore $A = C$. That's why $\forall s_{i}=s_{i+n},(i\leq m-n)$ Divide all columns by equivalence classes on the basis of $i\mathrm{~mod~}n$. For all $a$ and $b$ from one class $s_{a} = s_{b}$. $cnt_{a}$ is number of columns in class with $i\mod n=a$. There are $(C_{n}^{k})^{cnta}$ ways to draw $k$ points in the each of columns in the class $a$ independendently of the other classes. $dp[i][j]$ is number of ways to fill all columns in classes $1, ... i$ in such way that $\textstyle\sum_{k=0}^{k\leq i}s_{k}=j$. $d p[i][j]=\sum_{k=0}^{k\leq n}d p[i-1][j-k]\cdot(C_{n}^{k})^{c n t}$ $cnt_{i}$ take only two values $\textstyle\left|{\frac{m}{n}}\right\rangle$ and $\lfloor{\frac{m}{n}}\rfloor+1$. Let's calc $(C_{n}^{a})^{cnti}$ for all $a$ and $cnt_{i}$ and use it to calc our dp. We have $O(n^{2} \cdot k)$ complexity.
[ "bitmasks", "combinatorics", "dp", "math" ]
1,900
null
232
C
Doe Graphs
John Doe decided that some mathematical object must be named after him. So he invented the Doe graphs. The Doe graphs are a family of undirected graphs, each of them is characterized by a single non-negative number — its order. We'll denote a graph of order $k$ as $D(k)$, and we'll denote the number of vertices in the graph $D(k)$ as $|D(k)|$. Then let's define the Doe graphs as follows: - $D(0)$ consists of a single vertex, that has number $1$. - $D(1)$ consists of two vertices with numbers $1$ and $2$, connected by an edge. - $D(n)$ for $n ≥ 2$ is obtained from graphs $D(n - 1)$ and $D(n - 2)$. $D(n - 1)$ and $D(n - 2)$ are joined in one graph, at that numbers of all vertices of graph $D(n - 2)$ increase by $|D(n - 1)|$ (for example, vertex number $1$ of graph $D(n - 2)$ becomes vertex number $1 + |D(n - 1)|$). After that two edges are added to the graph: the first one goes between vertices with numbers $|D(n - 1)|$ and $|D(n - 1)| + 1$, the second one goes between vertices with numbers $|D(n - 1)| + 1$ and $1$. Note that the definition of graph $D(n)$ implies, that $D(n)$ is a connected graph, its vertices are numbered from $1$ to $|D(n)|$. \begin{center} {\scriptsize The picture shows the Doe graphs of order 1, 2, 3 and 4, from left to right.} \end{center} John thinks that Doe graphs are that great because for them exists a polynomial algorithm for the search of Hamiltonian path. However, your task is to answer queries of finding the shortest-length path between the vertices $a_{i}$ and $b_{i}$ in the graph $D(n)$. A path between a pair of vertices $u$ and $v$ in the graph is a sequence of vertices $x_{1}$, $x_{2}$, $...$, $x_{k}$ $(k > 1)$ such, that $x_{1} = u$, $x_{k} = v$, and for any $i$ $(i < k)$ vertices $x_{i}$ and $x_{i + 1}$ are connected by a graph edge. The length of path $x_{1}$, $x_{2}$, $...$, $x_{k}$ is number $(k - 1)$.
Let's reduce the problem to the same problem for graphs with less orders. Vertex $|D(n - 1)| + 1$ is cutpoint (except cases $n \le 2$ but equations below is true for these cases). Without loss of generality $a < b$. Let $dist(a, b, n)$ - length of the shortest path in graph of order $n$. The first case is $a \le |D(n - 1)|$ and $|D(n - 1)| + 1 \le b$ $dist(a, b, n) = min(dist(a, |D(n - 1)|, n - 1), dist(a, 1, n - 1)) + dist(b - |D(n - 1)|, 1, n - 2) + 1$ Edges is marked in red, paths is marked in blue. This formula means that we can go from the vertex $a$ by the path $1$ to the vertex $1$. Then we can go to the $|D(n - 1)| + 1$ by the edge and go to the vertex $b$ by the path $3$. Or we can go to the vertex $|D(n - 1)|$ by the path $2$ and then go to the vertex $|D(n - 1)| + 1$ by the path $2$ and then go to the vertex $b$ by the path $3$. The second case is $|D(n - 1)| + 1 \le a, b$. $dist(a, b, n) = dist(a - |D(n - 1)|, b - |D(n - 1)|, n - 2)$That's easy case. The third case is $a, b \le |D(n - 1)|$ $dist(a, b, n) = min(dist(a, b, n - 1), min(dist(1, a, n - 1), dist(|D(n - 1)|, a, n - 1)) + min(dist(1, b, n - 1), dist(|D(n - 1)|, b, n - 1) + 2)$ If shortest path contains cutpoint ($|D(n - 1)| + 1$) we can go to the vertex $1$ or $|D(n - 1)$+1$ form the both of $a$ and $b$. After that we can go to the cutpoint. Else we should consider path from $a$ to $b$ in $D(n - 1)$. Let's notice that for all of $n$ will be no more than $4$ distinct runnings of $dist(i, j, n)$. It can be prooved by the considering many cases of our actions. In authors colution we cashed all $dist(1, i, n)$ and $dist(i, |D(n)|, n)$ for all achieveable $i$ and $n$. We have complexity $\log m a x(a_{i},b_{i})$ for one query. (it's log because $|D(n)|$ grows like $ \phi ^{n}$).
[ "constructive algorithms", "divide and conquer", "dp", "graphs", "shortest paths" ]
2,600
null
232
D
Fence
John Doe has a crooked fence, consisting of $n$ rectangular planks, lined up from the left to the right: the plank that goes $i$-th $(1 ≤ i ≤ n)$ (from left to right) has width 1 and height $h_{i}$. We will assume that the plank that goes $i$-th $(1 ≤ i ≤ n)$ (from left to right) has index $i$. A piece of the fence from $l$ to $r$ $(1 ≤ l ≤ r ≤ n)$ is a sequence of planks of wood with indices from $l$ to $r$ inclusive, that is, planks with indices $l, l + 1, ..., r$. The width of the piece of the fence from $l$ to $r$ is value $r - l + 1$. Two pieces of the fence from $l_{1}$ to $r_{1}$ and from $l_{2}$ to $r_{2}$ are called matching, if the following conditions hold: - the pieces do not intersect, that is, there isn't a single plank, such that it occurs in both pieces of the fence; - the pieces are of the same width; - for all $i$ $(0 ≤ i ≤ r_{1} - l_{1})$ the following condition holds: $h_{l1 + i} + h_{l2 + i} = h_{l1} + h_{l2}$. John chose a few pieces of the fence and now wants to know how many distinct matching pieces are for each of them. Two pieces of the fence are distinct if there is a plank, which belongs to one of them and does not belong to the other one.
Let $d$ and $d'$ be arrays such that $d_{i} = h_{i} - h_{i + 1}, d'_{i} = - d_{i}$ for every $1 \le i \le (n - 1)$. With that notation the conditions of matching look somehow like these: the pieces do not intersect, that is, there isn't a single plank, such that it occurs in both pieces of the fence; the pieces are of the same width; for all i $i$ $(0 \le i \le r_{1} - l_{1} - 1)$ the following condition holds: $d_{l1 + i} = d'_{l2 + i}$ (that is true in case when $l = r$). The main idea of our solution is stated in the next sentence. For each query $l...r$ the answer is number of pairs $(a, b)$ such that ($a > r$ or $b < l$), $1 \le a \le b \le n - 1$, $b - a = r - l$ and $d_{l...r - 1}$ exactly matches $d'_{a...b - 1}$. Let's build a suffix array $sa$ from the concatenation of arrays $d$ and $d'$ with a fictive number between them for separation. Let position of suffix $i$ in $sa$ be $pos_{i}$. For each query all pieces of the fence that satisfy both second and third conditions of matching will be placed in $sa$ on some segment $bound_{left}...bound_{right}$ such that $bound_{left} \le pos_{l} \le bound_{right}$ and $lcp(bound_{left}...bound_{right}) \ge (r - l)$. So, it's possible to use binary search to find $bound$'s. Depending on complexity of $lcp$ finding algorithm, we could get them in $O(logn)$ or $O(log^{2}n)$ complexity. But there is still a problem to count the number of suffixes from $sa_{boundleft...boundright}$ that satisfy the first condition too. Actually it is equal to count the number of $i$ ($bound_{left} \le i \le bound_{right}$) such that ($n + 1 \le sa_{i} \le n + l - (r - l) - 1$ or $sa_{i} \ge n + r$) (in the concatenation $d'$ starts from $n + 1$). It is a classic problem to count numbers from the given interval in the given subarray. For each query it could be solved in $O(logn)$ complexity. For instance, we could solve it offline using sweep line method and any data structure that support queries of sum on an interval and increment of an element. Or we could use some 2D/persistent structure. So, the summary of the algorithm looks like this: build $d$ and $d'$. Build a suffix array on their concatenation. For each query: find the interval ($bound_{left}...bound_{right}$) with two consecutive binary searches using lcp function. query the count of suffixes from that interval that do not intersect with the given piece of the fence. The best author's solution complexity is $O(nlogn + qlogn)$, but careful written solutions in $O(nlog^{2}n)$ comply with the lime limit too.
[ "binary search", "data structures", "string suffix structures" ]
2,900
null
232
E
Quick Tortoise
John Doe has a field, which is a rectangular table of size $n × m$. We assume that the field rows are numbered from 1 to $n$ from top to bottom, and the field columns are numbered from 1 to $m$ from left to right. Then the cell of the field at the intersection of the $x$-th row and the $y$-th column has coordinates ($x$; $y$). We know that some cells of John's field are painted white, and some are painted black. Also, John has a tortoise, which can move along the white cells of the field. The tortoise can get from a white cell with coordinates ($x$; $y$) into cell ($x + 1$; $y$) or ($x$; $y + 1$), if the corresponding cell is painted white. In other words, the turtle can move only along the white cells of the field to the right or down. The turtle can not go out of the bounds of the field. In addition, John has $q$ queries, each of them is characterized by four numbers $x_{1}, y_{1}, x_{2}, y_{2}$ ($x_{1} ≤ x_{2}$, $y_{1} ≤ y_{2}$). For each query John wants to know whether the tortoise can start from the point with coordinates ($x_{1}$; $y_{1}$), and reach the point with coordinates ($x_{2}$; $y_{2}$), moving only along the white squares of the field.
Let's choose central column of the area and for all cells to the left from column calc masks of achieveable cells in the central column and for all cells to the right from column calc masks of cells of which this is achievable. It's easy dp with bitsets. $d p[i][j]=d p[i-1][j]\vee d p[i][j-1]$ for the right part of board. $d p[i][j]=d p[i+1][j]\vee d p[i][j+1]$ ($\boldsymbol{\mathit{V}}$ - logical or, here it's bitwise or for masks) for the left part. dp calcs mask of achieveable points in the central column. For query $x_{1}$, $y_{1}$, $x_{2}$, $y_{2}$ (if $y_{1} \le mid \le y_{2}$, where $mid$ is chosen central column) answer is yes if $d p[x_{1}][y_{1}]\wedge d p[x_{2}][y_{2}]$ ($\Lambda$ is bitwise and) is not empty. Run this algo for left and right part of board we will get answers for all queries. Complexity is ${\frac{q n}{32}}+q\log n+{\frac{n^{3}\log n}{32}}$.
[ "bitmasks", "divide and conquer", "dp" ]
3,000
null
233
A
Perfect Permutation
A permutation is a sequence of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. Let's denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size of permutation $p_{1}, p_{2}, ..., p_{n}$. Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation $p$ that for any $i$ $(1 ≤ i ≤ n)$ ($n$ is the permutation size) the following equations hold $p_{pi} = i$ and $p_{i} ≠ i$. Nickolas asks you to print any perfect permutation of size $n$ for the given $n$.
Consider permutation $p$ such that $p_{i} = i$. Actually $p$ is a sequence of numbers from $1$ to $n$. Obviously $p_{pi} = i$. Now the only trick is to change the permutation to satisfy the second equation: $p_{i} \neq i$. Let's swap every two consequtive elements. More formally, for each $k: 2k \le n$ let's swap $p_{2k - 1}$ and $p_{2k}$. It's easy to see that the obtained permutation satisfies both equations for every $n$ with the only exception: when $n$ is odd, there is no answer and we should print $- 1$.
[ "implementation", "math" ]
800
null
233
B
Non-square Equation
Let's consider equation: \[ x^{2} + s(x)·x - n = 0, \] where $x, n$ are positive integers, $s(x)$ is the function, equal to the sum of digits of number $x$ in the decimal number system. You are given an integer $n$, find the smallest positive integer root of equation $x$, or else determine that there are no such roots.
Firstly let's find the interval of possible values of $s(x)$. Hence $x^{2} \le n$ and $n \le 10^{18}$, $x \le 10^{9}$. In other words, for every considerable solution $x$ the decimal length of $x$ does not extend $10$ digits. So $s_{max} \le s(9999999999) = 10 \cdot 9 = 90$. Let's bruteforce the value of $s(x)$ ($0 \le s(x) \le 90$). Now we have an ordinary square equation. The deal is to solve it and to check that the current bruteforced value of $s(x)$ is equal to sum of digits of the solution. If the solution exists and the equality holds, we should relax the answer. It seems that the most error-generating part of this problem is solving the equation. Knowing arrays is not neccessary to solve these two problems.
[ "binary search", "brute force", "math" ]
1,400
null
235
A
LCM Challenge
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than $n$. Can you help me to find the maximum possible least common multiple of these three integers?
It is a simple problem, but many competitors used some wrong guesses and failed. First of all, we should check if n is at most 3 and then we can simply output 1,2,6. Now there are two cases: When n is odd, the answer is obviously n(n-1)(n-2). When n is even, we can still get at least (n-1)(n-2)(n-3), so these three numbers in the optimal answer would not be very small compared to n. So we can just iterate every 3 number triple in [n-50,n] and update the answer.
[ "number theory" ]
1,600
null
235
B
Let's Play Osu!
You're playing a game called Osu! Here's a simplified version of it. There are $n$ clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of $n$ characters "O" and "X". Using the play sequence you can calculate the score for the play as follows: for every maximal consecutive "O"s block, add the square of its length (the number of characters "O") to the score. For example, if your play can be encoded as "OOXOOOXXOO", then there's three maximal consecutive "O"s block "OO", "OOO", "OO", so your score will be $2^{2} + 3^{2} + 2^{2} = 17$. If there are no correct clicks in a play then the score for the play equals to $0$. You know that the probability to click the $i$-th $(1 ≤ i ≤ n)$ click correctly is $p_{i}$. In other words, the $i$-th character in the play sequence has $p_{i}$ probability to be "O", $1 - p_{i}$ to be "X". You task is to calculate the expected score for your play.
Let us take a deep look at how this score is calculated. For an $n$ long 'O' block, it contributes $n^{2}$ to the answer. Let us reformat this problem a bit and consider the following alternative definition of the score: (1) For each two 'O' pair which there is no 'X' between them, they add 2 to the score. (2) For each 'O', it adds 1 to the score. We claim that this new definition of the score is equivalent to the definition in the problem statement. Proof of the claim: For an $n$ long 'O' block, there are $C_{n}^{2}$ pairs of 'O' in it and $n$ 'O' in it. Note that $2C_{n}^{2} + n = n^{2}$. So now we work with the new definition of the score. For each event(i,j) (which means s[i] and s[j] are 'O', and there is no 'X' between them). If event(i,j) happens, it adds 2 to the score. So we only need to sum up the probabilities of all events and multiply them by 2, and our task becomes how to calculate the sum of probabilities of all the event(i,j). Let P(i,j) be the probability of event(i,j). We can see that P(i,j) can be computed by $\textstyle\prod_{i}^{j}p_{x}$. Then we denote P(j) as the sum of all event(i,j) for i<j. We have dp(0)=0 and dp(j)=(dp(j-1)+$p_{j - 1}$)*$p_{j}$
[ "dp", "math", "probabilities" ]
2,000
null
235
C
Cyclical Quest
Some days ago, WJMZBMR learned how to answer the query "how many times does a string $x$ occur in a string $s$" quickly by preprocessing the string $s$. But now he wants to make it harder. So he wants to ask "how many consecutive substrings of $s$ are cyclical isomorphic to a given string $x$". You are given string $s$ and $n$ strings $x_{i}$, for each string $x_{i}$ find, how many consecutive substrings of $s$ are cyclical isomorphic to $x_{i}$. Two strings are called cyclical isomorphic if one can rotate one string to get the other one. 'Rotate' here means 'to take some consecutive chars (maybe none) from the beginning of a string and put them back at the end of the string in the same order'. For example, string "abcde" can be rotated to string "deabc". We can take characters "abc" from the beginning and put them at the end of "de".
This problem can be solved by many suffix structures. Probably using suffix automaton is the best way to solve it since suffix automaton is simple and clear. Let us build a suffix automaton of the input string S, and consider the query string x. Let us also build a string t as x concatenated with x dropping the last char. One can see that every consecutive sub-string of t with length |x| is a rotation of x. Let us read the string t with suffix automaton we have build, and every time take the first char out and add a new char, add the answer by the number of string equal to this current sub-string of t (which is a rotation of x). And one more thing, we should consider the repetend of x as well
[ "data structures", "string suffix structures", "strings" ]
2,700
/** * Created by IntelliJ IDEA. * User: mac * Date: 12-10-17 * Time: 下午1:30 * To change this template use File | Settings | File Templates. */ import java.io.*; import java.util.*; public class CJava { BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; List<Node> nodes = new ArrayList<Node>(); class Node { Node[] go; Node suf, nxt = null; int val, cnt; Node(Node[] go, Node suf, int val) { this.go = go; this.suf = suf; this.val = val; this.cnt = 0; nodes.add(this); } Node(Node suf, int val) { this(new Node[26], suf, val); } Node() { this(null, 0); } } Node root, last; void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } void extend(int w) { Node p = last; Node np = new Node(); np.val = p.val + 1; np.cnt = 1; while (p != null && p.go[w] == null) { p.go[w] = np; p = p.suf; } if (p == null) { np.suf = root; } else { Node q = p.go[w]; if (p.val + 1 == q.val) np.suf = q; else { Node nq = new Node(q.go.clone(), q.suf, p.val + 1); q.suf = nq; np.suf = nq; while (p != null && p.go[w] == q) { p.go[w] = nq; p = p.suf; } } } last = np; } int repetend(char[] s) { int n = s.length; int[] nxt = new int[n + 1]; nxt[0] = -1; for (int i = 1; i <= n; i++) { int j = nxt[i - 1]; while (j >= 0 && s[j] != s[i - 1]) j = nxt[j]; nxt[i] = j + 1; } int a = n - nxt[n]; if (n % a == 0) return a; return n; } void solve() throws IOException { root = last = new Node(); { char[] s = nextToken().toCharArray(); // char[] s = new char[500000]; // Random rnd = new Random(); // for (int i = 0; i < s.length; i++) { // s[i] = (char)(rnd.nextInt(26) + 'a'); // } int n = s.length; for (char c : s) { extend(c - 'a'); } Node[] first = new Node[n + 1]; for (Node node : nodes) { node.nxt = first[node.val]; first[node.val] = node; } for (int i = n; i >= 0; i--) { for (Node u = first[i]; u != null; u = u.nxt) if (u.suf != null) u.suf.cnt += u.cnt; } } int nQ = nextInt(); for (int i = 0; i < nQ; i++) { char[] buf = nextToken().toCharArray(); int rep = repetend(buf); Node cur = root; int l = 0; int n = buf.length; for (int j = 0; j < n; j++) { int w = buf[j] - 'a'; while (cur != null && cur.go[w] == null) { cur = cur.suf; if (cur != null) l = cur.val; } if (cur != null && cur.go[w] != null) { cur = cur.go[w]; ++l; } else { cur = root; l = 0; } } int ans = 0; if (l == n) ans += cur.cnt; for (int j = 1; j < rep; j++) { if (l == n) { --l; if (l <= cur.suf.val) cur = cur.suf; } //add last int w = buf[j - 1] - 'a'; while (cur != null && cur.go[w] == null) { cur = cur.suf; if (cur != null) l = cur.val; } if (cur != null && cur.go[w] != null) { cur = cur.go[w]; ++l; } else { cur = root; l = 0; } if (l == n) ans += cur.cnt; } writer.println(ans); } } static public void main(String[] args) { new CJava().run(); } }
235
D
Graph Game
In computer science, there is a method called "Divide And Conquer By Node" to solve some hard problems about paths on a tree. Let's desribe how this method works by function: $solve(t)$ ($t$ is a tree): - Chose a node $x$ (it's common to chose weight-center) in tree $t$. Let's call this step "Line A". - Deal with all paths that pass $x$. - Then delete $x$ from tree $t$. - After that $t$ becomes some subtrees. - Apply $solve$ on each subtree. This ends when $t$ has only one node because after deleting it, there's nothing. Now, WJMZBMR has mistakenly believed that it's ok to chose any node in "Line A". So he'll chose a node at random. To make the situation worse, he thinks a "tree" should have the same number of edges and nodes! So this procedure becomes like that. Let's define the variable $totalCost$. Initially the value of $totalCost$ equal to $0$. So, $solve(t)$ (now $t$ is a graph): - $totalCost = totalCost + (size of t)$. The operation "=" means assignment. $(Size of t)$ means the number of nodes in $t$. - Choose a node $x$ in graph $t$ at random (uniformly among all nodes of $t$). - Then delete $x$ from graph $t$. - After that $t$ becomes some connected components. - Apply $solve$ on each component. He'll apply $solve$ on a connected graph with $n$ nodes and $n$ edges. He thinks it will work quickly, but it's very slow. So he wants to know the expectation of $totalCost$ of this procedure. Can you help him?
First of all, let us consider the simpler case of trees. Let us use Event(A,B) to denote the following event "when we select A as the deleting point, B is connected to A". Clearly, if Event(A,B) happens, it would add 1 to $totolCost$. So we can just simply calculate the probability of every Event(A,B), and add them up. Let us consider how to calculate the probability of Event(A,B). Assume there are n vertices in the path between A and B, we claim that the probability is simply $1 / n$. Let us try to prove it using induction. First let us assume there's a connected sub-graph of the tree containing both A and B, if the sub-graph only has n vertices, then the event happens only if we select vertex A, so the probability is $1 / n$. Otherwise, assume it has x vertices there is two cases: whether the selected vertex is on the path between A and B or not. In the first case, the probability of Event(A,B) happen is $1 / x$ because if we don't select A, Event(A,B) will never happen. In the second case, the sub-graph containing A,B has become smaller, so the probability is $(x - n) / xn$. So add them up we can prove this statement. Then we can solve the tree case by simply add up the inverse of every path's length in the tree. And for the original case, there's at most 2 paths between A and B. If there's only one path, then everything is the same with the tree case. Otherwise, the path between A and B should pass the cycle in the graph. Let us examine this case, you can see that there 2 types of vertex: Vertex on the path of A to cycle or B to cycle, they should not be selected before A because once they're selected, A and B lost connectivity, let us call them X. Vertex on the cycle, the two paths from A to B, each path contains a path in the cycle, let us call them Y and Z. So there are two possibilities: X and Y are free when A is selected, X and Z are free when A is selected. And we should subtract the case that X and Y, Z are all free when A is selected because it double-counts before. So the probability is $1 / (X + Y + 1) + 1 / (X + Z + 1) - 1 / (X + Y + Z + 1)$.
[ "graphs" ]
3,000
import java.util.List; import java.io.InputStreamReader; import java.io.IOException; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { class Vertex { List<Vertex> adj = new ArrayList<Vertex>(); int stackDepth = -1; int cyclePos = -1; Vertex parent = null; int subtreeSize; int[] depthProfile; public boolean findCycle(int depth) { if (depth != stack.size()) throw new RuntimeException(); if (stackDepth >= 0) { if (stackDepth == depth - 2) return false; for (int i = stackDepth; i < depth; ++i) cycle.add(stack.get(i)); return true; } stackDepth = depth; stack.add(this); for (Vertex v : adj) if (v.findCycle(depth + 1)) return true; stack.remove(stack.size() - 1); stackDepth = -2; return false; } public void buildTree() { subtreeSize = 1; for (Vertex v : adj) if (v != parent && v.cyclePos < 0) { v.parent = this; v.buildTree(); subtreeSize += v.subtreeSize; } } public double buildOneTreeAnswers() { double res = 0; int maxDepth = 0; for (Vertex v : adj) { if (v != parent && v.cyclePos < 0) { res += v.buildOneTreeAnswers(); maxDepth = Math.max(maxDepth, v.depthProfile.length); } } depthProfile = new int[maxDepth + 1]; ++depthProfile[0]; for (Vertex v : adj) { if (v != parent && v.cyclePos < 0) { for (int oldDepth = 1; oldDepth <= v.depthProfile.length; ++oldDepth) for (int newDepth = 0; newDepth <= maxDepth; ++newDepth) { res += simpleProb(oldDepth + newDepth) * depthProfile[newDepth] * v.depthProfile[oldDepth - 1]; } for (int oldDepth = 1; oldDepth <= v.depthProfile.length; ++oldDepth) depthProfile[oldDepth] += v.depthProfile[oldDepth - 1]; v.depthProfile = null; } } return res; } } private double simpleProb(int dist) { if (dist == 0) throw new RuntimeException(); return 2.0 / (dist + 1); } List<Vertex> stack = new ArrayList<Vertex>(); List<Vertex> cycle = new ArrayList<Vertex>(); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); Vertex[] v = new Vertex[n]; for (int i = 0; i < n; ++i) { v[i] = new Vertex(); } for (int i = 0; i < n; ++i) { Vertex a = v[in.nextInt()]; Vertex b = v[in.nextInt()]; a.adj.add(b); b.adj.add(a); } v[0].findCycle(0); for (int i = 0; i < cycle.size(); ++i) { cycle.get(i).cyclePos = i; } for (Vertex vv : cycle) vv.buildTree(); double res = n; for (Vertex vv : cycle) res += vv.buildOneTreeAnswers(); for (int i = 0; i < cycle.size(); ++i) { for (int j = i + 1; j < cycle.size(); ++j) { int[] dpi = cycle.get(i).depthProfile; int[] dpj = cycle.get(j).depthProfile; for (int di = 0; di < dpi.length; ++di) for (int dj = 0; dj < dpj.length; ++dj) res += complexProb(j - i, cycle.size() - (j - i), di, dj) * dpi[di] * dpj[dj]; } } out.println(res); } private double complexProb(int cycleA, int cycleB, int tree1, int tree2) { return 2.0 / (cycleA + tree1 + tree2 + 1) + 2.0 / (cycleB + tree1 + tree2 + 1) - 2.0 / (cycleA + cycleB + tree1 + tree2); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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()); } }
235
E
Number Challenge
Let's denote $d(n)$ as the number of divisors of a positive integer $n$. You are given three integers $a$, $b$ and $c$. Your task is to calculate the following sum: \[ \textstyle\sum_{i=1}^{a}\sum_{j=1}^{b}\sum_{k=1}^{c}d(i\cdot j\cdot k). \] Find the sum modulo $1073741824$ $(2^{30})$.
Let us consider each prime in one step, the upper limit for $a, b, c$ is recorded. So if we fixed the power of 2 in each $i, j, k$ like $2^{x}, 2^{y}, 2^{z}$, then their upper limit becomes $a / 2^{x}, b / 2^{y}, c / 2^{z}$, and the power of 2 in their multiplication is just x+y+z. Let us denote $dp(a, b, c, p)$ for the answer to the original problem that $i, j, k$ 's upper limit is $a, b, c$. And their can only use the prime factors which are not less than $p$. Let the next prime to be $q$, so we can try to fix the power of $p$ in $i, j, k$ and get the new upper limit. So we can do transform like this: $dp(a, b, c, p)$ = sum of $dp(a / p^{x}, b / p^{y}, c / p^{z}, q) \cdot (x + y + z + 1)$
[ "combinatorics", "dp", "implementation", "math", "number theory" ]
2,600
/** * Created by IntelliJ IDEA. * User: mac * Date: 12-10-9 * Time: 下午12:41 * To change this template use File | Settings | File Templates. */ import java.io.*; import java.util.*; public class EJava { BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } class Converter { int n, sq; int[] lst; public Converter(int n) { this.n = n; sq = 1; while (sq * sq <= n) ++sq; lst = new int[sq * 2 + 1]; for (int i = 1; i <= sq * 2; i++) { lst[i] = i <= sq ? i : n / (i - sq); } } int encode(int x) { return x <= sq ? x : n / x + sq; } int decode(int x) { return lst[x]; } int size() { return sq * 2; } } int calcTwo(int a, int b, int[] cnt) { if (a > b) { int tmp = a; a = b; b = tmp; } return cnt[a] * cnt[b] * 4 - cnt[a] * 4 + cnt[a] * 3; } void solve() throws IOException { int a = nextInt(), b = nextInt(), c = nextInt(); Converter A = new Converter(a), B = new Converter(b), C = new Converter(c); int n = Math.max(a, Math.max(b, c)); int[] cnt = new int[n + 1]; boolean[] is = new boolean[n + 1]; Arrays.fill(is, true); ArrayList<Integer> smallPrimes = new ArrayList<Integer>(); for (int i = 2; i <= n; i++) { if (is[i]) { if (i * i <= n) { smallPrimes.add(i); } else { cnt[i]++; } for (int j = i + i; j <= n; j += i) { is[j] = false; } } } for (int i = 1; i <= n; i++) { cnt[i] += cnt[i - 1]; } int[][][] am = new int[A.size() + 1][B.size() + 1][C.size() + 1]; int[][][] nam = new int[A.size() + 1][B.size() + 1][C.size() + 1]; am[A.encode(a)][B.encode(b)][C.encode(c)] += 1; for (int p : smallPrimes) { for (int[][] x : nam) { for (int[] y : x) { Arrays.fill(y, 0); } } for (int i = 1; i <= A.size(); i++) { for (int j = 1; j <= B.size(); j++) { for (int k = 1; k <= C.size(); k++) { int d = am[i][j][k]; if (d == 0) continue; int I = A.decode(i), J = B.decode(j), K = C.decode(k); for (int pi = 1, ci = 0; pi <= I; pi *= p, ++ci) { int x = A.encode(I / pi); for (int pj = 1, cj = 0; pj <= J; pj *= p, ++cj) { int y = B.encode(J / pj); for (int pk = 1, ck = 0; pk <= K; pk *= p, ++ck) { int z = C.encode(K / pk); nam[x][y][z] += d * (ci + cj + ck + 1); } } } } } } int[][][] tmp = am; am = nam; nam = tmp; } int ans = 0; for (int i = 1; i <= A.size(); ++i) { for (int j = 1; j <= B.size(); ++j) { for (int k = 1; k <= C.size(); ++k) { int d = am[i][j][k]; if (d == 0) continue; int I = A.decode(i), J = B.decode(j), K = C.decode(k); int t[] = {I, J, K}; Arrays.sort(t); I = t[0]; J = t[1]; K = t[2]; //there int cur = cnt[I] * cnt[J] * cnt[K] * 8; //abc->8 cur += -cnt[I] * cnt[K] * 2; //aab->3*2->6 cur += -cnt[I] * cnt[J] * 2; cur += -cnt[J] * cnt[I] * 2; cur += cnt[I] * 2; //aaa->4 //two cur += calcTwo(I, J, cnt) + calcTwo(J, K, cnt) + calcTwo(I, K, cnt); //one cur += (cnt[I] + cnt[J] + cnt[K]) * 2; //zero cur += 1; ans += cur * d; } } } ans %= 1 << 30; if (ans < 0) ans += 1 << 30; System.out.println(ans); } static public void main(String[] args) { new EJava().run(); } }
236
A
Boy or Girl
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names. This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.
It is a very simple problem, just count how many distinct chars in the input and output the correct answer.
[ "brute force", "implementation", "strings" ]
800
null
236
B
Easy Number Challenge
Let's denote $d(n)$ as the number of divisors of a positive integer $n$. You are given three integers $a$, $b$ and $c$. Your task is to calculate the following sum: \[ \textstyle\sum_{i=1}^{a}\sum_{j=1}^{b}\sum_{k=1}^{c}d(i\cdot j\cdot k). \] Find the sum modulo $1073741824$ $(2^{30})$.
First of all, we can make a table of size a*b*c to store every number's d value. Then we can just brute force through every tripe to calculate the answer.
[ "implementation", "number theory" ]
1,300
null
238
A
Not Wool Sequences
A sequence of non-negative integers $a_{1}, a_{2}, ..., a_{n}$ of length $n$ is called a wool sequence if and only if there exists two integers $l$ and $r$ $(1 ≤ l ≤ r ≤ n)$ such that $a_{l}\ \oplus\ a_{l+1}\ \oplus\ \cdots\ \leftrightarrow a_{r}=0$. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0. The expression $x\oplus y$ means applying the operation of a bitwise xor to numbers $x$ and $y$. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as "^", in Pascal — as "xor". In this problem you are asked to compute the number of sequences made of $n$ integers from 0 to $2^{m} - 1$ that are not a wool sequence. You should print this number modulo $1000000009$ $(10^{9} + 9)$.
Let $a_{1}, ..., a_{n}$ be a not-wool-sequence. We define another sequence called $b$ in which $b_{i}$ is xor of the first $i$ elements of $a$, $b_{i}=a_{i}\oplus b_{i-1}$ and $b_{0} = 0$. Now xor of elements of a consecutive subsequence like $a_{i}, ..., a_{j}$ will be equal to $b_{j}\oplus b_{i-1}$. So we know that all elements of $b$ should be different. Therefore $b$ is a sequence of distinct integers of length $n + 1$ starting with 0 made of numbers $0$ to $2^{m} - 1$. The number of such sequences is $\textstyle\prod_{1}^{n}2^{m}-i$ and this is the answer to problem.
[ "constructive algorithms", "math" ]
1,300
null
238
C
World Eater Brothers
You must have heard of the two brothers dreaming of ruling the world. With all their previous plans failed, this time they decided to cooperate with each other in order to rule the world. As you know there are $n$ countries in the world. These countries are connected by $n - 1$ directed roads. If you don't consider direction of the roads there is a unique path between every pair of countries in the world, passing through each road at most once. Each of the brothers wants to establish his reign in some country, then it's possible for him to control the countries that can be reached from his country using directed roads. The brothers can rule the world if there exists at most two countries for brothers to choose (and establish their reign in these countries) so that any other country is under control of at least one of them. In order to make this possible they want to change the direction of minimum number of roads. Your task is to calculate this minimum number of roads.
Consider we only want to change direction of minimum number of roads so that all other countries are reachable from a specific country $x$. This problem can be solved in $O(n)$ and it's exactly what 219D - Choosing Capital for Treeland asks for. If you don't know how to solve it you can read the editorial of that contest. Consider two countries $A$ and $B$ which can be chosen by world eater brothers to achieve the minimum number of road direction changes. After changing the direction of roads, there exists a country on the undirected path between $A$ and $B$ which is reachable from both $A$ and $B$ using roads. We call such country a middle-country. We want to iterate on middle-countries and find the best two countries for ruling for each middle-country. For each neighbor of the current middle-country calculate the minimum number of road changes in the subtree rooted at that neighbor so that all countries will be reachable from some country in that subtree. Then from two of these subtrees we need to pick $A$ and $B$ and all other subtrees will have edges pointing to the root of subtree. This can be computed in $O(n)$ for each middle-city. So the overall complexity will be $O(n^{2})$.
[ "dfs and similar", "dp", "greedy", "trees" ]
2,100
null
238
D
Tape Programming
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. - Current character pointer (CP); - Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right. We repeat the following steps until the first moment that CP points to somewhere outside the sequence. - If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was $0$ then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one. - If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated. It's obvious the every program in this language terminates after some steps. We have a sequence $s_{1}, s_{2}, ..., s_{n}$ of "<", ">" and digits. You should answer $q$ queries. Each query gives you $l$ and $r$ and asks how many of each digit will be printed if we run the sequence $s_{l}, s_{l + 1}, ..., s_{r}$ as an independent program in this language.
This problem was my favorite in the problemset. The primary point is that at any moment during the interpretation of a program only a prefix of the program is modified and used by IP. Consider we want to calculate the output of subsequence $s_{l}, ..., s_{r}$. While running the original program $s_{1}, ..., s_{n}$ if at any moment CP enters the interval $[l, r]$ it should be pointing to position $l$ and the direction of DP should be right. So it's like we have started interpreting $s_{l}, ..., s_{r}$ independently. The termination of execution of $s_{l}, ..., s_{r}$ is the first time CP points to somewhere outside interval $[l, r]$. Therefore what we need to solve the problem is to run the original program. And after each termination if the program is nonempty then run it again until program is empty. Then we should keep a log of positions we have visited and the time of each visit and the number of printed digits of each type until then. After this preprocessing the to calculate the answer of query $(l_{i}, r_{i})$ its enough to find the first time CP visited $s_{li}$ and the first time CP visited $s_{ri + 1}$ or $s_{li - 1}$ after that. The described approach can be implemented in $O(nlog(n) + qlog(n))$.
[ "data structures", "implementation" ]
2,900
null
238
E
Meeting Her
Urpal lives in a big city. He has planned to meet his lover tonight. The city has $n$ junctions numbered from $1$ to $n$. The junctions are connected by $m$ directed streets, all the roads have equal length. Urpal lives in junction $a$ and the date is planned in a restaurant in junction $b$. He wants to use public transportation to get to junction $b$. There are $k$ bus transportation companies. At the beginning of every second, a bus from the $i$-th company chooses a random shortest path between junction $s_{i}$ and junction $t_{i}$ and passes through it. There might be no path from $s_{i}$ to $t_{i}$. In that case no bus will leave from $s_{i}$ to $t_{i}$. If a bus passes through a junction where Urpal stands, he can get on the bus. He can also get off the bus at any junction along the path. Now Urpal wants to know if it's possible to go to the date using public transportation in a finite amount of time (the time of travel is the sum of length of the traveled roads) and what is the minimum number of buses he should take in the worst case. \textbf{At any moment Urpal knows only his own position and the place where the date will be. When he gets on the bus he knows only the index of the company of this bus. Of course Urpal knows the city map and the the pairs $(s_{i}, t_{i})$ for each company.} Note that Urpal doesn't know buses velocity.
Consider a bus passing a shortest path from $s_{i}$ to $t_{i}$. There are some points that are necessary to pass in order to obtain a shortest path. Firstly we compute them. This can be done in $O(n^{3})$ with Floyd-Warshall and some processing after that. Urpal is sure that a bus from $i$-th company always passes such vertices on his path from $s_{i}$ to $t_{i}$. So he can get on a bus from $i$-th company only at vertices the bus surely passes. At any moment Urpal's status can be uniquely determined by his position on the map and the bus he's traveling with. So we have $nk$ states $(position, bus)$. Our goal is to reach some $(b, ...)$ state from a $(a, v)$ state which bus $v$ surely passes $a$ (source states). So let's find all states that can reach a goal state. We call such states good states. Consider Urpal is at junction $x$ and he's traveling with a bus of type $y$. Let $v_{1}, v_{2}, ..., v_{w}$ be the list of junctions the bus might go on its shortest path from $s_{y}$ to $t_{y}$. And let $c_{1}, c_{2}, ..., c_{l}$ be the list of companies that their bus surely passes junction $x$, excluding $y$-th company. For state $(x, y)$ we know we can reach junction $b$ (it's a good state) if one of the following is true: $x = b$, the minimum cost of solving the problem will be 0. All states $(v_{1}, y)$, $(v_{2}, y)$, ... and $(v_{w}, y)$ are good states, the minimum cost of solving the problem will be the maximum of all these states. At least one of states $(x, c_{1})$, $(x, c_{2})$, ... or $(x, c_{l})$ is a good state, the minimum cost of solving the problem will be the minimum the good ones plus one. At first the only good states we know are states with junction $b$, $(b, ...)$. Now some new states might have become good states. So we add those states to the list of known good states. We do this until no state becomes good anymore. At the end we print the minimum cost of source states which are good, and if they don't exist we print -1. The process thing can be implemented in $O(n^{4})$.
[ "dp", "graphs", "shortest paths" ]
2,600
null
239
A
Two Bags of Potatoes
Valera had two bags of potatoes, the first of these bags contains $x$ $(x ≥ 1)$ potatoes, and the second — $y$ $(y ≥ 1)$ potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains $x$ potatoes) Valera lost. Valera remembers that the total amount of potatoes $(x + y)$ in the two bags, firstly, was not gerater than $n$, and, secondly, was divisible by $k$. Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.
The total number of potatoes is a multiple of $k$ and constraint $\xrightarrow[{k}]{\leq}10^{5}$ there will be at most $10^{5}$ multiples of $k$ in range $1$ to $n$. So you can iterate on multiples of $k$ and print the ones that satisfy the problem.
[ "greedy", "implementation", "math" ]
1,200
null
239
B
Easy Tape Programming
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. - Current character pointer (CP); - Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right. We repeat the following steps until the first moment that CP points to somewhere outside the sequence. - If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was $0$ then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one. - If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated. It's obvious the every program in this language terminates after some steps. We have a sequence $s_{1}, s_{2}, ..., s_{n}$ of "<", ">" and digits. You should answer $q$ queries. Each query gives you $l$ and $r$ and asks how many of each digit will be printed if we run the sequence $s_{l}, s_{l + 1}, ..., s_{r}$ as an independent program in this language.
In this problem you just need to simulate every thing which is written in the statement step by step.
[ "brute force", "implementation" ]
1,500
null
242
A
Heads or Tails
Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin $x$ times, then Petya tosses a coin $y$ times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw. At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least $a$ times, and Petya got heads at least $b$ times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.
This problem was very easy, we should only use two cycles with $i$ and with $j$ ($a \le i \le x$, $b \le j \le y$), iterate all possible outcomes of the game and print such in that $i > j$. The time is $O(x \cdot y)$.
[ "brute force", "implementation" ]
1,100
null
242
B
Big Segment
A coordinate line has $n$ segments, the $i$-th segment starts at the position $l_{i}$ and ends at the position $r_{i}$. We will denote such a segment as $[l_{i}, r_{i}]$. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1. Formally we will assume that segment $[a, b]$ covers segment $[c, d]$, if they meet this condition $a ≤ c ≤ d ≤ b$.
At first, we must note that the answer is always unique, because if segment $i$ covers segment $j$, that segment $j$ can't cover segment $i$. It possible if and only if there are coincide segments in the set, but it's not permissible by the statement. Let's pay attention the answer covers the most left point of all segments and the most right point of all points too. Now then we should found $L = min(l_{i})$ and $R = max(r_{i})$ and print index of segment $[L, R]$, or $- 1$ if there is no such segment in the set. The time is $O(n)$.
[ "implementation", "sortings" ]
1,100
null
242
C
King's Path
The black king is standing on a chess field consisting of $10^{9}$ rows and $10^{9}$ columns. We will consider the rows of the field numbered with integers from $1$ to $10^{9}$ from top to bottom. The columns are similarly numbered with integers from $1$ to $10^{9}$ from left to right. We will denote a cell of the field that is located in the $i$-th row and $j$-th column as $(i, j)$. You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as $n$ segments. Each segment is described by three integers $r_{i}, a_{i}, b_{i}$ $(a_{i} ≤ b_{i})$, denoting that cells in columns from number $a_{i}$ to number $b_{i}$ inclusive in the $r_{i}$-th row are allowed. Your task is to find the minimum number of moves the king needs to get from square $(x_{0}, y_{0})$ to square $(x_{1}, y_{1})$, provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way. Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.
The most important thing for accepted solution is that it is guaranteed that the total length of all given segments doesn't exceed $10^{5}$. We should use this feature, let's number allowed cells and found shortest path by BFS. It's easiest to use associative array such as map in C++ for numbering. The time is $O(n \cdot log(n))$.
[ "dfs and similar", "graphs", "hashing", "shortest paths" ]
1,800
null
242
D
Dispute
Valera has $n$ counters numbered from $1$ to $n$. Some of them are connected by wires, and each of the counters has a special button. Initially, all the counters contain number $0$. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connected to it by a wire, increase by one. Valera and Ignat started having a dispute, the dispute is as follows. Ignat thought of a sequence of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Valera should choose some set of distinct counters and press buttons on each of them exactly once (on other counters the buttons won't be pressed). If after that there is a counter with the number $i$, which has value $a_{i}$, then Valera loses the dispute, otherwise he wins the dispute. Help Valera to determine on which counters he needs to press a button to win the dispute.
Denote current value of counter number $i$ as $b_{i}$. Let's describe an algorithm. It takes any counter $i$ such that $b_{i} = a_{i}$ and presses its button. The algorithm finishes if there is no such $i$. Let's proof correctness of the algorithm: Why does Valera win the game? Because there is no such counter which has $b_{i} = a_{i}$ else we must press the button. Why doesn't algorithm press some button multiple times? Because it presses button number $i$ only if $b_{i} = a_{i}$, and after this pressing the value $b_{i}$ is increased and the equation will be true never. Why is the algorithm fast? Because of paragraph 2 it does no more $n$ pressings which produces no more $n + 2 \cdot m$ increases of the counters. We should use queue for fast seaching counters which has $b_{i} = a_{i}$ like this: every time we change value of the counter numbered $i$ we check equation $b_{i} = a_{i}$ and if it's true then we push value $i$ to the queue. It's easy to understand that all indexes $i$ will be in queue no more one time. Also these paragraphs proof that the answer always exists. You must print $- 1$ never. The time is $O(n + m)$.
[ "dfs and similar", "graphs", "greedy" ]
2,100
null
242
E
XOR on Segment
You've got an array $a$, consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. You are allowed to perform two operations on this array: - Calculate the sum of current array elements on the segment $[l, r]$, that is, count value $a_{l} + a_{l + 1} + ... + a_{r}$. - Apply the xor operation with a given number $x$ to each array element on the segment $[l, r]$, that is, execute $a_{I}=a_{I}\oplus x,a_{I+1}=a_{I+1}\oplus x,\cdot\cdot\cdot,a_{r}=a_{r}\oplus x$. This operation changes exactly $r - l + 1$ array elements. Expression $x\oplus y$ means applying bitwise xor operation to numbers $x$ and $y$. The given operation exists in all modern programming languages, for example in language C++ and Java it is marked as "^", in Pascal — as "xor". You've got a list of $m$ operations of the indicated type. Your task is to perform all given operations, for each sum query you should print the result you get.
Let's write numbers $a_{1}, a_{2}, ..., a_{n}$ as a table which has size $n \times 20$, and $b_{i, j}$ is $j$th bit in $a_{i}$. Then sum of numbers on segment $[l, r]$ equals $\begin{array}{l}{{\sum_{i=l}^{r}\sum_{j=0}^{19}b_{i,j}\cdot2^{j}=\sum_{j=0}^{19}2^{j}\cdot(\sum_{i=l}^{r}b_{i,j})}}\end{array}$. The last notation helps us to process queries. For fast implementation we should use 20 binary trees like cartesian trees or range trees. Every tree matchs one of bits (and matchs one of the columns of the table $b_{i, j}$). calculation of sum is equal to counting $1$-s from $l$-th to $r$-th. operation "xor" equals reversing all bits from $l$-th to $r$-th (i.e. $0$ changes to $1$, $1$ changes to $0$). The first operation executes for all bit numbers, the second executes only for bits in which input number $x_{i}$ has ones. These operations may be easy implemented with binary trees. The time is $O(m \cdot log(n) \cdot 20)$.
[ "bitmasks", "data structures" ]
2,000
null
243
A
The Brand New Function
Polycarpus has a sequence, consisting of $n$ non-negative integers: $a_{1}, a_{2}, ..., a_{n}$. Let's define function $f(l, r)$ ($l, r$ are integer, $1 ≤ l ≤ r ≤ n$) for sequence $a$ as an operation of bitwise OR of all the sequence elements with indexes from $l$ to $r$. Formally: $f(l, r) = a_{l} | a_{l + 1} | ...  | a_{r}$. Polycarpus took a piece of paper and wrote out the values of function $f(l, r)$ for all $l, r$ ($l, r$ are integer, $1 ≤ l ≤ r ≤ n$). Now he wants to know, how many \textbf{distinct} values he's got in the end. Help Polycarpus, count the number of distinct values of function $f(l, r)$ for the given sequence $a$. Expression $x | y$ means applying the operation of bitwise OR to numbers $x$ and $y$. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Let's see how function $f$ changes for all suffixes of sequence $a$. Values of $f$ will increase when you will increase length of suffix. For every increase all 1-bits will stay 1-bits, but some 0-bits will be changed by 1-bits. So, you can see that no more than $k$ increasing will be, where $k$ number of bits (in this problem $k$ = 20). Among all suffixes will be no more that $k + 1$ values of function $f$. Now you can run over sequence $a$ trom left to right and support an array $m$ (or a set) of values of $f$ for all subsegments that end in the current position. Size of $m$ always no more than $k + 1$. When you go from position $i - 1$ into position $i$, you should replace $m = {m_{1}, m_{2}, ..., m_{t}}$ by $m' = {a_{i}, m_{1}|a_{i}, m_{2}|a_{i}, ... m_{t}|a_{i}}$. After that you should remove from $m$ repeated values (if you use set, set will do this dirty work itself). Then you should mark all numbers from $m$ in some global array (or put them into some global set). At the end you should calculate answer from the global array (or set).
[ "bitmasks" ]
1,600
null
243
B
Hydra
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph. A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes $u$ and $v$ connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with $h$ nodes, which are the hydra's heads. The stomach is connected with $t$ nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of $h + t + 2$ nodes. Also, Petya's got a non-directed graph $G$, consisting of $n$ nodes and $m$ edges. Petya got this graph as a last year birthday present from his mom. Graph $G$ contains no self-loops or multiple edges. Now Petya wants to find a hydra in graph $G$. Or else, to make sure that the graph doesn't have a hydra.
You should check for every edge: this one can be body of hydra or not. Let's fix some edge $(u, v)$ (order of vertices is important, i.e. you should also check edge $(v, u)$). Now you should chose some set of $h$ vertices connected with $u$ and some set of $t$ vertices connected with $v$. These sets should not contain vertices $u$ and $v$. Also, these two sets should have no common vertices. If $\deg(u)<h+1$ and ${\mathrm{deg}}(v)<t+1$, there is no any hydra here. Orherwise, if $\deg(u)\geq h+t+1$ or $\deg(v)\geq h+t+1$, there is some hydra in any case. Even if all vertices connected with $u$ and with $v$ are common, number of them so big, that you always can split them into groups of size $ \ge h$ and size $ \ge t$. The last case is $h+1\leq\deg(u)\leq h+l$ and $t+1\leq\deg(v)\leq h+l$. Here you can find all common vertices in $O(h + t)$, using array of flags. When you find the common subset, you can easy check existence of hydra. How to find common vertices in O(h + t) using array of flgs? You should initailize that array in the beginning of program. For every check you should do following actions. Firstly in $O(\mathrm{deg}(u))$ you should mark in the array all neighbours of $u$. After that you should iterate over all adjacent to $v$ vertices and check value of flag in the array for every of them (in $\deg(v)$). Vertices that have "thue" in the array will be common. Finally you should clear the array in $O(\mathrm{deg}(u))$: you should iterate over all adjacent to $u$ vertices again and mark these vertices in the array as "false". Because $\deg(u)\leq h+l$ and $\deg(v)\leq h+l$, the total complexity will be O(h + t). All edges can be checked in time $O(m(h + t))$. So you either find reqired edge or find that there is no required edge. Also in time $O(m)$ you can build hydra with fixed body-edge. This problem also has solution in $O(m{\sqrt{m}})$ independent from values of $h$ and $t$, but this solution is more complex.
[ "graphs", "sortings" ]
2,000
null
243
C
Colorado Potato Beetle
Old MacDonald has a farm and a large potato field, $(10^{10} + 1) × (10^{10} + 1)$ square meters in size. The field is divided into square garden beds, each bed takes up one square meter. Old McDonald knows that the Colorado potato beetle is about to invade his farm and can destroy the entire harvest. To fight the insects, Old McDonald wants to spray some beds with insecticides. So Old McDonald went to the field, stood at the center of the central field bed and sprayed this bed with insecticides. Now he's going to make a series of movements and spray a few more beds. During each movement Old McDonald moves left, right, up or down the field some integer number of meters. As Old McDonald moves, he sprays all the beds he steps on. In other words, the beds that have any intersection at all with Old McDonald's trajectory, are sprayed with insecticides. When Old McDonald finished spraying, he wrote out all his movements on a piece of paper. Now he wants to know how many beds won't be infected after the invasion of the Colorado beetles. It is known that the invasion of the Colorado beetles goes as follows. First some bed on the field border gets infected. Than any bed that hasn't been infected, hasn't been sprayed with insecticides and has a common side with an infected bed, gets infected as well. Help Old McDonald and determine the number of beds that won't be infected by the Colorado potato beetle.
Firstly tou should emulate all process in "idle mode". Let farmer was in points $(x_{0} + 1 / 2, y_{0} + 1 / 2)$, $(x_{1} + 1 / 2, y_{1} + 1 / 2)$, ... , $(x_{n} + 1 / 2, y_{n} + 1 / 2)$. Coordinates $x_{0}$, $x_{0} + 1$, $x_{1}$, $x_{1} + 1$, ... $x_{n}$, $x_{n} + 1$ on axis $x$ are interesting for us. Coordinates $y_{0}$, $y_{0} + 1$, $y_{1}$, $y_{1} + 1$, ... $y_{n}$, $y_{n} + 1$ on axis $y$ are interesting too. You should store all of them into two arrays. Also you should add to these coordinates bounds of the field. Then you should build "compressed" field: every cell of this field means rectangle of the starting field that placed between neighbour interesting coordinates. Size of the compressed field is $O(n) \times O(n)$. Let's initally all cells painted into the white color. Now you should emulate all process again and paint all visited cells in the compressed field by the black color. During every move you will paint $O(n)$ cells, so all process will be done in $O(n^{2})$. Now you should emulate bugs' actions. You should run DFS (ot BFS) from some border cell of the compressed field and paint all reached cells be red color. At the end you should iterate over all compressed field and find sum of areas of rectengles corresponding to black and white cells. So, you will receive the answer. This solution works in $O(n^{2})$.
[ "dfs and similar", "implementation" ]
2,200
null
243
D
Cubes
One day Petya got a set of wooden cubes as a present from his mom. Petya immediately built a whole city from these cubes. The base of the city is an $n × n$ square, divided into unit squares. The square's sides are parallel to the coordinate axes, the square's opposite corners have coordinates $(0, 0)$ and $(n, n)$. On each of the unit squares Petya built a tower of wooden cubes. The side of a wooden cube also has a unit length. After that Petya went an infinitely large distance away from his masterpiece and looked at it in the direction of vector $v = (v_{x}, v_{y}, 0)$. Petya wonders, how many distinct cubes are visible from this position. Help him, find this number. Each cube includes the border. We think that a cube is visible if there is a ray emanating from some point $p$, belonging to the cube, in the direction of vector $ - v$, that doesn't contain any points, belonging to other cubes.
You need for every column find the lowermost cube that you can see. You will see all cubes above this cube. Consider the city from above. You will see drid of size $n \times n$. Now you should draw the line through every node of the grid parallel to vector $v$. We need know only that happens in every strip between two neighbour lines. Every column cover segment of $O(n)$ adjacent strips. Now you should create an array $a$; every element of $a$ corresponding to one strip. This array will store maximal height of considered columns. Then you should sort all columns in order if increasing distance from observer. In that order you should do following queries of 2 types: Minimum on segment. This query is needed when you want find the lowermost visible cube. Replace $a_{i} \rightarrow max(a_{i}, h)$ on segment. You need this query for "drawing" column in the array. That is all solution. You just need choose some data structure that can fast do queries. You can select from: block decomposition (length of every block should be $\sqrt{n}$; because length of every query about $O(n)$, total complexity of solution will be $O(n^{5 / 2})$), segment tree ($O(n^2 \log n)$), stupid array (it's $O(n^{3})$, cache optimized implementaton fits in the time limit).
[ "data structures", "dp", "geometry", "two pointers" ]
2,700
null
243
E
Matrix
Let's consider an $n × n$ square matrix, consisting of digits one and zero. We'll consider a matrix good, if it meets the following condition: in each row of the matrix all ones go in one group. That is, each row of the matrix looks like that $00...0011...1100...00$ (or simply consists of zeroes if it has no ones). You are given matrix $a$ of size $n × n$, consisting of zeroes and ones. Your task is to determine whether you can get a good matrix $b$ from it by rearranging the columns or not.
We will build the matrix constructively. At any step we will have array of groups of columns. Order of groups is defined but order of columns inside every group is unknown. During building we will change order of rows because it is doesn't affect the answer (we can build answer using order of columns only). Consider the way of building of the matrix. Firstly you should find the row that has maximal number of ones. You should swap this row with the first row. Aftar that two groups of columns should be created. Into the first group you should put columns that have "1" in the firts row; all other columns should be stored into the second group. The second group is "special" - see about it below. Now you should more times search the row that has "1" in at least two groups. For every of that rows you can determine positions of all ones no more than only way. If you determined no ways, you should output NO and finish execution. After that you determined positions of ones, you should split some groups of columns into two subgroups. About "special" group. You should take into account case when you should drop some columns from this group and insert them before all groups. You will never face with situation when it is not clear which columns should be dropped and which should not, because in the beginning you chose the row with maximal number of ones. After repeating process than described above sevaral times, "good" rows may end. I.e. for every row all ones will be placed in no more than one group. Now you should recursively do solution described above inside every of groups of columns. The solution works in $O(n^{3})$. It can be upgraded to $O(n^2 \log n)$, but it was not required.
[ "data structures" ]
3,000
null
244
A
Dividing Orange
One day Ms Swan bought an orange in a shop. The orange consisted of $n·k$ segments, numbered with integers from 1 to $n·k$. There were $k$ children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the $i$-th $(1 ≤ i ≤ k)$ child wrote the number $a_{i}$ $(1 ≤ a_{i} ≤ n·k)$. All numbers $a_{i}$ accidentally turned out to be different. Now the children wonder, how to divide the orange so as to meet these conditions: - each child gets exactly $n$ orange segments; - the $i$-th child gets the segment with number $a_{i}$ for sure; - no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.
Consider an array $A$ of integers in range from 1 to $nk$. Let's remove from $A$ all numbers $a_{i}$ and all other numbers store into an array $B$. The array $B$ will have $(n - 1)k$ elements. Now for $i$-th kid you should output numbers $a_{i}$, $B[(n - 1) * (i - 1) + 1]$, $B[(n - 1) * (i - 1) + 2]$, ... $B[(n - 1) * (i - 1) + n - 1]$ ($B$ is 1-based).
[ "implementation" ]
900
null
244
B
Undoubtedly Lucky Numbers
Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits $x$ and $y$. For example, if $x = 4$, and $y = 7$, then numbers 47, 744, 4 are lucky. Let's call a positive integer $a$ undoubtedly lucky, if there are such digits $x$ and $y$ $(0 ≤ x, y ≤ 9)$, that the decimal representation of number $a$ (without leading zeroes) contains only digits $x$ and $y$. Polycarpus has integer $n$. He wants to know how many positive integers that do not exceed $n$, are undoubtedly lucky. Help him, count this number.
Solution 1. You should write some bruteforce solution over all numbers with no more than 9 digits (number $10^{9}$ should be considered separately). Bruteforce algo seems like this: dfs( int num ) // run it as dfs(0) if (num > 0 && num <= n) ans++ if (num >= 10^8) return for a = 0..9 do if num*10+a>0 then if number num*10+a has no more than 2 different digits then dfs( num*10+a )ans will store the answer. After that you wrote bruteforce, you can run it and see that it works fast (that is same time for any testcase). Solution 2. Let's build all undoubdetly lucku numbers using bitmasks. You can iterate over length of number $L$, pair of digits $x$ and $y$, and bitmask $m$ of length $L$. If the $i$-th bit of $m$ is 1, the $i$-th digit of number should be $x$; otherwise it should be $y$. So about $10^{3} \times 2^{10}$ numbers will be generated (it is very rough estimate, count of numbers will be more than 10 times less). In this solution you should accurately process the case of leading zeroes and the case when all digits of number are same.
[ "bitmasks", "brute force", "dfs and similar" ]
1,600
null
245
A
System Administrator
Polycarpus is a system administrator. There are two servers under his strict guidance — $a$ and $b$. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers $x$ and $y$ $(x + y = 10; x, y ≥ 0)$. These numbers mean that $x$ packets successfully reached the corresponding server through the network and $y$ packets were lost. Today Polycarpus has performed overall $n$ ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network. Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.
Let's define following variables: $A_{Reached}$ : Number of packets that reached $A$. $A_{Lost}$ : Number of packets which didn't reach $A$. $B_{Reached}$ : Number of packets that reached $B$. $B_{Lost}$ : Number of packets which didn't reach $B$. We iterate over input and update each variable accordingly. Now answer for server $A$ is LIVE if and only if $A_{Reached} \ge A_{Lost}$ otherwise it's DEAD. Also answer for server $B$ is LIVE if and only if $B_{Reached} \ge B_{Lost}$ otherwise it's DEAD.
[ "implementation" ]
800
#include <iostream> using namespace std; int A_Reached, A_Lost, B_Reached, B_Lost; int main() { int n; cin >> n; for (int i = 1 ; i <= n ; i++) { int t, x, y; cin >> t >> x >> y; if (t == 1) { A_Reached += x; A_Lost += y; } else { B_Reached += x; B_Lost += y; } } if (A_Reached >= A_Lost) cout << "LIVE" << endl; else cout << "DEAD" << endl; if (B_Reached >= B_Lost) cout << "LIVE" << endl; else cout << "DEAD" << endl; return 0; }
245
B
Internet Address
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: \begin{center} <protocol>://<domain>.ru[/<context>] \end{center} where: - <protocol> can equal either "http" (without the quotes) or "ftp" (without the quotes), - <domain> is a non-empty string, consisting of lowercase English letters, - the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters. If string <context> isn't present in the address, then the additional character "/" isn't written. Thus, the address has either two characters "/" (the ones that go before the domain), or three (an extra one in front of the context). When the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters ":", "/", ".". Help Vasya to restore the possible address of the recorded Internet resource.
Problem guarantees that there exists an Internet resource address from which we can obtain our input. At first, let's find Protocol of address. It's sufficient to only check first letter of input, if it's $h$ then protocol is $http$ otherwise, it's $ftp$. Now, let's find position of $.ru$. We can iterate over our string from right to left and greedily choose the first occurrence of $.ru$ as TLD. Now the rest of Internet address can be obtained easily as we have positions of Protocol and TLD. Just note that we should check whether $< context >$ is present after $.ru$ or not. Also picking $.ru$ greedily from left to right fails following testcase, hence it's incorrect. Input: httpruru Incorrect output: http://.ru/ru Correct output: http://ru.ru
[ "implementation", "strings" ]
1,100
#include <iostream> using namespace std; string ans, s; int index; int main() { cin >> s; if (s[0] == 'h') { ans += "http://"; index = 4; } else { ans += "ftp://"; index = 3; } for (int i = (int)s.size()-3 ; i >= index ; i--) if (s[i] == 'r' && s[i+1] == 'u') { cout << ans + s.substr(index, i-index) + ".ru/" + s.substr(i+2) << endl; return 0; } cout << ans + s.substr(index, (int)s.size()-2-index) + ".ru" << endl; return 0; }
245
C
Game with Coins
Two pirates Polycarpus and Vasily play a very interesting game. They have $n$ chests with coins, the chests are numbered with integers from 1 to $n$. Chest number $i$ has $a_{i}$ coins. Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer $x$ $(2·x + 1 ≤ n)$ and take a coin from each chest with numbers $x$, $2·x$, $2·x + 1$. It may turn out that some chest has no coins, in this case the player doesn't take a coin from this chest. The game finishes when all chests get emptied. Polycarpus isn't a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily's moves.
First note that if $n \le 2$ or $n\equiv0{\bmod{2}}$ then answer is $- 1$. It's because of the following $2$ facts: 1. $2x+1\leq n\to x\leq{\frac{n-1}{2}}$ and $x\in\mathbb{N}$ so $n \ge 3$ otherwise $x$ won't be a natural number. 2. If $n\equiv0{\bmod{2}}$ then $n = 2k$ and $x\leq{\frac{2k-1}{2}}$ which means $x \le k - 1$ hence $2x + 1 \le 2k - 1$ so there doesn't exist a $x$ such that it satisfies problem's conditions and can be used to reduce $a[n]$ In other situations, there always exists a sequence which can finish the game. We now propose a greedy algorithm and then prove it's correctness. Algorithm: Iterate from $n$ to $2$. Suppose that you're in position $i$. If $i\equiv0{\bmod{2}}$ then take $x={\frac{i}{2}}$ otherwise, take $x={\frac{i-1}{2}}$ and execute operations with obtained $x$ as long as $a[i] > 0$ and increase $ans$ for each execution. At the end, increase $ans$ by $a[1]$ and output it. Remember to check if an element you're going to decrease by $1$ is positive beforehand. Correctness: Let's prove correctness of algorithm by induction on $n$. Base case is $n = 3$ in which $ans = max(a[1], a[2], a[3])$ and algorithm correctly computes it. Now take $n \ge 5$ and consider it's of the form $2k + 1$. To change $a[n]$ and $a[n - 1]$ into $0$, we need to take $x = k$ as it's the only possible $x$ which affects their values and perform operations exactly $max(a[n], a[n - 1])$ number of times. It's both necessary and sufficient in order to change both of them into $0$. After that, we can ignore both $a[n]$ and $a[n - 1]$ from the list and induction hypothesis ensures that executing algorithm on remaining elements finishes the game in the least number of moves. $\blacksquare$
[ "greedy" ]
1,700
#include <iostream> using namespace std; const int MAXN = 110; int n, a[MAXN], ans; int main() { cin >> n; if (n <= 2 || n % 2 == 0) { cout << -1 << endl; return 0; } for (int i = 1 ; i <= n ; i++) cin >> a[i]; for (int i = n ; i >= 2 ; i--) { while (a[i] && i & 1) { int x = (i-1)/2; a[i]--; a[x] -= (a[x]) ? 1 : 0; a[2*x] -= (a[2*x]) ? 1 : 0; ans++; } while (a[i] && i % 2 == 0) { int x = i/2; a[i]--; a[x] -= (a[x]) ? 1 : 0; a[2*x+1] -= (a[2*x+1]) ? 1 : 0; ans++; } } ans += a[1]; cout << ans << endl; return 0; }
245
D
Restoring Table
Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation. For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers $a_{1}, a_{2}, ..., a_{n}$. He also wrote a square matrix $b$ of size $n × n$. The element of matrix $b$ that sits in the $i$-th row in the $j$-th column (we'll denote it as $b_{ij}$) equals: - the "bitwise AND" of numbers $a_{i}$ and $a_{j}$ (that is, $b_{ij} = a_{i} & a_{j}$), if $i ≠ j$; - -1, if $i = j$. Having written out matrix $b$, Polycarpus got very happy and wiped $a$ off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly. Help Polycarpus, given matrix $b$, restore the sequence of numbers $a_{1}, a_{2}, ..., a_{n}$, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed $10^{9}$.
Consider $a[i]$, $a[j]$ and $b[i][j] = a[i]&a[j]$. Now consider binary representation of $b[i][j]$. For each $1$-bit of $b[i][j]$ at position $k$, ($0$-indexed) we conclude that $k$-th bit of $a[i]$ and $a[j]$ equals $1$ so we set $a[i] = a[i]|2^{k}$ and $a[j] = a[j]|2^{k}$. Now let's describe algorithm. We use $i$ to iterate from $1$ to $n$ and for each $i$, we iterate over all $b[i][j]$ such that $i \neq j$ and assign $a[i] = a[i]|b[i][j]$. At the end, we'll have sequence $a$ constructed. Now we prove correctness of algorithm. Correctness: Consider $2$ indices $i$ and $j$ such that $a[i]&a[j] \neq b[i][j]$. Consider that $k$-th bit of $a[i]&a[j]$ differs from $k$-th bit of $b[i][j]$. If $k$-th bit of their $AND$ equals $0$, we face contradiction as $k$-th bit of $b[i][j]$ has to be $1$ and algorithm ensures that in this situation, $k$-th bit of both numbers will be set as $1$. On the other hand, if $k$-th bit of their $AND$ equals $1$ then we conclude that $k$-th bit of both numbers equals $1$ hence when calculating $AND$ of them, we get $1$ in $k$-th bit which is a contradiction with our preliminary hypothesis. So we proved correctness of algorithm. $\blacksquare$
[ "constructive algorithms", "greedy" ]
1,500
#include <iostream> using namespace std; const int MAXN = 110; int n, a[MAXN]; int main() { cin >> n; for (int i = 1 ; i <= n ; i++) for (int j = 1 ; j <= n ; j++) { int AND; cin >> AND; if (i != j) a[i] |= AND; } for (int i = 1 ; i <= n ; i++) cout << a[i] << " "; cout << endl; return 0; }
245
E
Mishap in Club
Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen. On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, each time a visitor left the club, Polycarpus put character "-" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended. Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.
Consider following interpretation of problem. We're standing in $(0, 0)$ at the center of Cartesian coordinate system. We iterate over the given sequence, for each $+$, we move from $(x, y)$ to $(x + 1, y + 1)$ and for each $-$, we move from $(x, y)$ to $(x + 1, y - 1)$. Consider the maximum $y$ coordinate we visit during our movement as $MAX$ and minimum $y$ we visit as $MIN$. It's obvious that we need at least $MAX - MIN$ people. It can be proved that we can take our moves in such a way that we exactly need $MAX - MIN$ people. For each $+$, if there exists a person out of cafe who had entered cafe once or was in cafe once, we move him in, otherwise, we need a new person. The same argument holds for each $-$ we see in sequence.
[ "greedy", "implementation" ]
1,400
#include <iostream> using namespace std; string s; int MAX, MIN, pos; int main() { cin >> s; for (int i = 0 ; i < (int)s.size() ; i++) if (s[i] == '+') { pos++; MAX = max(pos, MAX); } else { pos--; MIN = min(pos, MIN); } cout << MAX - MIN << endl; return 0; }
245
F
Log Stream Analysis
You've got a list of program warning logs. Each record of a log stream is a string in this format: \begin{center} "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). \end{center} String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format. The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description). Your task is to print the first moment of time, when the number of warnings for the last $n$ seconds was not less than $m$.
First note that "MESSAGE" is useless and can be ignored. Year is always $2012$ so it can be ignored too. Now convert each date and time to seconds past from beginning of $2012$. Maintain a list, such as a vector, $V$, for storing seconds. Define pointer $head$ to be head of your vector. Define $sec$ to be conversion of date and time in seconds for the most recent log. As long as $head \le Size[V]$ and $V[head] + n \le sec$, increase $head$. After that, push $sec$ into $V$. If $Size[V] - head \ge m$ then answer is the current log. If at the end, no time was found, answer will be $- 1$. Implementation Note: You may use $stringstream$ in order to ease implementation part.
[ "binary search", "brute force", "implementation", "strings" ]
2,000
#include <iostream> #include <sstream> #include <vector> using namespace std; vector <int> v; int months[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int n, m, head; string s; int input(string temp) { int val; stringstream sin; sin << temp; sin >> val; return val; } int main() { ios::sync_with_stdio(0); cin >> n >> m; getline(cin, s); while (getline(cin, s)) { int month = input(s.substr(5, 2)); int day = input(s.substr(8, 2)); int hour = input(s.substr(11, 2)); int min = input(s.substr(14, 2)); int second = input(s.substr(17, 2)); int sec = second + min * 60 + hour * 3600 + day * 24 * 3600; for (int i = 0 ; i+1 < month ; i++) sec += months[i] * 24 * 3600; while (head < (int)v.size() && v[head] + n <= sec) head++; v.push_back(sec); if ((int)v.size() - head >= m) { cout << s.substr(0, 19) << endl; return 0; } } cout << -1 << endl; return 0; }
245
G
Suggested Friends
Polycarpus works as a programmer in a start-up social network. His boss gave his a task to develop a mechanism for determining suggested friends. Polycarpus thought much about the task and came to the folowing conclusion. Let's say that all friendship relationships in a social network are given as $m$ username pairs $a_{i}, b_{i}$ $(a_{i} ≠ b_{i})$. Each pair $a_{i}, b_{i}$ means that users $a_{i}$ and $b_{i}$ are friends. Friendship is symmetric, that is, if $a_{i}$ is friends with $b_{i}$, then $b_{i}$ is also friends with $a_{i}$. User $y$ is a suggested friend for user $x$, if the following conditions are met: - $x ≠ y$; - $x$ and $y$ aren't friends; - among all network users who meet the first two conditions, user $y$ has most of all common friends with user $x$. User $z$ is a common friend of user $x$ and user $y$ $(z ≠ x, z ≠ y)$, if $x$ and $z$ are friends, and $y$ and $z$ are also friends. Your task is to help Polycarpus to implement a mechanism for determining suggested friends.
Use $map$ in order to map people to numbers. Construct the given graph using adjacency list. Now, let's find answer for each vertex $v$. Mark all of $v$'s neighbors. After that iterate over all other vertices, and iterate over their adjacency list and count their mutual neighbors with $v$ and update answer for $v$. Complexity is $O(m)$ for each vertex $v$. Summing up all complexities, we conclude that our algorithm is of $O(nm)$ and as $n$ is of $O(m)$, we can conclude that overall complexity is $O(m^{2})$.
[ "brute force", "graphs" ]
2,200
#include <iostream> #include <vector> #include <map> #include <cstring> using namespace std; const int MAXN = 10000 + 10; map <string, int> vertices; int n, m, mark[MAXN], ans[MAXN]; vector <int> g[MAXN]; int main() { ios::sync_with_stdio(0); cin >> m; for (int i = 1 ; i <= m ; i++) { string s1, s2; cin >> s1 >> s2; if (!vertices[s1]) vertices[s1] = ++n; if (!vertices[s2]) vertices[s2] = ++n; int u = vertices[s1]; int v = vertices[s2]; g[u].push_back(v); g[v].push_back(u); } for (int i = 1 ; i <= n ; i++) { int count = 0; memset(mark, 0, sizeof(mark)); for (int j = 0 ; j < (int)g[i].size() ; j++) mark[g[i][j]] = 1; for (int j = 1 ; j <= n ; j++) if (i != j && !mark[j]) { int temp = 0; for (int k = 0 ; k < (int)g[j].size() ; k++) temp += mark[g[j][k]]; if (temp > ans[i]) { ans[i] = temp; count = 1; } else if (temp == ans[i]) count++; } ans[i] = count; } cout << n << endl; for (map<string, int>::iterator it = vertices.begin() ; it != vertices.end() ; it++) cout << it->first << " " << ans[it->second] << endl; return 0; }
245
H
Queries for Number of Palindromes
You've got a string $s = s_{1}s_{2}... s_{|s|}$ of length $|s|$, consisting of lowercase English letters. There also are $q$ queries, each query is described by two integers $l_{i}, r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ |s|)$. The answer to the query is the number of substrings of string $s[l_{i}... r_{i}]$, which are palindromes. String $s[l... r] = s_{l}s_{l + 1}... s_{r}$ $(1 ≤ l ≤ r ≤ |s|)$ is a substring of string $s = s_{1}s_{2}... s_{|s|}$. String $t$ is called a palindrome, if it reads the same from left to right and from right to left. Formally, if $t = t_{1}t_{2}... t_{|t|} = t_{|t|}t_{|t| - 1}... t_{1}$.
Note: Strings and arrays are considered $0$-based in the following solution. Let $isPal[i][j]$ be $1$ if $s[i...j]$ is palindrome, otherwise, set it $0$. Let's define $dp[i][j]$ to be number of palindrome substrings of $s[i...j]$. Let's calculate $isPal[i][j]$ and $dp[i][j]$ in $O(|S|^{2})$. First, initialize $isPal[i][i] = 1$ and $dp[i][i] = 1$. After that, loop over $len$ which states length of substring and for each specific $len$, loop over $start$ which states starting position of substring. $isPal[start][start + len - 1]$ can be easily calculated by the following formula: isPal[start][start+len-1] = isPal[start+1][start+len-2] & (s[start] == s[start+len-1])After that, $dp[start][start + len - 1]$ can be calculated by the following formula which is derived from Inc-Exc Principle. dp[start][start+len-1] = dp[start][start+len-2] + dp[start+1][start+len-1] - dp[start+1][start+len-2] + isPal[start][start+len-1]After preprocessing, we get queries $l_{i}$ and $r_{i}$ and output $dp[l_{i} - 1][r_{i} - 1]$. Overall complexity is $O(|S|^{2})$.
[ "dp", "hashing", "strings" ]
1,800
#include <iostream> using namespace std; const int MAXN = 5000 + 10; string s; int n, q, dp[MAXN][MAXN]; bool isPal[MAXN][MAXN]; int main() { ios::sync_with_stdio(0); cin >> s; n = (int)s.size(); for (int i = 0 ; i < n ; i++) { isPal[i][i] = 1; dp[i][i] = 1; isPal[i+1][i] = 1; } for (int len = 2 ; len <= n ; len++) for (int start = 0 ; start <= n-len ; start++) { isPal[start][start+len-1] = isPal[start+1][start+len-2] & s[start] == s[start+len-1]; dp[start][start+len-1] = dp[start][start+len-2] + dp[start+1][start+len-1] - dp[start+1][start+len-2] + isPal[start][start+len-1]; } cin >> q; for (int i = 1 ; i <= q ; i++) { int l, r; cin >> l >> r; l--; r--; cout << dp[l][r] << endl; } return 0; }
246
A
Buggy Sorting
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of $n$ integers $a_{1}, a_{2}, ..., a_{n}$ in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number $n$ and array $a$. \begin{verbatim} loop integer variable $i$ from $1$ to $n - 1$     loop integer variable $j$ from $i$ to $n - 1$         if $(a_{j} > a_{j + 1})$ , then swap the values of elements $a_{j}$ and $a_{j + 1}$ \end{verbatim} But Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of $n$ doesn't exist, print -1.
In this problem you should hack the sorting algorithm, of course it was incorrect. It was correct only for arrays with $n < = 2$. In other cases you could print $n, n-1, ..., 1$ as a counter-example. To make the sorting right, the second cycle should be from $1$ but not from $i$.
[ "constructive algorithms", "greedy", "sortings" ]
900
null
246
B
Increase and Decrease
Polycarpus has an array, consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: - he chooses two elements of the array $a_{i}$, $a_{j}$ $(i ≠ j)$; - he simultaneously increases number $a_{i}$ by $1$ and decreases number $a_{j}$ by $1$, that is, executes $a_{i} = a_{i} + 1$ and $a_{j} = a_{j} - 1$. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.
Note, that you can always get the answer $n-1$. To get this result you should make first $n-1$ equal using the last element as the second element in pair of given operation. But after it, the whole array could become equal. It could happen if the sum of array's elements is divisible by $n$. So the answer is $n-1$ or $n$.
[ "greedy", "math" ]
1,300
null
246
C
Beauty Pageant
General Payne has a battalion of $n$ soldiers. The soldiers' beauty contest is coming up, it will last for $k$ days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants. All soldiers in the battalion have different beauty that is represented by a positive integer. The value $a_{i}$ represents the beauty of the $i$-th soldier. On each of $k$ days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of $k$ days the beauty of the sent detachment should be unique. In other words, all $k$ beauties of the sent detachments must be distinct numbers. Help Payne choose $k$ detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty.
This problem was rather mathematical. The correct solution is: firstly take every element once, then take the maximum and any other, then two maximums and any other, then three maximums and any other and so on. In this case, you get as many sets as you need in this problem. It is easy to check, that all sums will be different.
[ "brute force", "constructive algorithms", "greedy" ]
1,600
null
246
D
Colorful Graph
You've got an undirected graph, consisting of $n$ vertices and $m$ edges. We will consider the graph's vertices numbered with integers from 1 to $n$. Each vertex of the graph has a color. The color of the $i$-th vertex is an integer $c_{i}$. Let's consider all vertices of the graph, that are painted some color $k$. Let's denote a set of such as $V(k)$. Let's denote the value of the neighbouring color diversity for color $k$ as the cardinality of the set $Q(k) = {c_{u} :  c_{u} ≠ k$ and there is vertex $v$ belonging to set $V(k)$ such that nodes $v$ and $u$ are connected by an edge of the graph$}$. Your task is to find such color $k$, which makes the cardinality of set $Q(k)$ maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color $k$, that the graph has at least one vertex with such color.
This problem could be solved in this way: create new graph where vertices are the colors of the given graph. The edge between vertices $u$ and $v$ belongs this new graph if there are two vertices $a$ and $b$ in the given graph such that $c[a] = u$ and $c[b] = v$. So, the answer is such color $k$ with minimum number, that the degree of the vertex $k$ in the new graph is maximum (without multiple edges). Such solution could be written using $O(M \cdot log(N))$ time.
[ "brute force", "dfs and similar", "graphs" ]
1,600
null
246
E
Blood Cousins Return
Polycarpus got hold of a family tree. The found tree describes the family relations of $n$ people, numbered from 1 to $n$. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique. We call the man with a number $a$ a 1-ancestor of the man with a number $b$, if the man with a number $a$ is a direct ancestor of the man with a number $b$. We call the man with a number $a$ a $k$-ancestor $(k > 1)$ of the man with a number $b$, if the man with a number $b$ has a 1-ancestor, and the man with a number $a$ is a $(k - 1)$-ancestor of the 1-ancestor of the man with a number $b$. In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an $x$-ancestor of himself, for some $x$, $x > 0$). We call a man with a number $a$ the $k$-son of the man with a number $b$, if the man with a number $b$ is a $k$-ancestor of the man with a number $a$. Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote $m$ pairs of numbers $v_{i}$, $k_{i}$. Help him to learn for each pair $v_{i}$, $k_{i}$ the number of distinct names among all names of the $k_{i}$-sons of the man with number $v_{i}$.
This problem had little in common with problem 208E - Blood Cousins. In comments to this problem there was given a solution using structure deque (array in which you can add or delete elements from both endings). Let's describe solution using this structure. Firstly all different names change with different integers and for every vertex $v$ save all queries with this vertex. Then for every vertex, which is root of some tree make dfs, the parameters of dfs are vertex $v$ and deque <set > $z$. This deque for every depth $i$ of the subtree of $v$ save set - all different names (integers) on depth $i$. This deque could be calculated simply. Consider all sons of $v$ and calculate such deque for them. Obviously, the size of our deque $z$ will be maximum of sizes of descendants' deques. Then consider every descendants' deques and merge appropriate sets of integers. Of course, we will merge smaller set to a larger set. After that you should insert to the beginning of deque $z$ the set of size $1$ - color of vertex $v$. After this, you can at once answer all queries of vertex $v$. Answer is $0$ if $v$ has no descendants on the depth $k$ or the size of $z[k]$. It is known that such method has good asymptotic, the author's solution works about one second. The asymptotic is $O(N \cdot log^{2}(N))$. The solution should be realized carefully. You must not copy every element of your set or deque. You should do swap of smaller and greater set or deque without copying elements ant than merge smaller to greater.
[ "binary search", "data structures", "dfs and similar", "dp", "sortings" ]
2,400
null
250
A
Paper Work
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as $n$ days. Right now his task is to make a series of reports about the company's performance for the last $n$ days. We know that the main information in a day report is value $a_{i}$, the company's profit on the $i$-th day. If $a_{i}$ is negative, then the company suffered losses on the $i$-th day. Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the $n$ days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on. It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses $(a_{i} < 0)$, he loses his temper and his wrath is terrible. Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal. Write a program that, given sequence $a_{i}$, will print the minimum number of folders.
For every folder you should take reports as much as possible. In other words, you should stop forming a folder either before the third bad report or in the end of sequence. You can easily prove that this strategy is optimal. This solution works in $O(n)$.
[ "greedy" ]
1,000
null
250
B
Restoring IPv6
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full. Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000" $ → $ "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address. Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several \textbf{consecutive blocks}, with all 16 bits equal to 0. You can see examples of zero block shortenings below: - "a56f:00d3:0000:0124:0001:0000:0000:0000" $ → $ "a56f:00d3:0000:0124:0001::"; - "a56f:0000:0000:0124:0001:0000:1234:0ff0" $ → $ "a56f::0124:0001:0000:1234:0ff0"; - "a56f:0000:0000:0000:0001:0000:1234:0ff0" $ → $ "a56f:0000::0000:0001:0000:1234:0ff0"; - "a56f:00d3:0000:0124:0001:0000:0000:0000" $ → $ "a56f:00d3:0000:0124:0001::0000"; - "0000:0000:0000:0000:0000:0000:0000:0000" $ → $ "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon. The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short. You've got several short records of IPv6 addresses. Restore their full record.
Firstly you should split string into substrings using ":" as separator. All empty substrings will go in the row; you should leave only one of them. Then you should calculate number of nonempty substrings and determine number of zero-blocks which will replace empty substring. After replacing you should increase every substring to length 4 inserting leading zeros. After all you should output the answer.
[ "implementation", "strings" ]
1,500
null
250
C
Movie Critics
A film festival is coming up in the city N. The festival will last for exactly $n$ days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to $k$. On the $i$-th day the festival will show a movie of genre $a_{i}$. We know that a movie of each of $k$ genres occurs in the festival programme at least once. In other words, each integer from 1 to $k$ occurs in the sequence $a_{1}, a_{2}, ..., a_{n}$ at least once. Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site. As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress. Valentine can't watch all $n$ movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the $k$ genres and will skip all the movies of this genre. He is sure to visit other movies. Valentine wants to choose such genre $x$ ($1 ≤ x ≤ k$), that the total number of after-movie stresses (after all movies of genre $x$ are excluded) were minimum.
Consider some maximal by inclusion segment of movies of some genre $x$ (this number from 1 to $k$). Now let's see how changes number of stresses after removing this segment. If the segment adjoins to the end of all sequence $a$, improvement will be +1. Segment cannot adjoin to both ends of sequence because $k > 1$. For some seqment $[i, j]$ inside of sequence consider values $a_{i - 1}$ and $a_{j + 1}$. If they are equal, after deleting segment improvement will be +2; otherwise it will be +1. Now you should iterate over all maximal be inclusion segments and find improvement for every of them. After that you should group all segments by genre and calculate sum of improvements inside every group. Answer will be number of genre of group that has maximal total improvement (if there are many of them, you should chose minimal number of genre). You can implement this solution in in $O(n)$.
[ "greedy" ]
1,600
null
250
D
Building Bridge
Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages. The river banks can be assumed to be vertical straight lines $x = a$ and $x = b$ ($0 < a < b$). The west village lies in a steppe at point $O = (0, 0)$. There are $n$ pathways leading from the village to the river, they end at points $A_{i} = (a, y_{i})$. The villagers there are plain and simple, so their pathways are straight segments as well. The east village has reserved and cunning people. Their village is in the forest on the east bank of the river, but its exact position is not clear. There are $m$ twisted paths leading from this village to the river and ending at points $B_{i} = (b, y'_{i})$. The lengths of all these paths are known, the length of the path that leads from the eastern village to point $B_{i}$, equals $l_{i}$. The villagers want to choose exactly one point on the left bank of river $A_{i}$, exactly one point on the right bank $B_{j}$ and connect them by a straight-line bridge so as to make the total distance between the villages (the sum of $|OA_{i}| + |A_{i}B_{j}| + l_{j}$, where $|XY|$ is the Euclidean distance between points $X$ and $Y$) were minimum. The Euclidean distance between points $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ equals $\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}}$. Help them and find the required pair of points.
For every point of the east river bank you should find optimal point of the west bank. After that you should chose optimal pair over all considered east points. Well, let's fix $j$-th east point ($1 \le j \le m$). Now consider how changes total distance depending on chosing the west point. The best point is intersection of lines $OB_{j}$ and $x = a$: $Z=(a,\frac{a}{b}y_{j}^{\prime})$, but this point can be not present among all west points. You can see that if you will move from point $Z$ up or down, total distance will increase. So only nearest to $Z$ points may be considered. You can find that points using binary search. Also you can observe that after every increasing of $j$ point $Z$ will move in same direction; so you can support nearest points to $Z$ usins some pointer. The third way is using such fact that during moving point over the west bank total distance initially will decrease and then increase; so you can use ternary search here. Considered solutions work in $O(m + n)$ and $O(m\log n)$.
[ "geometry", "ternary search", "two pointers" ]
1,900
null
250
E
Mad Joe
Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path. Joe's house has $n$ floors, each floor is a segment of $m$ cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each floor is surrounded by a concrete wall on the left and on the right. Now Joe is on the $n$-th floor and in the first cell, counting from left to right. At each moment of time, Joe has the direction of his gaze, to the right or to the left (always one direction of the two). Initially, Joe looks to the right. Joe moves by a particular algorithm. Every second he makes one of the following actions: - If the cell directly under Joe is empty, then Joe falls down. That is, he moves to this cell, the gaze direction is preserved. - Otherwise consider the next cell in the current direction of the gaze. - If the cell is empty, then Joe moves into it, the gaze direction is preserved. - If this cell has bricks, then Joe breaks them with his forehead (the cell becomes empty), and changes the direction of his gaze to the opposite. - If this cell has a concrete wall, then Joe just changes the direction of his gaze to the opposite (concrete can withstand any number of forehead hits). Joe calms down as soon as he reaches \textbf{any} cell of the first floor. The figure below shows an example Joe's movements around the house. Determine how many seconds Joe will need to calm down.
You should emulate the process. You can catch case of infinity walk if you will observe hits with concrete wall from the left and the right side. If for some floor both types of hits happened, you should output "Never". Stupid emulation is very slow. It has complexity $O(nm^{2})$ and answer can be about $10^{10}$. You should speed up stupid emulation using following way. For every floor you should store segment of visited cells (two integers - L and R bounds). We know that under every cell of this segment all cells are non-empty. Therefore after every changing of move direction you can go through all the segment in $O(1)$. After every one or two "teleportations" through segment you either expand bounds of the segnent or change some brick-cell into empty-cell or fall down. But actions of every type you can do no more than $nm$ times, so this optimization improves complexety to $O(nm)$.
[ "brute force" ]
2,000
null
251
A
Points on Line
Little Petya likes points a lot. Recently his mom has presented him $n$ points lying on the line $OX$. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed $d$. Note that the order of the points inside the group of three chosen points doesn't matter.
Let's select the rightmost point of our triplet. In order to do this we can iterate over all points in ascending order of their X-coordinate. At the same time we'll maintain a pointer to the leftmost point which lays on the distance not greater than $d$ from the current rightmost point. We can easily find out the number of points in the segment between two pointers, excluding the rightmost point. Let's call this number $k$. Then there exist exactly $k * (k - 1) / 2$ triplets of points with the fixed rightmost point. The only thing left is to sum up these values for all rightmost points.
[ "binary search", "combinatorics", "two pointers" ]
1,300
null
251
B
Playing with Permutations
Little Petya likes permutations a lot. Recently his mom has presented him permutation $q_{1}, q_{2}, ..., q_{n}$ of length $n$. A permutation $a$ of length $n$ is a sequence of integers $a_{1}, a_{2}, ..., a_{n}$ $(1 ≤ a_{i} ≤ n)$, all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length $n$. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules: - Before the beginning of the game Petya writes permutation $1, 2, ..., n$ on the blackboard. After that Petya makes exactly $k$ moves, which are described below. - During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. - Let's assume that the board contains permutation $p_{1}, p_{2}, ..., p_{n}$ at the given moment. Then Petya removes the written permutation $p$ from the board and writes another one instead: $p_{q1}, p_{q2}, ..., p_{qn}$. In other words, Petya applies permutation $q$ (which he has got from his mother) to permutation $p$. - All actions are similar to point 1, except that Petya writes permutation $t$ on the board, such that: $t_{qi} = p_{i}$ for all $i$ from 1 to $n$. In other words, Petya applies a permutation that is inverse to $q$ to permutation $p$. We know that after the $k$-th move the board contained Masha's permutation $s_{1}, s_{2}, ..., s_{n}$. Besides, we know that throughout the game process Masha's permutation \textbf{never occurred on the board} before the $k$-th move. Note that the game has exactly $k$ moves, that is, throughout the game the coin was tossed exactly $k$ times. Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding.
First, we need to theck whether permutation $s$ is the identity permutation. If it is, then the answer is "NO". Now we'll describe an algorithm which works in all cases except for one. We'll tell about this case later. Let's apply our permutation $q$ until either the current permutation becomes equal to $s$ or we make exactly $k$ steps. If the current permutation is equal to $s$ and we've made $t$ steps before this happened, then we need to look at the parity of $k - t$. If this number is even, then we can select any two consequent permutations in the sequence and apply $(k - t) / 2$ times the following two permutations in this order: $q$ and $inv(q)$, where $inv(q)$ is the inversed permutation $q$. Actually, we don't need to build the sequence itself, it's enough to check only the parity of $k - t$. So, if it is even, then the answer is "YES". Analogically, we can replace $q$ with $inv(q)$ and repeat described process again. If we still didn't print "YES", then the answer is "NO". The algorithm we've just described works for all cases except for one: when the permutation $q$ is equal to $inv(q)$ and at the same time $s$ is reachable within one step. In this case the answer is "YES" iff $k = 1$. The complexity of described solution is $O(N^{2})$.
[ "implementation", "math" ]
1,800
null
251
C
Number Transformation
Little Petya likes positive integers a lot. Recently his mom has presented him a positive integer $a$. There's only one thing Petya likes more than numbers: playing with little Masha. It turned out that Masha already has a positive integer $b$. Petya decided to turn his number $a$ into the number $b$ consecutively performing the operations of the following two types: - Subtract 1 from his number. - Choose any integer $x$ from $2$ to $k$, inclusive. Then subtract number $(a mod x)$ from his number $a$. Operation $a mod x$ means taking the remainder from division of number $a$ by number $x$. Petya performs one operation per second. Each time he chooses an operation to perform during the current move, no matter what kind of operations he has performed by that moment. In particular, this implies that he can perform the same operation any number of times in a row. Now he wonders in what minimum number of seconds he could transform his number $a$ into number $b$. Please note that numbers $x$ in the operations of the second type are selected anew each time, independently of each other.
Let $L$ be the least common multiple of all numbers from 2 to $k$, inclusive. Note that if $a$ is divisible by $L$, then we can't decrease it with applying an operation of the second type. It means that any optimal sequence of transformations will contain all numbers divisible by $L$ which are located between $b$ and $a$. Let's split our interval from $b$ to $a$ into several intervals between the numbers divisible by $L$. It may happen that the first and the last intervals will have length less than $L$. Now we can solve the problem for the first interval, the last interval and for any interval between them. After that we need to multiply the last result by the total number of intervals excluding the first and the last ones. The only thing left is to add up obtained 3 values. In order to solve the problem for one interval one can simply use bfs. Be careful in the cases when we have only 1 or 2 intervals. The complexity of described solution is $O(L)$.
[ "dp", "greedy", "number theory" ]
2,000
null
251
D
Two Sets
Little Petya likes numbers a lot. Recently his mother has presented him a collection of $n$ non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill: - Let's introduce $x_{1}$ to denote the $xor$ of all numbers Petya has got left; and let's introduce $x_{2}$ to denote the $xor$ of all numbers he gave to Masha. Value $(x_{1} + x_{2})$ must be as large as possible. - If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value $x_{1}$. The $xor$ operation is a bitwise excluding "OR", that is denoted as "xor" in the Pascal language and "^" in C/C++/Java. Help Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the $xor$ of an empty set of numbers equals 0.
Let $X$ be the $xor$ of all numbers in the input. Also let $X1$ be the $xor$ of all numbers in the first collection and $X2$ be the $xor$ of all numbers in the second collection. Note, if the $i$-th bit in $X$ is equal to 1 then the same bit in numbers $X1$ and $X2$ is either equal 0 and 1 or 1 and 0, respectively. Analogically, if the $i$-th bit in $X$ is equal to 0 then this bit in numbers $X1$ and $X2$ is either equal 0 and 0 or 1 and 1, respectively. As we can see, if the $i$-th bit in $X$ is equal to 1 then it doesn't affect on the sum $X1 + X2$ in any way. For now, let's forget about the second condition in the statement which asks us to minimize $X1$ in case of tie. In order to find the optimal value of $X1 + X2$ we need to make one more observation. Let's look at the most significant bit of number $X$ which is equal to 0. If there exist such partitions of the initial collection in which this bit is equal to 1 in $X1$ then the optimal partition should be one of them. To prove this one should remember that the respective bit in number $X2$ is also equal to 1. Let this bit correspond to $2^{L}$. If the bit we are looking at is equal to 1 in both $X1$ and $X2$ then the smallest possible value of $X1 + X2$ is $2^{L + 1}$. On the other hand, if both $X1$ and $X2$ have zero in this bit, then the maximal possible value of $X1 + X2$ is $2^{L + 1} - 2$ which is strictly smaller than $2^{L + 1}$. We'll be solving the initial problem with a greedy algorithm. Let's iterate over all bits which are equal to 0 in number $X$ from highest to lowest. We'll try to put 1 to the number $X1$ in this position and then check if there exists at least one partition which satisfies the current condition together with all conditions we've already set up. If such partition exists, then we can leave our newly added condition and move to lower bits. If there is no such condition, then we need to move to lower bits without adding any new conditions. At the end we'll find the maximal value of $X1 + X2$. So, we have a set of conditions and we want to check if there exist at least one partition which satisfies all of them. For each condition for $i$-th bit we'll create an equation over the field $Z_{2}$ with $n$ variables, where the coefficient at the $j$-th variable is equal to the $i$-th bit of the $j$-th number. If some variable is equal to one then we take the corresponding number into the first set, otherwise -- into the second one. This system of equations can be solved with Gaussian elimination. Note that we don't need to solve the complete system from scratch every time we add a new equation. It's sufficient to recalculate the matrix from the previous state, which can be done in $O(NK)$. Here $K$ is the number of equations in the system. Now we need to minimize $X1$ while keeping the value of $X1 + X2$ unchanged. It can be done in the similar way as finding the optimal value of $X1 + X2$. We'll iterate over all bits which are equal to 1 in number $X$ starting from the highest one. For the current bit we'll try to put 0 in the corresponding position of $X1$. If after adding this condition our system of equations becomes incompatible, then we need to put 1 in this position of $X1$. The complexity of this algorithm is $O(NL^{2})$, where $L$ -- is the length of binary notation of the largest number. For further optimization one can use $bitset$ in Gaussian elimination, although it wasn't necessary for getting AC during the contest.
[ "bitmasks", "math" ]
2,700
null
251
E
Tree and Table
Little Petya likes trees a lot. Recently his mother has presented him a tree with $2n$ nodes. Petya immediately decided to place this tree on a rectangular table consisting of 2 rows and $n$ columns so as to fulfill the following conditions: - Each cell of the table corresponds to exactly one tree node and vice versa, each tree node corresponds to exactly one table cell. - If two tree nodes are connected by an edge, then the corresponding cells have a common side. Now Petya wonders how many ways are there to place his tree on the table. He calls two placements distinct if there is a tree node which corresponds to distinct table cells in these two placements. Since large numbers can scare Petya, print the answer modulo $1000000007$ $(10^{9} + 7)$.
If $N = 1$, then the answer is 2. If there is a node with degree greater than 3 in the tree, then the answer is 0. That's because every cell of the table has at most 3 neighbors. If there is no vertex of degree 3 in the tree, then the answer is $2n^{2} - 2n + 4$. This formula can be derieved in natural way during the solution of other parts of the problem. Also, one could write a simple DP to calculate the answer in this case. Anyway, let's prove this formula. At first, let's solve slightly different problem, which will be also used in the solution of main case of the initial problem. We want to find the number of ways to place a tree in which all nodes have degree smaller than 3 on the table so that one node of degree 1 is attached to the upper-left corner of the table (let it be node number 1). It can be shown that if the table has size 2xK, then the number of placements of the tree is equal to $K$. The last formula can be proven by mathematical induction. If $K = 1$ then the above statement is obviously true. Suppose $K > 1$ and let's assume that the table is oriented horizontally so that we have 2 rows and $K$ columns. If we put a vertex adjacent to the first one to the right from upper-left corner then we have only 1 way to complete the placement of the tree. If we put this vertex to the bottom-left corner, than the next vertex should be put to (2, 2) and the problem is reduced to the same one with $K$ smaller by one. We have a recurrent relation $f(K) = f(K - 1) + 1$ and we know that $f(1) = 1$. This means that $f(K) = K$. Let's come back to the initial problem of counting the nymber of ways to put a tree without vertices of degree 3 on the table 2xN. Without loss of generality let's assume that the first vertex has degree 1. We'll consider only placements in which the first vertex is laying in the first row and at the end we'll multiply our answer by 2. If the first vertex is laying in the first or the last column then then there are $N$ ways to complete the tree (see the previous paragraph). If the first vertex is laying in the $i$-th column than there are $i - 1$ ways of placing our tree in which a vertex adjacent to the first one (let it be vertex 2) is laying to the left of it. Also there are $N - i$ ways in which the second vertex is laying to the right of vertex 1. Adding up these values for all columns and multiplying the answer by 2 we get the final formula: $2n^{2} - 2n + 4$. Now we have only one case left in which there exists a vertex of degree 3 in our tree. Let's declare this vertex to be a root. If there are several vertices of degree 3, any of them can be chosen to be a root. We'll assume that the root is laying in the first row and at the end we'll multiply our answer by 2. Obviously, the root should be put to a cell with 3 neighbors. Each descendant of the root should be put either to the left, to the right or to the bottom from the cell which contains the root. Let's fix this ordering (to do this we need to iterate over 6 permutations). Also if the "bottom" son of the root has degree greater than 1, then we'll also fix the ordering of its adjacent vertices (there are 2 ways to do this). Now the column which contains the root is fully occupied. The last statement means that regardless of the way we place the rest of vertices, the ones to the right from the root will stay there. The same for all vertices which lay to the left from the root. Moreover, we have the fixed number of vertices to the left from the root, which means that there's at most one way to place the root on our table. Note that if the number of vertices to the left from the root is odd, then we won't be able to complete the placement. In order to find the number of vertices to the left from the root we need to sum up sizes of subtrees of its left descendant and of the left descendant of its bottom son. So, we have two separate subproblems (for vertices laying to the left from the root and to the right from the root) and for each of them we need to calculate the number of trees to place the rest of our tree in the table. There are only two possible situations: 1) We need to place a subtree with its root in vertex $v$ on the rectangular table in such way that vertex $v$ is laying in the corner (let it be upper-left corner). 2) We need to place subtrees with roots in $v1$ and $v2$ on the rectangular table in such way that vertex $v1$ is laying in the upper-left corner and vertex $v2$ is laying in bottom-left corner. Obviously, each of these two problems has non-zero answer only if total size of subtrees is even. Let's show how to reduce a problem of the second type to a problem of the first type. So, if either $v1$ or $v2$ has two descendants, then the answer is 0. If both of them have one descendant, then we can solve the same problem for their children which'll have the same answer. If both $v1$ and $v2$ have no children, then the answer is 1. At last, if one of these two vertices has 1 descendant and the other vertice doesn't have any descendants, we have a problem of the first type for this only child of vertices $v1$ and $v2$. The only thing left is to solve a problem of the first type. Let $f(v)$ be the number of ways to place a subtree having vertex $v$ as its root on the rectangular table. The size of this table is determined uniquely by the size of subtree. Let's consider two cases: a) Vertex $v$ has degree 2. b) Vertex $v$ has degree 3. In the case when vertex $v$ has degree 2 and there are no vertices of degree 3 in its subtree, then $f(v) = s(x) / 2$, where $s(v)$ is the size of subtree with its root in vertex $v$. We've already proven this formula above. Now let's suppose that there's at least one vertex of size 3 in the subtree with root $v$. If there are several vertices with degree 3, we'll chose the one that is closer to vertex $v$. Let it be vertex $w$. We have 2 possible cases for it: a.1) Path from vertex $v$ to vertex $w$ will go in such way that the vertex which lays before vertex $w$ in this path is located to the left from vertex $w$ on the table. a.2) Path from vertex $v$ to vertex $w$ will go in such way that the vertex which lays before vertex $w$ in this path is located to the top from vertex $w$ on the table. Its easy to show that there's no third option. In each of two cases a.1) and a.2) we'll fix directions of descendants of number $w$ (one direction is taken by the parent of vertex $w$, so there are exactly 2 possible directions). In case if descendant of degree greater than 1 is located in the same column with $w$, we need to fix directions of its descendants, too. After this we have problem of type 1) or 2) to the right of vertex $w$. To the left from $w$ we have a tree which either can't be put on the table or can be put in exactly 1 way. In order to check this we need to look on the length of path from $v$ to $w$ and the size of subtree of grandson of $w$, which is located to the right from $w$ (of course, if it exists). Now we need to sup up answers for all possible variants. So we know how to solve problem of type a), when vertex $v$ has degree w. The only thing left is to solve problem b), when $v$ has degree 3. To do this we need to fix directions of its descendants and after that we'll have either a problem of type 1) or a problem of type 2), which were formulated above. The complexity of solution is $O(N)$.
[ "dfs and similar", "dp", "implementation", "trees" ]
3,000
null
252
A
Little Xor
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of $n$ elements. Petya immediately decided to find there a segment of consecutive elements, such that the $xor$ of all numbers from this segment was maximal possible. Help him with that. The $xor$ operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
Let's iterate over all segments in our array. For each of them we'll find the $xor$ of all its elements. Then we need to output the maximal $xor$ we've seen.
[ "brute force", "implementation" ]
1,100
null
252
B
Unsorting Array
Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of $n$ elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya \textbf{must} swap some two integers even if the original array meets all requirements. Array $a$ (the array elements are indexed from 1) consisting of $n$ elements is called sorted if it meets at least one of the following two conditions: - $a_{1} ≤ a_{2} ≤ ... ≤ a_{n}$; - $a_{1} ≥ a_{2} ≥ ... ≥ a_{n}$. Help Petya find the two required positions to swap or else say that they do not exist.
If all elements in the array are equal then there's no pair of numbers we are looking for. Now we can assume that there exist at least 2 different numbers in the array. Let's iterate over all pairs of different numbers in the array and for each such pair we'll check if it can be the answer. If some pair indeed can be the answer, we'll output it and terminate the program. Otherwise, there is no pair of numbers we are looking for, so we need to output -1. It may seem that the complexity of described algorithm is $O(N^{3})$. Actually it's not true and the real complexity is $O(N)$. One may notice that in every array of length greater than 3 there are at least 3 pairs of different numbers (remember we assumed that there exist at least one pair of different numbers in the array). Note that these 3 pairs lead to 3 different resulting arrays. On the other hand, there are only 2 possible sorted arrays. According to the pigeonhole principle one of these 3 resulting arrays is unsorted.
[ "brute force", "sortings" ]
1,800
null
253
A
Boys and Girls
There are $n$ boys and $m$ girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to $n + m$. Then the number of integers $i$ ($1 ≤ i < n + m$) such that positions with indexes $i$ and $i + 1$ contain children of different genders (position $i$ has a girl and position $i + 1$ has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.
Lets assume that we have more boys than girls (the other case is solved similarly). Then we can construct one of the optimal solutions in the following way: we add pairs consisting of a boy and a girl (BG, in that order) to the end of the line until we don't have girls any more. Then add remaining boys to the end of the line. For instance, with 7 boys and 4 girls we will come to the solution BGBGBGBGBBB.
[ "greedy" ]
1,100
null
253
B
Physics Practical
One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as $n$ measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result $x$, and the largest result $y$, then the inequality $y ≤ 2·x$ must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes. Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.
For each $x$ from 1 to 5000 calculate $count(x)$ - the number of measurements equal to $x$. The iterate over all possible minimal values $m$ (from 1 to 5000). For a fixed $m$ we can easily figure out which numbers we have to erase: we should erase every number $k$ that $k < m$ or $k > 2 \cdot m$. To find out the number of such values in the given sequence, we should sum up values $count(k)$ for all such $k$.
[ "binary search", "dp", "sortings", "two pointers" ]
1,400
null
253
C
Text Editor
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition. As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one? Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written $n$ lines, the $i$-th line contains $a_{i}$ characters (including spaces). If some line contains $k$ characters, then this line overall contains $(k + 1)$ positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers $(r, c)$, where $r$ is the number of the line and $c$ is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line). Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position $(r, c)$, then Vasya pushed key: - "Up": if the cursor was located in the first line ($r = 1$), then it does not move. Otherwise, it moves to the previous line (with number $r - 1$), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position $c$ there, the cursor moves to the last position of the line with number $r - 1$; - "Down": if the cursor was located in the last line ($r = n$), then it does not move. Otherwise, it moves to the next line (with number $r + 1$), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position $c$ there, the cursor moves to the last position of the line with number $r + 1$; - "Right": if the cursor can move to the right in this line ($c < a_{r} + 1$), then it moves to the right (to position $c + 1$). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; - "Left": if the cursor can move to the left in this line ($c > 1$), then it moves to the left (to position $c - 1$). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key. You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position $(r_{1}, c_{1})$ to position $(r_{2}, c_{2})$.
One of the solutions to the problem is breadth-first-search (BFS). Vertices of the graph correspond to all possible pairs ($r, c$), denoting the row and the position of the cursor. Each vertex has at most four arcs leaving it (these arcs correspond to pressing the buttons). So we need to find the shortest path from one vertex to the other. There are at most $10^{7}$ vertices and at most $4 \cdot 10^{7}$ arcs. This problem can also be solved with some greedy observations.
[ "data structures", "dfs and similar", "graphs", "greedy", "shortest paths" ]
1,600
null
253
D
Table with Letters - 2
Vasya has recently started to learn English. Now he needs to remember how to write English letters. He isn't sure about some of them, so he decided to train a little. He found a sheet of squared paper and began writing arbitrary English letters there. In the end Vasya wrote $n$ lines containing $m$ characters each. Thus, he got a rectangular $n × m$ table, each cell of the table contained some English letter. Let's number the table rows from top to bottom with integers from 1 to $n$, and columns — from left to right with integers from 1 to $m$. After that Vasya looked at the resulting rectangular table and wondered, how many subtables are there, that matches both following conditions: - the subtable contains at most $k$ cells with "a" letter; - all letters, located in all four corner cells of the subtable, are equal. Formally, a subtable's definition is as follows. It is defined by four integers $x_{1}, y_{1}, x_{2}, y_{2}$ such that $1 ≤ x_{1} < x_{2} ≤ n$, $1 ≤ y_{1} < y_{2} ≤ m$. Then the subtable contains all such cells $(x, y)$ ($x$ is the row number, $y$ is the column number), for which the following inequality holds $x_{1} ≤ x ≤ x_{2}, y_{1} ≤ y ≤ y_{2}$. The corner cells of the table are cells $(x_{1}, y_{1})$, $(x_{1}, y_{2})$, $(x_{2}, y_{1})$, $(x_{2}, y_{2})$. Vasya is already too tired after he's been writing letters to a piece of paper. That's why he asks you to count the value he is interested in.
Lets iterate over all pairs of rows $i, j$ ($i < j$), that bounds the sub-table from the top and from the bottom. Then for each character $ch$ make a list of such column numbers $k$ that $T[i, k] = T[j, k] = ch$. Consider such list for some fixed character $ch$. All we need to count is the number of pairs $l, r$ ($l < r$) in this list such that the sub-table with corners at $(i, l)$ and $(j, r)$ contains not more than $k$ characters $"a"$. This can be done using two standard techniques: two-pointer method and calculating partial sums.
[ "brute force", "two pointers" ]
2,000
null
253
E
Printer
Let's consider a network printer that functions like that. It starts working at time 0. In each second it can print one page of a text. At some moments of time the printer receives printing tasks. We know that a printer received $n$ tasks. Let's number the tasks by consecutive integers from 1 to $n$. Then the task number $i$ is characterised by three integers: $t_{i}$ is the time when the task came, $s_{i}$ is the task's volume (in pages) and $p_{i}$ is the task's priority. The priorities of all tasks are distinct. When the printer receives a task, the task goes to the queue and remains there until all pages from this task are printed. The printer chooses a page to print each time when it either stops printing some page or when it is free and receives a new task. Among all tasks that are in the queue at this moment, the printer chooses the task with the highest priority and next second prints an unprinted page from this task. You can assume that a task goes to the queue immediately, that's why if a task has just arrived by time $t$, the printer can already choose it for printing. You are given full information about all tasks except for one: you don't know this task's priority. However, we know the time when the last page from this task was finished printing. Given this information, find the unknown priority value and determine the moments of time when the printer finished printing each task.
First lets learn how to simulate the process with all priorities known. We will keep the priority queue of tasks. The task enters the queue when the printer receives this task, and leaves the queue when the printer finishes it. Then every change in the queue happens when one of the two possible events occurs: the printer receives some task or finishes printing some task. Between the consecutive events printer just prints pages from the tasks with the highest priority. So, if we maintain a set of events, the simulation can be done in $O(NlogN)$. To solve the problem, make an obvious observation: the higher priority the task has, the sooner the printer finishes it. Then the required missing priority can be found using binary search. Also we can search the missing priority among $O(N)$ values. The overall complexity is $O(Nlog^{2}(N))$. This problem also has $O(NlogN)$ solution, which will be described later.
[ "binary search", "data structures", "implementation", "sortings" ]
2,200
null
254
A
Cards with Numbers
Petya has got $2n$ cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from $1$ to $2n$. We'll denote the number that is written on a card with number $i$, as $a_{i}$. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.
For each $x$ from 1 to 5000 store a list $L(x)$ of such indexes $i$ that $a_{i} = x$. Then just check that all lists have even size and output the elements of each list in pairs.
[ "constructive algorithms", "sortings" ]
1,200
null
254
B
Jury Size
In 2013, the writers of Berland State University should prepare problems for $n$ Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to $n$. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number $i$ should be prepared by $p_{i}$ people for $t_{i}$ days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it. For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd. In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time.
One of the possible solutions is: for each Olympiad find the period of the preparation. This can be done by iterating the days back from the day of the Olympiad. For each day $d$ of the preparation add $p_{i}$ to the number of distinct jury members that have to work on problems on day $d$. Then the answer is maximum calculated sum over all days. Be careful with the year 2012.
[ "brute force", "implementation" ]
1,500
null
254
C
Anagram
String $x$ is an anagram of string $y$, if we can rearrange the letters in string $x$ and get exact string $y$. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not. You are given two strings $s$ and $t$ of the same length, consisting of uppercase English letters. You need to get the anagram of string $t$ from string $s$. You are permitted to perform the replacing operation: every operation is replacing some character from the string $s$ by any other character. Get the anagram of string $t$ in the least number of replacing operations. If you can get multiple anagrams of string $t$ in the least number of operations, get the lexicographically minimal one. The lexicographic order of strings is the familiar to us "dictionary" order. Formally, the string $p$ of length $n$ is lexicographically smaller than string $q$ of the same length, if $p_{1} = q_{1}$, $p_{2} = q_{2}$, ..., $p_{k - 1} = q_{k - 1}$, $p_{k} < q_{k}$ for some $k$ ($1 ≤ k ≤ n$). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.
Lets denote the number of character $x$ in $s$ by $C_{s}(x)$. Similarly $C_{t}(x)$ is defined. Then the minimum number of changes required to get anagram of $t$ from $s$ is equal to $\textstyle\sum(C_{s t}(x)-C_{t}(x)|}$. Now we need to obtain lexicographically minimum solution. Lets iterate through the positions in $s$ from the left to the right. For a fixed position, look through all characters from 'a' to 'z' and for each character decide whether the optimal answer can contain this character in that position. If it can, put this character in that position and continue with the next position. To check if the given character is suitable quickly, we maintain the values $C_{s}(x)$ and $C_{t}(x)$ while iterating through positions.
[ "greedy", "strings" ]
1,800
null
254
D
Rats
Rats have bred to hundreds and hundreds in the basement of the store, owned by Vasily Petrovich. Vasily Petrovich may have not noticed their presence, but they got into the habit of sneaking into the warehouse and stealing food from there. Vasily Petrovich cannot put up with it anymore, he has to destroy the rats in the basement. Since mousetraps are outdated and do not help, and rat poison can poison inattentive people as well as rats, he chose a radical way: to blow up two grenades in the basement (he does not have more). In this problem, we will present the shop basement as a rectangular table of $n × m$ cells. Some of the cells are occupied by walls, and the rest of them are empty. Vasily has been watching the rats and he found out that at a certain time they go to sleep, and all the time they sleep in the same places. He wants to blow up a grenade when this convenient time comes. On the plan of his basement, he marked cells with sleeping rats in them. Naturally, these cells are not occupied by walls. Grenades can only blow up in a cell that is not occupied by a wall. The blast wave from a grenade distributes as follows. We assume that the grenade blast occurs at time 0. During this initial time only the cell where the grenade blew up gets 'clear'. If at time $t$ some cell is clear, then at time $t + 1$ those side-neighbouring cells which are not occupied by the walls get clear too (some of them could have been cleared before). The blast wave distributes for exactly $d$ seconds, then it dies immediately. \begin{center} {\scriptsize An example of a distributing blast wave: Picture 1 shows the situation before the blast, and the following pictures show "clear" cells by time 0,1,2,3 and 4. Thus, the blast wave on the picture distributes for $d = 4$ seconds.} \end{center} Vasily Petrovich wonders, whether he can choose two cells to blast the grenades so as to clear all cells with sleeping rats. Write the program that finds it out.
Choose arbitrary rat (for say, the leftmost of the upmost). It's cell should be cleared. Make a BFS that never goes further than $d$ from this cell (we will call such a BFS by d-BFS). It will visit approximately $2d^{2}$ cells in the worst case. So, we have to blow the first grenade in one of the visited cells. Lets check every visited cell as a candidate. Make a d-BFS from the candidate cell. Some cells with the rats will not be visited. That means that they should be cleared by the second grenade. Choose arbitrary cell with a rat that was not cleared by the first grenade. Make a d-BFS from it. All cells visited by this BFS are candidates to blow the second grenade. Lets check every such cell. Checking a cell again means making a d-BFS from it. If this BFS visits all cells that were not cleared by the first grenade, that we have found a solution. As every d-BFS visits at most $2d^{2}$, the overall number of steps is approximately $8d^{6}$.
[ "brute force", "dfs and similar", "graphs", "implementation", "shortest paths" ]
2,300
null
254
E
Dormitory
Student Vasya came to study in Berland State University from the country, so he is living in a dormitory. A semester has $n$ days, and in each of those days his parents send him some food. In the morning of the $i$-th day he receives $a_{i}$ kilograms of food that can be eaten on that day and on the next one (then the food goes bad and becomes unfit for consumption). Every day Vasya eats $v$ kilograms of food. It is known that Vasya's parents do not allow him to starve, so there always is enough food for Vasya. Vasya has $m$ friends who sometimes live with him. Let's index the friends from 1 to $m$. Friend number $j$ lives with Vasya from day $l_{j}$ to day $r_{j}$, inclusive. Also, the $j$-th friend requires $f_{j}$ kilograms of food per day. Usually Vasya's friends eat in the canteen, but sometimes generous Vasya feeds some of them. Every day Vasya can feed some friends who live with him this day (or may feed nobody). Every time Vasya feeds his friend, he gives him as much food as the friend needs for the day, and Vasya's popularity rating at the University increases by one. Vasya cannot feed the same friend multiple times in one day. In addition, he knows that eating habits must be regular, so he always eats $v$ kilograms of food per day. Vasya wants so choose whom he will feed each day of the semester to make his rating as high as possible. Originally Vasya's rating is 0 because he is a freshman.
The problem can be solved by dynamic programming: denote as $D(n, r)$ the maximum rating that we can achieve in the first $n$ days with the condition that we have $r$ kilos of food remaining from the day $n - 1$. It is obvious that if we decide to feed $k$ friends on some day, the better way is to feed $k$ friends with the lowest $f_{j}$ (of course we consider only friends that live with Vasya on that day). So we need to sort all available students in the order of increasing $f_{j}$ and try to feed 0, 1, 2, \ldots first students in this order. We have $400^{2}$ states and $400$ transitions from each state.
[ "dp", "implementation" ]
2,100
null