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
⌀ |
|---|---|---|---|---|---|---|---|
65
|
C
|
Harry Potter and the Golden Snitch
|
Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points $(x_{0}, y_{0}, z_{0})$, $(x_{1}, y_{1}, z_{1})$, ..., $(x_{n}, y_{n}, z_{n})$. At the beginning of the game the snitch is positioned at the point $(x_{0}, y_{0}, z_{0})$, and then moves along the polyline at the constant speed $v_{s}$. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point $(P_{x}, P_{y}, P_{z})$ and his super fast Nimbus 2011 broom allows him to move at the constant speed $v_{p}$ in any direction or remain idle. $v_{p}$ is not less than the speed of the snitch $v_{s}$. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry.
|
Check for each segment in the polyline if Harry can catch the snitch in it. Note that since $v_{p} \ge v_{s}$, if Harry can catch the snitch at some moment of time, he can catch it at any later moment. He can just follow snitch along its trajectory. So use binary search in each segment. About problems with EPS that participants got. The problems may be caused by 1) some EPS in the condition: while (leftTime + EPS < rightTime) <do binary search>. The task was to output with a fixed accurancy not only the time, but also the point coordinates. If the difference between the time and the right one is less than EPS, the difference between coordinates may be significantly larger. In such cases you should compare not arguments of a function, but values of the function with EPS. Or the way that I usually follow and that once was not liked by the teacher of numerical methods - to implement some fixed number of iterations of the binary search (say, 60). 2) EPS in comparison of time moments inside the binary search like this: if (currentTime + addTime > distance / potterSpeed - EPS) rightTime = currentTime; else leftTime = currentTime; Here it is better to remove EPS at all. Or to put EPS significantly smaller than the required accurancy for printing the point. (Code fragments are from Egor's solution.) Thus, there was no crime with severe limitations. Probably for such problems extreme accurancy tests should be in pretests? It is about principles of pretests making again. UPD. The problem has an analytical solution too. Consider the i-th segment. Let $(x_{i}, y_{i}, z_{i})$ and $(x_{None}, y_{None}, z_{None})$ be its ends, and let $t_{i}$ be the time required for the snitch to reach the beginning of the segment. Then at the moment t the snitch will be at the point (x, y, z), $x = x_{i} + (x_{None} - x_{i})(t - t_{i}) / T_{i}$, $y = y_{i} + (y_{None} - y_{i})(t - t_{i}) / T_{i}$, $z = z_{i} + (z_{None} - z_{i})(t - t_{i}) / T_{i}$, $T_{i}$ is a time necessary for snitch to overcome the segment. To catch the snitch at the point (x, y, z), Harry have to overcome the distance that squared is equal to $(x - P_{x})^{2} + (y - P_{y})^{2} + (z - P_{z})^{2}$ for the time t. It is possible if $(x - P_{x})^{2} + (y - P_{y})^{2} + (z - P_{z})^{2} \le (tv_{p})^{2}$. To find the minimal proper moment t, solve the corresponding quadratic equation.
|
[
"binary search",
"geometry"
] | 2,100
| null |
65
|
D
|
Harry Potter and the Sorting Hat
|
As you know, Hogwarts has four houses: Gryffindor, Hufflepuff, Ravenclaw and Slytherin. The sorting of the first-years into houses is done by the Sorting Hat. The pupils are called one by one in the alphabetical order, each of them should put a hat on his head and, after some thought, the hat solemnly announces the name of the house the student should enter.
At that the Hat is believed to base its considerations on the student's personal qualities: it sends the brave and noble ones to Gryffindor, the smart and shrewd ones — to Ravenclaw, the persistent and honest ones — to Hufflepuff and the clever and cunning ones — to Slytherin. However, a first year student Hermione Granger got very concerned about the forthcoming sorting. She studied all the literature on the Sorting Hat and came to the conclusion that it is much simpler than that. If the relatives of the student have already studied at Hogwarts, the hat puts the student to the same house, where his family used to study. In controversial situations, when the relatives studied in different houses or when they were all Muggles like Hermione's parents, then the Hat sorts the student to the house, to which the least number of first years has been sent at that moment. If there are several such houses, the choice is given to the student himself. Then the student can choose any of the houses, to which the least number of first years has been sent so far.
Hermione has already asked the students that are on the list before her about their relatives. Now she and her new friends Harry Potter and Ron Weasley want to find out into what house the Hat will put Hermione.
|
Let $S_{i}$ be a set of all possible assignments of the first $i$ students to the houses, that is a set of tuples $(a_{1}, a_{2}, a_{3}, a_{4})$, where $a_{1}$ is a number of students sent to Gryffindor, $a_{2}$ - to Ravenclaw, etc. It's intuitively clear that these sets will not be large. So you can get $S_{None}$ from $S_{i}$ in a trivial way, and get finally $S_{n}$, and determine the answer from it. What is a rigorous proof of the algorithm? Let us have a set $S = {(a^{i}_{1}, a^{i}_{2}, a^{i}_{3}, a^{i}_{4})}_{None}$. Represent its elements as $a^{i}_{j} = b_{j} + x^{i}_{j}$, $x^{i}_{j} \ge 0$, where $b_{j}$ are maximal possible, i.e. there is i for each j such that $x^{i}_{j} = 0$. Let the tuple $(b_{1}, b_{2}, b_{3}, b_{4})$ be called the base part of S, and the set ${(x^{i}_{1}, x^{i}_{2}, x^{i}_{3}, x^{i}_{4})}_{None}$ be called the variant part of S. Initially for $S_{0}$ both base and variant parts are zeroes. Let us see how base and variant parts change when a current student is added. If a house is fixed for the student, only the base part changes. It increases by 1 at the position corresponding to the house. In particular, it follows that a set with every base part can be obtained (since the string given in the input can contain every combination of symbols G, H, R, S). If the current symbol in the string is '?', it can influence both base and variant parts. For example, for the string '????' we have: $S_{0} = {(0 + 0, 0 + 0, 0 + 0, 0 + 0)}$, $S_{1} = {(0 + 1, 0 + 0, 0 + 0, 0 + 0), (0 + 0, 0 + 1, 0 + 0, 0 + 0), (0 + 0, 0 + 0, 0 + 1, 0 + 0), (0 + 0, 0 + 0, 0 + 0, 0 + 1)}$, $S_{2} = {(0 + 1, 0 + 1, 0 + 0, 0 + 0), (0 + 1, 0 + 0, 0 + 1, 0 + 0), (0 + 1, 0 + 0, 0 + 0, 0 + 1), (0 + 0, 0 + 1, 0 + 1, 0 + 0), (0 + 0, 0 + 1, 0 + 0, 0 + 1), (0 + 0, 0 + 0, 0 + 1, 0 + 1)}$, $S_{3} = {(0 + 1, 0 + 1, 0 + 1, 0 + 0), (0 + 1, 0 + 1, 0 + 0, 0 + 1), (0 + 1, 0 + 0, 0 + 1, 0 + 1), (0 + 0, 0 + 1, 0 + 1, 0 + 1)}$, $S_{4} = {(1 + 0, 1 + 0, 1 + 0, 1 + 0)}$. Let us investigate the question of what species a variant part may have. It can be analyzed independently from a base one, taking into account that a base part can be any. Consider a directed graph with vertices corresponding to variant parts and with edges determined by the existence of at least one base part that let go from one variant part to another. We are interested only in vertices reachable from ${(0, 0, 0, 0)}$. Proposition. For all the vertices reachable from zero the following properties hold (1) $x^{i}_{j} \le 2$, (2) $k \le 13$. Let us prove that all the vertices not having the properties (1) and (2) are unreachable from zero. Consider a variant part with the property (1). To get all edges going from it you have to try all possible base parts. Note that base parts, that consist of the numbers 0, 1, 2, 3 and contain at lest one 0, are enough. Indeed, base part influence which elements are minimal, and 1 will be added to them. A base part can be always normed to contain at least one 0. If a base part contains numbers greater than 3, then the corresponding positions will never be minimal (since 4+0 > 0+2) and they can be changed equivalently by 3 (3+0 > 0+2). Unfortunately, my attempts to deal with cases by hand were unsuccessful, so I wrote the program that traverse the described graph. Starting from 0, it builds edges trying only "small" base parts described in the previous paragraph. As a result, the program obtains all the reachable variant parts (there is a little more than 1000 of them) and check (1) and (2) for them. In addition, the program helps to construct a test with $k = 13$.
|
[
"brute force",
"dfs and similar",
"hashing"
] | 2,200
| null |
65
|
E
|
Harry Potter and Moving Staircases
|
Harry Potter lost his Invisibility Cloak, running from the school caretaker Filch. Finding an invisible object is not an easy task. Fortunately, Harry has friends who are willing to help. Hermione Granger had read "The Invisibility Cloaks, and Everything about Them", as well as six volumes of "The Encyclopedia of Quick Search of Shortest Paths in Graphs, Network Flows, the Maximal Increasing Subsequences and Other Magical Objects". She has already developed a search algorithm for the invisibility cloak in complex dynamic systems (Hogwarts is one of them).
Hogwarts consists of $n$ floors, numbered by integers from $1$ to $n$. Some pairs of floors are connected by staircases. The staircases may change its position, moving exactly one end. Formally the situation is like this: if a staircase connects the floors $a$ and $b$, then in one move it may modify its position so as to connect the floors $a$ and $c$ or $b$ and $c$, where $c$ is any floor different from $a$ and $b$. Under no circumstances the staircase can connect a floor with itself. At the same time there can be multiple stairs between a pair of floors.
Initially, Harry is on the floor with the number $1$. He does not remember on what floor he has lost the cloak and wants to look for it on each of the floors. Therefore, his goal is to visit each of $n$ floors at least once. Harry can visit the floors in any order and finish the searching at any floor.
Nowadays the staircases move quite rarely. However, Ron and Hermione are willing to put a spell on any of them to help Harry find the cloak. To cause less suspicion, the three friends plan to move the staircases one by one, and no more than once for each staircase. In between shifting the staircases Harry will be able to move about the floors, reachable at the moment from the staircases, and look for his Invisibility Cloak. It is assumed that during all this time the staircases will not move spontaneously.
Help the three friends to compose a searching plan. If there are several variants to solve the problem, any valid option (not necessarily the optimal one) will be accepted.
|
Consider a graph with floors as vertices and staircases as edges. It is clear that Harry can visit the whole connected component in which he is currently located. Every edge can be used to reach a new vertex for not more than two times. If a connected component contains n vertices and m edges, only n - 1 edges are used to reach a new vertex during its traversal. The remaining m - n + 1 edges are not used to reach a new vertex in their initial placement. So they will be used to reach a new vertex not more than once. So using edges of only one connected component you can reach no more than n - m + 1 new vertices. Totally there are not more than $1\,+\,\succ_{i=1}^{k}(n_{k}\,+\,m_{k}\,-\,1)\,=\,1\,+\,m\,-\,k\,+\,m$ reachable vertices. If m < k - 1, it is impossible to visit all the vertices. We show that otherwise (m >= k - 1), if the degree of the vertex 0 is different from zero, it is possible to visit all the vertices. In other words, there is such a traversal that every edge can be moved. Use depth-first search for the current component. If a current edge goes to an already visited vertex, move it to a new component and traverse it recursively. If a current edge goes to a new vertex, after you visit this vertex and go back, you also can move this edge to a new component. As a result each edge can be moved and used again, if you reach all the components. If a component contains at least one edge, you can go from it to the next one. First visit components with edges, and you will visit them all and by the inequality (m >= k - 1) there are enough edges to visit all the isolated vertices. If the degree of the vertex 1 is zero, you can not start a traversal before you move some edge to it. After that you can go by this edge and remove it with the vertex 1 from the graph, becase you can not use this edge once more. If the chose edge is a bridge, you get k connected components and m - 1 egdes. If it is not a bridge, you get k - 1 components and m - 1 edges. In the first case the inequality m >= k - 1 turns m >= k. In the second case - m >= k - 1. So if not all the edges are bridges, you should not take a bridge. If they all are bridges, you should disconnect an edge from a vertex of degree >= 2 not to came back to the initial situation with the zero degree of the first vertex. If there is no such vertex, it is easy to check that there is no solution.
|
[
"dfs and similar",
"implementation"
] | 2,900
| null |
66
|
A
|
Petya and Java
|
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: "Which integer type to use if one wants to store a positive integer $n$?"
Petya knows only 5 integer types:
1) \textbf{byte} occupies 1 byte and allows you to store numbers from $ - 128$ to $127$
2) \textbf{short} occupies 2 bytes and allows you to store numbers from $ - 32768$ to $32767$
3) \textbf{int} occupies 4 bytes and allows you to store numbers from $ - 2147483648$ to $2147483647$
4) \textbf{long} occupies 8 bytes and allows you to store numbers from $ - 9223372036854775808$ to $9223372036854775807$
5) \textbf{BigInteger} can store any integer number, but at that it is not a primitive type, and operations with it are much slower.
For all the types given above the boundary values are included in the value range.
From this list, Petya wants to choose the smallest type that can store a positive integer $n$. Since BigInteger works much slower, Peter regards it last. Help him.
|
In this problem you should answer to 4 questions: 1) Can we use type byte to store N? 2) Can we use type short to store N? 3) Can we use type int to store N? 4) Can we use type long to store N? We should check these conditions in the given order. If all these conditions are wrong, the answer is BigInteger. The simplest way to check these conditions is to store numbers as strings and write a function to compare such strings. In Java you can use type BigInteger.
|
[
"implementation",
"strings"
] | 1,300
| null |
66
|
B
|
Petya and Countryside
|
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle $1 × n$ in size, when viewed from above. This rectangle is divided into $n$ equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.
Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a $1 × 5$ rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:
As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.
|
Try to check all possibilities for creation artificial rain and calculate how many sections contain water. The maximal answer from all these possibilities is the answer for the problem. To calculate the answer for the given position we should check how many sections are to the left and to the right of the given section receive water. The complexity of this algorithm is O(N^2).
|
[
"brute force",
"implementation"
] | 1,100
| null |
66
|
D
|
Petya and His Friends
|
Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to $n$.
Let us remind you the definition of the greatest common divisor: $GCD(a_{1}, ..., a_{k}) = d$, where $d$ represents such a maximal positive number that each $a_{i}$ ($1 ≤ i ≤ k$) is evenly divisible by $d$. At that, we assume that all $a_{i}$'s are greater than zero.
Knowing that Petya is keen on programming, his friends has agreed beforehand that the $1$-st friend gives $a_{1}$ sweets, the $2$-nd one gives $a_{2}$ sweets, ..., the $n$-th one gives $a_{n}$ sweets. At the same time, for any $i$ and $j$ ($1 ≤ i, j ≤ n$) they want the $GCD(a_{i}, a_{j})$ not to be equal to $1$. However, they also want the following condition to be satisfied: $GCD(a_{1}, a_{2}, ..., a_{n}) = 1$. One more: all the $a_{i}$ should be distinct.
Help the friends to choose the suitable numbers $a_{1}, ..., a_{n}$.
|
Consider N distinct prime numbers: p1, p2, \dots , pn. Let A=p1*p2* \dots *pn. Then, easy to see, that the numbers A/p1, A/p2, \dots , A/pn can be considered as the answer. The special case is when N=2. In this case there is no answer. We can see that this solution needs long arithmetic. If we choose first n prime numbers as p1, p2, \dots , pn then the maximal number in the answer for all N<=50 contains less than 100 digits. Of course, there are other solutions. For example, if N=3 numbers 15, 10, 6 are the answer, and for N>3 numbers 15, 10, 6, 6*2, 6*3, \dots , 6*(N-2) are the answer.
|
[
"constructive algorithms",
"math",
"number theory"
] | 1,700
| null |
66
|
E
|
Petya and Post
|
Little Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then he must drive in the given car exactly one round along the circular road and return to the starting post office (the uncle can drive along the circle in any direction, counterclockwise or clockwise). Besides, since the car belongs to the city post, it should also be fuelled with gasoline only at the Post Office stations.
The total number of stations equals to $n$. One can fuel the car at the $i$-th station with no more than $a_{i}$ liters of gasoline. Besides, one can fuel the car no more than once at each station. Also, the distance between the $1$-st and the $2$-nd station is $b_{1}$ kilometers, the distance between the $2$-nd and the $3$-rd one is $b_{2}$ kilometers, ..., between the $(n - 1)$-th and the $n$-th ones the distance is $b_{n - 1}$ kilometers and between the $n$-th and the $1$-st one the distance is $b_{n}$ kilometers. Petya's uncle's high-tech car uses only one liter of gasoline per kilometer. It is known that the stations are located so that the sum of all $a_{i}$ is equal to the sum of all $b_{i}$. The $i$-th gas station and $i$-th post office are very close, so the distance between them is $0$ kilometers.
Thus, it becomes clear that if we start from some post offices, then it is not always possible to drive one round along a circular road. The uncle faces the following problem: to what stations can he go in the morning to be able to ride exactly one circle along the circular road and visit all the post offices that are on it?
Petya, who used to attend programming classes, has volunteered to help his uncle, but his knowledge turned out to be not enough, so he asks you to help him write the program that will solve the posed problem.
|
First of all we divide our problem into 2 parts: consider stations from which we can start if we are moving in the clockwise direction and stations from which we can start if we are moving in the counterclockwise direction. Obviously, if we know the solution of one of these problems, we know the solution of another problem. So, we may assume that stations are located in the counterclockwise order and we are moving in the counterclockwise direction. Consider the following differences: D1=a1-b1, D2=(a1+a2)-(b1+b2), D3=(a1+a2+a3)-(b1+b2+b3), \dots Dn=(a1+a2+ \dots +an)-(b1+b2+ \dots +bn); Obviously if one of Di's is less than a zero, then we cannot drive one round along the road. Let D = min(Di) - we will use it later. Obviously, if D<0 then the first station cannot be the start station. Now, we can check with complexity O(n) whether the first station can be used as the starting point. Next, we want to show how we can check this for the second station with complexity O(1). To show this, consider: E1=D1-(a1-b1), E2=D2-(a1-b1), \dots En=Dn-(a1-b1). Next, substitute Di in these equalities. We get the following: E1=(a1-b1)-(a1-b1)=0=(a2+a3+ \dots +an+a1)-(b2+b3+ \dots +bn+b1) - (a1+ \dots +an=b1+ \dots +bn=X) E2=(a1+a2)-(b1+b2)-(a1-b1)=a2-b2 E3=(a1+a2+a3)-(b1+b2+b3)-(a1-b1)=(a2+a3)-(b2+b3) \dots En=(a1+a2+ \dots +an)-(b1+b2+ \dots +bn)-(a1-b1)=(a2+ \dots +an)-(b2+ \dots +bn) But it's easy to see that number E1 has the same meaning for the second station as number D1 for the first one. So, we just have to check min(Ei)>=0. But Ei=Di-(a1-b1), so we have to check min(Di-(a1-b1))>=0. Now, we can see that if min(Di)=Dk, then min(Di-(a1-b1))=Dk-(a1-b1). So, if we know Dk, that we can check whether the second station can be the starting point with complexity O(1). Similarly, we can check this for the third, the fourth, \dots , the nth stations. Now we should check the same things but assuming that the car is moving in the clockwise direction.
|
[
"data structures",
"dp"
] | 2,000
| null |
67
|
A
|
Partial Teacher
|
A teacher decides to give toffees to his students. He asks $n$ students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.
He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.
It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
|
Let the student at position 'x' receives 't' toffees Initially t=1 and temp=1 Now move towards RIGHT till you encounter a 'R' or end of string , if in the path 'L' is encountered increment t by 1.Following code performs the same : Now if temp is greater than t ; t is initialised as temp and temp as 1. Now move towards LEFT till you encounter a 'L' or beginning of string , if in the path 'R' is encountered increment by 1. Now if temp is greater than t ; t is initialised as temp. 't' is the required number of toffees thus obtained.
|
[
"dp",
"graphs",
"greedy",
"implementation"
] | 1,800
|
#include<iostream>
using namespace std;
int main()
{
int n,ans[1000],temp,i,j;
fill(ans,ans+1000,0);
char s[1000];
cin>>n;
cin>>s;
for(i=0;i<n;i++)
{
ans[i]=1;
temp=1;
for(j=i;j<n;j++)
{
if(s[j]=='R')
break;
else if(s[j]=='L')
temp++;
}
if(temp>ans[i])
ans[i]=temp;
temp=1;
for(j=i-1;j>=0;j--)
{
if(s[j]=='L')
break;
else if(s[j]=='R')
temp++;
}
if(temp>ans[i])
ans[i]=temp;
}
for(i=0;i<n;i++)
cout<<ans[i]<<" ";
return 0;
}
|
67
|
B
|
Restoration of the Permutation
|
Let $A = {a_{1}, a_{2}, ..., a_{n}}$ be any permutation of the first $n$ natural numbers ${1, 2, ..., n}$. You are given a positive integer $k$ and another sequence $B = {b_{1}, b_{2}, ..., b_{n}}$, where $b_{i}$ is the number of elements $a_{j}$ in $A$ to the left of the element $a_{t} = i$ such that $a_{j} ≥ (i + k)$.
For example, if $n = 5$, a possible $A$ is ${5, 1, 4, 2, 3}$. For $k = 2$, $B$ is given by ${1, 2, 1, 0, 0}$. But if $k = 3$, then $B = {1, 1, 0, 0, 0}$.
For two sequences $X = {x_{1}, x_{2}, ..., x_{n}}$ and $Y = {y_{1}, y_{2}, ..., y_{n}}$, let $i$-th elements be the first elements such that $x_{i} ≠ y_{i}$. If $x_{i} < y_{i}$, then $X$ is lexicographically smaller than $Y$, while if $x_{i} > y_{i}$, then $X$ is lexicographically greater than $Y$.
Given $n$, $k$ and $B$, you need to determine the lexicographically smallest $A$.
|
For k=1, the given sequence is called Table of Inversions. We notice that if i>j, relative position of i effects the b_j while placing of j does not effect b_i. For this value of k, and sequnce {b_1, b_2, ..., b_n}, we first place n in the permutation. Then we chose (n-1) and check whether n-1 is 0 or 1. If its 0, It lies to the right of n, otherwise to the left of n. Similarly, we proceed for all values from n to 1. For k=1, there is only one possible permutation. But, when value of k is increased, b_(n-k+1), b_(n-k+2), ..., b_n are all 0. Since we need to find the lexicographically smallest permutation, we insert values from (n-k+1) to n in ascending order first. Then for each value i from n-k to 1, we choose first location in the permutation such that b_i is satisfied. Table of inversions finds application in Sorting where it is easy to represent the permutation using this.
|
[
"greedy"
] | 1,800
|
#include <stdio.h>
int main()
{
int n,k,a[1002],b[1002],i,j,temp;
scanf("%d%d",&n;,&k;);
for(i=1;i<=n;i++)
{
scanf("%d",&b;[i]);
}
for(i=k;i>=1;i--)
a[i] = n-i+1;
for(i=n-k;i>=1;i--)
{
temp = b[i];
for(j=n-i;j>=1 && temp>0;j--)
{
if(a[j]>=i+k)
temp--;
a[j+1] = a[j];
}
a[j+1] = i;
}
for(i=n;i>=1;i--)
printf("%d ",a[i]);
printf("
");
}
|
67
|
C
|
Sequence of Balls
|
You are given a sequence of balls $A$ by your teacher, each labeled with a lowercase Latin letter 'a'-'z'. You don't like the given sequence. You want to change it into a new sequence, $B$ that suits you better. So, you allow yourself four operations:
- You can insert any ball with any label into the sequence at any position.
- You can delete (remove) any ball from any position.
- You can replace any ball with any other ball.
- You can exchange (swap) two adjacent balls.
Your teacher now places time constraints on each operation, meaning that an operation can only be performed in certain time. So, the first operation takes time $t_{i}$, the second one takes $t_{d}$, the third one takes $t_{r}$ and the fourth one takes $t_{e}$. Also, it is given that $2·t_{e} ≥ t_{i} + t_{d}$.
Find the minimal time to convert the sequence $A$ to the sequence $B$.
|
This is problem is an extension to the problem of String Edit Distance where you have to find the minimum cost of converting one string to another using only the following operations: 1) insert 2) delete 3) modify This problem has an extra operation of exchanging adjacent characters. It is similar to the Damerau Levenshtein distance where the operations have a fixed weight of 1. The pseudocode of the algorithm is: INF = a.length + b.length; H[0][0] = INF; // H is 2-D matrix of size (a.length+2)*(b.length+2) for(i = 0; i<=a.length; ++i) {H[i+1][1] = i; H[i+1][0] = INF;} for(j = 0; j<=b.length; ++j) {H[1][j+1] = j; H[0][j+1] = INF;} DA = new Array(C); //here C is the size of alhpabet set, here 'a' to 'z' } for(d = 0; d This finds application in spell checkers, in biology to measure the variation between DNA.
|
[
"dp"
] | 2,600
|
#include<stdio.h>
#include<string.h>
#include <iostream>
#define MAX 5010
using namespace std;
int main()
{
char A[MAX],B[MAX];
int length_A,length_B,INF,wd,wi,ws,wc,H[MAX+2][MAX+2],i,j,DA[MAX+10],d,DB,i1,j1,C,min[4],k,testcase;
//scanf("%d%d%d%d",&wi;,&wd;,&wc;,&ws;);
//scanf("%s%s",A,B);
//printf("%s
%s
",A,B);
cin>>wi>>wd>>wc>>ws;
//cout<<wi<<" "<<wd<<" "<<wc<<" "<<ws<<" ";
cin>>A>>B;
//cout<<A<<" "<<B<<" ";
length_A = strlen(A);
length_B = strlen(B);
//for(int i=0;i<length_B;++i)
//printf("%c",B[i]);
//cout<<endl;
//printf("%s
",B);
INF = length_A*wd + length_B*wi + 1;
H[0][0] = INF;
//printf("%s
",B);
for(i=0;i<=length_A;i++)
{
H[i+1][1] = i*wd;
H[i+1][0] = INF;
}
//printf("%s
",B);
for(j=0;j<=length_B;j++)
{
H[1][j+1] = j*wi;
H[0][j+1] = INF;
}
//printf("%s
",B);
for(d=0;d<=MAX;d++)
DA[d]=0;
//printf("hahah %s
",B);
for(i=1;i<=length_A;i++)
{
DB=0;
//printf("%s
",B);
for(j=1;j<=length_B;j++)
{
//cout<<A[i-1]<<B[j-1]<<endl;
i1=DA[(int)(B[j-1])-97];
j1=DB;
//if(((int)(A[i-1])-97)==((int)(B[j-1])-97))
//d=0;
if ( A[i-1]==B[j-1])
d=0;
else
d=wc;
//cout<<d<<endl;
if(d==0)
DB=j;
int op=0;
min[0]=H[i][j]+d;
min[1]=H[i+1][j]+wi;
min[2]=H[i][j+1]+wd;
min[3]=H[i1][j1]+(i-i1-1)*wd+ws+(j-j1-1)*wi;
H[i+1][j+1]=min[0];
for(k=1;k<4;k++)
{
if(H[i+1][j+1]>min[k]){
H[i+1][j+1]=min[k];
op=k;
}
}
/*switch(op){
case 0:printf("c ");break;
case 1:printf("i ");break;
case 2:printf("d ");break;
case 3:printf("t ");break;
}*/
}
DA[(A[i-1])-97]=i;
//printf("
");
}
//printf("%d
",H[length_A+1][length_B+1]);
cout<<H[length_A+1][length_B+1]<<endl;
/*int x=length_A+1,y=length_B+1;
for( i=0;i<=x;++i){
for( j=0;j<=y;++j)
printf("%d ",H[i][j]);
printf("
");
}
* */
//}
}
|
67
|
D
|
Optical Experiment
|
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for $n$ rays is as follows.
There is a rectangular box having exactly $n$ holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line.
Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".
Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
|
For a given set of n rays, we can prepare the graph, having exactly n nodes. The n nodes represent the rays, numbered from 1 to n. There is an edge between the ith and jth node, if ith ray intersect the jth ray. A Clique of a graph is a complete subgraph. For this graph, the problem requires to find the Clique number, i.e. the number of nodes in the largest clique of that graph. The graph generated in this problem is permutation graph. The Clique number of a permutation grpah is Largest decreasing subsequence of the given permutation. By using the given two permutations, we can generate the 2 new permutations of n, such that 1st sequence is in the ascending order, and the second sequence is the permutation of n. For preparing 1st permutation to be in ascending order, we replace the ith ray in jth hole of 1st permutation by value j and replace the ith ray in second sequence by value j. So, now we have to calculate the Largest decreasing subsequence of the second sequence, which can be calculated in O(n log(n)) time complexity. This finds application in DNA computing and Adiabatic Quantum Computation.
|
[
"binary search",
"data structures",
"dp"
] | 1,900
|
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
using namespace std;
void find_lis(vector<int> &a;, vector<int> &b;)
{
vector<int> p(a.size());
int u, v;
b.push_back(0);
for (int i = 1; i < a.size(); i++)
{
if (a[b.back()] > a[i])
{
p[i] = b.back();
b.push_back(i);
continue;
}
for (u = 0, v = b.size()-1; u < v;)
{
int c = (u + v) / 2;
if (a[b[c]] > a[i])
u=c+1;
else
v=c;
}
if (a[i] > a[b[u]])
{
if (u > 0)
p[i] = b[u-1];
b[u] = i;
}
}
for (u = b.size(), v = b.back(); u--; v = p[v])
b[u] = v;
}
int main()
{
int n;
scanf("%d",&n;);
int x,y,A[n],B[n],a[n];
for(int i=1;i<=n;i++)
{
scanf("%d",&x;);
A[x]=i;
}
for(int i=1;i<=n;i++)
{
scanf("%d",&x;);
B[x]=i;
}
for(int i=1;i<=n;i++)
a[B[i]-1]=A[i];
vector<int> seq(a, a+sizeof(a)/sizeof(a[0]));
vector<int> lis;
find_lis(seq, lis);
printf("%d
",lis.size());
return 0;
}
|
67
|
E
|
Save the City!
|
In the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away from the uncorrupted part, the crimes could be stopped. So, they are trying to set up a compound where they can keep the corrupted people. To ensure that the criminals don't escape the compound, a watchtower needs to be set up, so that they can be watched.
Since the people of Aalam-Aara aren't very rich, they met up with a merchant from some rich town who agreed to sell them a land-plot which has already a straight line fence $AB$ along which a few points are set up where they can put up a watchtower. Your task is to help them find out the number of points on that fence where the tower can be put up, so that all the criminals can be watched from there. Only one watchtower can be set up. A criminal is watchable from the watchtower if the line of visibility from the watchtower to him doesn't cross the plot-edges at any point between him and the tower i.e. as shown in figure 1 below, points $X$, $Y$, $C$ and $A$ are visible from point $B$ but the points $E$ and $D$ are not.
\begin{center}
Figure 1
\end{center}
\begin{center}
Figure 2
\end{center}
Assume that the land plot is in the shape of a polygon and coordinate axes have been setup such that the fence $AB$ is parallel to $x$-axis and the points where the watchtower can be set up are the integer points on the line. For example, in given figure 2, watchtower can be setup on any of five integer points on $AB$ i.e. $(4, 8)$, $(5, 8)$, $(6, 8)$, $(7, 8)$ or $(8, 8)$. You can assume that no three consecutive points are collinear and all the corner points other than $A$ and $B$, lie towards same side of fence $AB$. The given polygon doesn't contain self-intersections.
|
The problem is to find out the total number of points on the segment AB such that the whole polygon(compound) is watchable from it. It can be observed that a straight line segment XY is fully visible from another straight line segment PQ if the point X is visible from points P and Q, and point Y is also visible from points P and Q. So, the points on which watchtower can be setup will always consist of a range of integer points on AB. Also, to check if all the points on the polygon from a range of points, it is only needed to check all the vertices are visible from the range. In a naive brute force approach, we can proceed from A to B iterating by unit distance each time and checking if the all the other vertices of polygon are visible from it.or we can find for each vertex of polygon, the maximum range on AB, from which it is visible and in the take the intersection of all the ranges obtained. To find the range of each of the vertex, it is needed to check if the line visibility intersects any other edge in a way that it goes outside the polygon. This results in the complexity of O(kn) where k is the number of integral points on AB. Since, 0<=k<=1000000 and 3<=n<=1000, it will take 109 counts. Some very critical cases need to be taken care of which make the brute force even more complex.For e.g. the cases mentioned in the figure 1 in question has one of them. When it is checked whether the line of visibility for a point intersects another edge of the polygon, it should be taken care of that the point of intersection isn't the end point of an edge in case line of visibility is completely inside the polygon. This gives rise to another case in which the line of visibility is outside the polygon as for BD in the figure 1 in the question above. It can be done by checking if it the turns CBA and CBD are both either right turns or left turns. Main algorithm to find the number of points first finds the left intercept and right intercept for each vertex of polygon on AB in linear time. Right intercept a vertex X on AB is given by the rightmost point on AB from which the vertex X is visible.Similarly, left intercept is given by the leftmost point on AB from which the vertex X is visible. To find the right and left intercepts for the vertices, two scans are performed on the polygon, one from right to left as in along BCD..A and one along left to right as in along A..DCB. In each scan,the algorithm uses a stack to keep track of what can be said to be the internal convex hull for the polygon between point B and another vertex X of polygon for which the intercept is to be calculated. To calculate the intercept, we just need to find the nearest vertex Y on convex hull to X and extend XY to intersect AB as shown in figure 3 below. If the point of lies between A and B, then the point X is visible,otherwise it is not. To find the convex hull, the algorithm uses the concept that the turns on the hull will always be right or left depending on whether its left or right scan. Given three points A(x1,y1), B(x2,y2) and C(x3,y3), S is defined S = x3*(y1-y2) + y3*(x2-x1) + y2*x1 - y1*x2 The turn ABC is a left turn if S is positive, a right turn if S is negative and collinear if S=0. The pseudocode for the procedure to find the right intercepts for the points is given below: procedure RIGHTSCAN 1) (Initialize) r = STACK(1) = 2; s = STACK(2) = 3; t = 4; v = 2; u = 1; top = 2; 2) (See if t is contained in the convex path so far) x = s - 1; if rst is left turn and xst is right turn, then terminate with No Visibility; 3) (If rst is right turn, backtrack the stack to make the path convex) while top!= -1 and rst is right turn do top = top - 1; s = STACK(top); if top != -1 r = STACK(top-1); end; 4) (Compute right intercept and test whether it lies on AB) Compute right intercept rt of line segment from through s with the line through AB; If rt does not lie on AB, terminate with No Visibility; 5) (Store t into stack and move to next vertex) top = top + 1; STACK(top) = t; r = s; s = t; t = t + 1; if t != n go to step 2 Left Scan can be done similarly. So, now the main algorithm can be given by: procedure VISIBILITY call RIGHTSCAN call LEFTSCAN for i = 1 to n if ri is left of li, terminate with no possible solutions r=p2 l=p1 for i = 2 to n-1 if ri is to left of r r=ri if li is to right of l l=li if l is to left of r print the number of integer points from l to r else terminate with no visibility This finds application in surveillance and Robot control, Automated Cartography, Image Processing.
|
[
"geometry"
] | 2,500
|
#include <iostream>
#include <stack>
#include <stdlib.h>
#include <math.h>
using namespace std;
#define EPS 1E-9
struct Point
{
long double x,y;
};
long double Left, Right;
int up;
int RST(Point r,Point s,Point t)
{
long double val = t.x*(r.y-s.y) + t.y*(s.x - r.x) + r.x*s.y - r.y*s.x;
if(val < 0)
return -1;
return 1;
}
int RightScan(Point *a, int n)
{
stack<int> st;
int r,s,t,u,v,x;
r=1;
st.push(r);
s = 2;
st.push(s);
t=3;
u=n; v=1;
while(t!=n)
{
x=s-1;
if(RST(a[r],a[s],a[t])>0 && RST(a[x],a[s],a[t])<0)
{cout<<"0
"; return 0;}
while(st.size()!=1 && RST(a[r],a[s],a[t])<0)
{
st.pop();
s = st.top();
if(st.size()!=1)
{
int temp = st.top();
st.pop();
r = st.top();
st.push(temp);
}
}
long double inx;
if(a[t].y-a[s].y < EPS && a[s].y-a[t].y < EPS)
{cout<<"0
"; return 0;}
inx = ((a[s].x - a[t].x)*(a[0].y-a[t].y)/(a[s].y-a[t].y)) + a[t].x;
if(up==-1)
{
if(inx > (a[0].x-EPS) && inx < (a[1].x+EPS))
{
if(inx<Right+EPS)
Right = inx;
}
else
{cout<<"0
"; return 0;}
}
else
{
if(inx > (a[1].x-EPS) && inx < (a[0].x+EPS))
{
if(inx>Left-EPS)
Left = inx;
}
else
{cout<<"0
"; return 0;}
}
st.push(t);
r=s; s=t; t++;
}
return 1;
}
int LeftScan(Point *a, int n)
{
stack<int> st;
int r,s,t,x;
r=n;
st.push(r);
s = n-1;
st.push(s);
t=n-2;
while(t!=1)
{
x=s+1;
if(RST(a[r],a[s],a[t])<0 && RST(a[x],a[s],a[t])>0)
{cout<<"0
"; return 0;}
while(st.size()!=1 && RST(a[r],a[s],a[t])>0)
{
st.pop();
s = st.top();
if(st.size()!=1)
{
int temp = st.top();
st.pop();
r = st.top();
st.push(temp);
}
}
long double inx;
if(a[t].y-a[s].y < EPS && a[s].y-a[t].y < EPS)
{cout<<"0
"; return 0;}
inx = ((a[s].x - a[t].x)*(a[0].y-a[t].y)/(a[s].y-a[t].y)) + a[t].x;
if(up==-1)
{
if(inx > (a[0].x-EPS) && inx < (a[1].x+EPS))
{
if(inx>Left-EPS)
Left = inx;
}
else
{cout<<"0
"; return 0;}
}
else
{
if(inx > (a[1].x-EPS) && inx < (a[0].x+EPS))
{
if(inx<Right+EPS)
Right = inx;
}
else
{cout<<"0
"; return 0;}
}
st.push(t);
r=s; s=t; t--;
}
return 1;
}
int main()
{
Point a[1010];
int top=2, n, i;
cin>>n;
for(i=0;i<n;i++)
cin>>a[i].x>>a[i].y;
a[n].x = a[0].x;
a[n].y = a[0].y;
if(a[2].y > a[0].y)
{
Left = a[1].x;
Right = a[0].x;
up=1;
}
else
{
Left = a[0].x;
Right = a[1].x;
up=-1;
}
if(RightScan(a,n))
if(LeftScan(a,n))
{
if(Right+EPS<Left)
{cout<<"0
"; return 0;}
cout<<abs(floor(Right+EPS)-ceil(Left-EPS)+1)<<endl;
}
}
|
69
|
A
|
Young Physicist
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
In this task all you had to do was to make sure that the sum of all \Sigma xi is 0, the sum of all \Sigma yi is 0 and that the sum of all \Sigma zi - 0 . We have not written that condition evidently in order that participants will have a chance to break a solution.
|
[
"implementation",
"math"
] | 1,000
| null |
69
|
B
|
Bets
|
In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor.
To begin with friends learned the rules: in the race there are $n$ sections of equal length and $m$ participants. The participants numbered from $1$ to $m$. About each participant the following is known:
- $l_{i}$ — the number of the starting section,
- $r_{i}$ — the number of the finishing section ($l_{i} ≤ r_{i}$),
- $t_{i}$ — the time a biathlete needs to complete an section of the path,
- $c_{i}$ — the profit in roubles. If the $i$-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman.
The $i$-th biathlete passes the sections from $l_{i}$ to $r_{i}$ inclusive. The competitor runs the whole way in $(r_{i} - l_{i} + 1)·t_{i}$ time units. It takes him exactly $t_{i}$ time units to pass each section. In case of the athlete's victory on $k$ sections the man who has betted on him receives $k·c_{i}$ roubles.
In each section the winner is determined \textbf{independently} as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed.
We should also add that Nikita can bet on each section and on any contestant running in this section.
Help the friends find the maximum possible profit.
|
In this problem, in fact, you should find a winner at every section. For each section, you must do a full search of all competitors to find a competitor with a minimum section time, which ran that section. Asymptotic of the solution is O(nm).
|
[
"greedy",
"implementation"
] | 1,200
| null |
69
|
C
|
Game
|
In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts.
After the composing composite artifact, all the components disappear.
Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts.
|
In this task, you had to update the collection of artifacts, which belong to Kostya's friends, after each purchase . You had to set a matrix c[i][j] - number of the j-th basic artifact that is required in order to collect the i-th component artifact. Further, one can make a matrix of composite artifacts, where a[i][j] is number of the j-th basic artifact of the i-th friend and a similar matrix b of composite artifacts, and check whether i-th friend has any a composite artifact of O (MN) after each i-th friend's purchase. Check whether one component of the artifact assembles for O (N): while checking whether the i-th friend is able to collect the j-th artifact you have to check, if there is such u, that c[j [u]> a[i][u], if so, the j-th artefact will not be collected, if not, then you have to increase the b[i][j] and update the values in a[i]). So.the asymptotics of the processing of all purchases will be O (NQM). Then, we need to make a list of artifacts for each person, keeping their quantity(a total of O (KN + KM), and sort it (a total of O (QlogQ)).
|
[
"implementation"
] | 2,000
| null |
69
|
D
|
Dot
|
Anton and Dasha like to play different games during breaks on checkered paper. By the 11th grade they managed to play all the games of this type and asked Vova the programmer to come up with a new game. Vova suggested to them to play a game under the code name "dot" with the following rules:
- On the checkered paper a coordinate system is drawn. A dot is initially put in the position $(x, y)$.
- A move is shifting a dot to one of the pre-selected vectors. Also each player can once per game symmetrically reflect a dot relatively to the line $y = x$.
- Anton and Dasha take turns. Anton goes first.
- The player after whose move the distance from the dot to the coordinates' origin exceeds $d$, loses.
Help them to determine the winner.
|
This game is over, because except for a finite number (2) of reflections about the line y = x,the coordinates are changed to non-negative integer (and at least one coordinate is changed to a positive number). Algorithm for solving this problem is DFS / BFS (states) where the state is a pair of coordinates, and two logical variables, which denote if the 1 (2) player had reflected a point about the line y = x. Total number of states is obtained by S <= 4D^2 (pairs of coordinates) * 4 (Boolean variables). Processing of one state takes O (N) actions (do not forget to try to reflect the point about the line y = x, if the player had not made it earlier in the game). Thereby, we have the overall asymptotic O (ND^2), which works on C + + in less than 200ms.
|
[
"dp",
"games"
] | 1,900
| null |
69
|
E
|
Subsegments
|
Programmer Sasha has recently begun to study data structures. His coach Stas told him to solve the problem of finding a minimum on the segment of the array in $O(\log n)$, which Sasha coped with. For Sasha not to think that he had learned all, Stas gave him a new task. For each segment of the fixed length Sasha must find the maximum element of those that occur on the given segment exactly once. Help Sasha solve this problem.
|
To solve this problem you have to do a "move" subsegment and know : 1. The set B of numbers, meeting once, with the function of extracting the maximum for O (logN) 2.The set of numbers appearing on this subsegments with keeping the number of times,that this number is found on this subsegments, with function of verifying how many times the number in this subsegments for O (logN). While moving a segment from (a[i] .. a[i + k - 1]) for 1 item left (a[I + 1] .. a[I + k]) you have to: 1) Check whether a[i] with a[I + k]. If yes, then there is no need to modify the set, otherwise proceed to item 2 and 3. 2) Check how many times we have a[i] in the set A: if 2, then add a[i] to B, if 1, then remove it from A and B. Do not forget to reduce the corresponding number of occurrences of a[i] in the current segment 1. 3) Check, how many times we have a[I + k] in the set A: if 0, then add a[i] in the B and A, if 1, then remove it from B. Do not forget to increase the corresponding number of occurrences of a[i] the current interval to 1. After that, if the set is not empty, we should take peak from it. So the asymptotics of this process will be O(NlogN). As such data structures set / map(for those who use C + +) and the Cartesian tree are suitable.
|
[
"data structures",
"implementation"
] | 1,800
| null |
70
|
A
|
Cookies
|
Fangy collects cookies. Once he decided to take a box and put cookies into it in some way. If we take a square $k × k$ in size, divided into blocks $1 × 1$ in size and paint there the main diagonal together with cells, which lie above it, then the painted area will be equal to the area occupied by one cookie $k$ in size. Fangy also has a box with a square base $2^{n} × 2^{n}$, divided into blocks $1 × 1$ in size. In a box the cookies should not overlap, and they should not be turned over or rotated. See cookies of sizes $2$ and $4$ respectively on the figure:
To stack the cookies the little walrus uses the following algorithm. He takes out of the repository the largest cookie which can fit in some place in the box and puts it there. Everything could be perfect but alas, in the repository the little walrus has infinitely many cookies of size $2$ and larger, and there are no cookies of size $1$, therefore, empty cells will remain in the box. Fangy wants to know how many empty cells will be left in the end.
|
Let's define a half-filled square of size $k$ as an empty square of size $k$ after adding a cookie of the biggest posible size. Notice, that if we add a cookie of the biggest possible size into the half-filled square of size $2^{n} \times 2^{n}$, it will be divided into three half-filled squares of size $2^{None} \times 2^{None}$ and one filled square. After performing the same actions with the three half-filled squares we will get nine half-filled squares of size $2^{None} \times 2^{None}$ and so on. It's easy to get the formula $f(n) = 3 * f(n - 1)$, $f(0) = f(1) = 1$. $3^{None}$ (for $n > 0$) and $1$ (for $n = 0$).
|
[
"math"
] | 1,300
| null |
70
|
B
|
Text Messaging
|
Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing $n$ characters (which is the size of one text message). Thus, whole sentences and words get split!
Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).
The little walrus's text looks in the following manner:
\begin{verbatim}
TEXT ::= SENTENCE | SENTENCE SPACE TEXT
SENTENCE ::= WORD SPACE SENTENCE | WORD END
END ::= {'.', '?', '!'}
WORD ::= LETTER | LETTER WORD
LETTER ::= {'a'..'z', 'A'..'Z'}
SPACE ::= ' '
\end{verbatim}
SPACE stands for the symbol of a space.
So, how many messages did Fangy send?
|
It's obviously, that sentences should be added into the SMS greedily. Really, if we put the sentence into the new message, when it's possible to add into previous, the number of messages may be increased. The only thing you should pay attention is correct processing whitespaces between the sentences.
|
[
"expression parsing",
"greedy",
"strings"
] | 1,600
| null |
70
|
C
|
Lucky Tickets
|
In Walrusland public transport tickets are characterized by two integers: by the number of the series and by the number of the ticket in the series. Let the series number be represented by $a$ and the ticket number — by $b$, then a ticket is described by the ordered pair of numbers $(a, b)$.
The walruses believe that a ticket is lucky if $a * b = rev(a) * rev(b)$. The function $rev(x)$ reverses a number written in the decimal system, at that the leading zeroes disappear. For example, $rev(12343) = 34321$, $rev(1200) = 21$.
The Public Transport Management Committee wants to release $x$ series, each containing $y$ tickets, so that \textbf{at} \textbf{least} $w$ lucky tickets were released and the total number of released tickets ($x * y$) were minimum. The series are numbered from $1$ to $x$ inclusive. The tickets in each series are numbered from $1$ to $y$ inclusive. The Transport Committee cannot release more than $max_{x}$ series and more than $max_{y}$ tickets in one series.
|
Let's learn how to solve more easy problem: it's need to count a number of lucky tickets with $1 \le a \le x$ and $1 \le b \le y$. Rewrite sentence $a * b = rev(a) * rev(b)$ as $a / rev(a) = rev(b) / b$. Brute all $a$ and count a number of irreducible fractions $a / rev(a)$ using, for example, map from STL. Now for every $b$ you should count the number of fractions $a / rev(a)$ equal to $rev(b) / b$ and add to answer. Come back to our problem. If the number of lucky tickets with $1 \le a \le max_{x}$ and $1 \le b \le max_{y}$ less than $w$, it should be printed $- 1$. If the solution exist, let's use the method of two pointers. We need to keep up the quantity of lucky tickets with $1 \le a \le x$ and $1 \le b \le y$ for some state $(x, y)$ an change it to (x,y+1), (x+1,y), (x,y-1), (x-1,y). That's why we create two structures of type map (named m1 and m2). Let's learn how to change state from (x,y) to (x,y+1), (x+1,y), (x,y-1), (x-1,y). If we want to increase (decrase) the value of $x$, we should add (subtract) m2[x/rev(x)] to (from) the number of lucky tickets and increase (decrease) m1[x/rev(x)] by one. In the case of changing $y$ you should do the similar actions. Let's set the state $(x, y)$, where $x = max_{x}$, $y = 1$ and count the quantity of lucky tickets for it. We will be increase $y$, while the number of lucky tickets is less than $w$. Obviously, that it will be the least $y$ for $x$, such as it will be enough lucky tickets in the range. Relax the answer. You had to decrease $x$ by one and do the same actions while $x$ is greater than one. The anser have the least value of $x * y$ because we relaxed it with the optimal state for every $x$. So, the $x$ was equael to every value between $1$ and $max_{x}$ not more than once. The similar is correct for $y$ because it was only increasing. The time need for change the value in map is O(log(map_size)), that's why the algorithm lave an asymptotic form as $O(max_{x} * log(max_{y}) + max_{y} * log(max_{x}))$.
|
[
"binary search",
"data structures",
"sortings",
"two pointers"
] | 2,200
| null |
70
|
D
|
Professor's task
|
Once a walrus professor Plato asked his programming students to perform the following practical task.
The students had to implement such a data structure that would support a convex hull on some set of points $S$. The input to the program had $q$ queries of two types:
1. Add a point with coordinates $(x, y)$ into the set $S$. Note that in this case the convex hull of $S$ could have changed, and could have remained the same.
2. Say whether a point with coordinates $(x, y)$ belongs to an area limited by the convex hull, including the border.
All the students coped with the task. What about you?
|
Notice, that any point from the triangle based on first three points will be into the area bounded with the convex hull in the future. Let choose one of these points ad set it as the origin. All points of convex hull will keep in structure like map in C++, where the key is the angle of vector from the origin to a point. No two points from the hull will have the same angle. How to answer the second-type queries? For the point from the query ($A$) let's find the closest point clockwise ($B$) and the closest point anticlockwise ($C$). If the vectors $AB$ and $AC$ make up a clockwise rotation, then point A doesn't lay into the convex or on it's bounds. How to answer the first-type queries? If the point from the query ($C$) lays into the convex hull, then do nothing else let's find two closest points clockwise relative to point $C$ (the closest will be named $A$, tho other will be named $B$). If rotation from the vector $AB$ to the vector $AC$ is a counterclockwise rotation then processing points laying clockwise relative to point $C$ in ended, else you have to delete point $A$ from the structure and repeat the same actions. The similar actions you should apply to points anticlockwise relative to point $C$. All points will be added and deleted in the structure not more than once. These operations need $O(log(h))$ time, where $h$ is a number of point in convex hull. Total asymptotic form is $O(q * log(h))$.
|
[
"data structures",
"geometry"
] | 2,700
| null |
70
|
E
|
Information Reform
|
Thought it is already the XXI century, the Mass Media isn't very popular in Walrusland. The cities get news from messengers who can only travel along roads. The network of roads in Walrusland is built so that it is possible to get to any city from any other one in exactly one way, and the roads' lengths are equal.
The North Pole governor decided to carry out an information reform. Several cities were decided to be chosen and made regional centers. Maintaining a region center takes $k$ fishlars (which is a local currency) per year. It is assumed that a regional center always has information on the latest news.
For every city which is not a regional center, it was decided to appoint a regional center which will be responsible for keeping this city informed. In that case the maintenance costs will be equal to $d_{len}$ fishlars per year, where $len$ is the distance from a city to the corresponding regional center, measured in the number of roads along which one needs to go.
Your task is to minimize the costs to carry out the reform.
|
Notice next facts. If we have the fixed state of some regional centers then for every city will be assigned the nearest regional center. The regional center of some city will be assigned for all cities between this city and it's regional center. It means that tree should be divided into some subtrees. Also define $d[0] = 0$. Let's solve the problem using "crossed" Dynamic Programming. First function of DP. D1(T, g, x, s) will be responsible for forming the subtree with the regional center g. T is somme subtree of tree from the input defined with edge $uv$. regional center g must be situated in T. Let's consider that $g$ is assigned to $v$. The aim will be considered in choosing edges which will bound our subtree. Picture: Green and red edges connect cities which g was assigned. Purple edge bounds the set of such cities. Notice, that vertexes laying on the red pass cannot be bounding, because g is assigned to v. Let $xs$ edge be bounding, then for subtree $T'$ (vertexes of it's subtree are into the circle) call the secnod funtion of DP $D2(T')$. The second function of DP will brute every point of subtree $T'$ as a regional center and call D1. D1 have $O(n^{3})$ states, because the number of subtrees $T$ is $O(n)$, number of options to choose g is the same and pair (x;s) makes up an edge, number of edges is 2*n-2. The second function of DP has $O(v)$ states and transition need $O(v)$ iterations. Thats why solution need $O(n^{3})$ memory and have asymptotic form $O(n^{3})$.
|
[
"dp",
"implementation",
"trees"
] | 2,700
| null |
71
|
A
|
Way Too Long Words
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is \textbf{strictly more} than $10$ characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
In this problem you can just do what is written in the statement. Let read all words. For each of them compute its length $L$, its the first and the last letter. If $L > 10$, output word without any changes, otherwise output the first letter, next $L - 2$ and finally the last letter.
|
[
"strings"
] | 800
| null |
71
|
B
|
Progress Bar
|
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as $n$ squares, located in line. To add clarity, let's number them with positive integers from $1$ to $n$ from the left to the right. Each square has saturation ($a_{i}$ for the $i$-th square), which is measured by an integer from $0$ to $k$. When the bar for some $i$ ($1 ≤ i ≤ n$) is displayed, squares $1, 2, ... , i - 1$ has the saturation $k$, squares $i + 1, i + 2, ... , n$ has the saturation $0$, and the saturation of the square $i$ can have any value from $0$ to $k$.
So some first squares of the progress bar always have the saturation $k$. Some last squares always have the saturation $0$. And there is no more than one square that has the saturation different from $0$ and $k$.
The degree of the process's completion is measured in percents. Let the process be $t$% completed. Then the following inequation is fulfilled:
\[
{\frac{\sum_{i=1}^{n}a_{i}}{n k}}\leq{\frac{t}{100}}<{\frac{(\sum_{i=1}^{n}a_{i})+1}{n k}}.
\]
An example of such a bar can be seen on the picture.
For the given $n$, $k$, $t$ determine the measures of saturation for all the squares $a_{i}$ of the progress bar.
|
At first, compute $z=\sum_{i=1}^{n}a_{i}$. It equals $ \lfloor mnk / 100 \rfloor $, where $ \lfloor x \rfloor $ is rounding down. Next we fill first $ \lfloor z / k \rfloor $ squares with a saturation $k$. $( \lfloor z / k \rfloor + 1)$-th square (if it exists) we fill in a saturation $z - \lfloor z / k \rfloor k$. All other squares we leave with a saturation $0$.
|
[
"implementation",
"math"
] | 1,300
| null |
71
|
C
|
Round Table Knights
|
There are $n$ knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.
Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.
A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.
On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.
King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.
|
Define an good polygon as a regular polygon which has a knight in a good mood in every of its vertex. Side of polygon we will measure in arcs which is obtained by dividing border of round table with knights. Freeze the length of the side. Let this length equals $k$. Observe that the regular polygon with such length of side exists only if $k$ divides $n$. We have exactly $k$ of such polygons. Every of them has exactly $n / k$ vertices. Check every of the polygons for goodness by review all of its vertices. If sum of vertices with knight in a good mood equals to $n / k$, this polygon is good. Checking of all polygons with some frozen length of side works in an $O(n)$. Now observe that $n$ has $O({\sqrt{n}})$ of divisors. Really, all divisors (may be except only one) we can divide into pairs (for $i$ corresponds $n / i$, for $i = n / i$ there is no pair). One of divisors in every pair less than $\sqrt{n}$. It means thah number of pairs no more than $\sqrt{n}$ and number of divisors no more than $2{\sqrt{n}}$. It gives solution - iterate over all divisors of $n$ and for every of them check existence of good polygon with length side equals this divisor. Solution has an $O(n{\sqrt{n}})$ time. In reality for big $n$ is has $O({\dot{\sqrt{n}}})$ divisors. So solution actually has $O(n^{4 / 3})$-complexity. For all numbers less than $10^{5}$ maximal number of divisors is 128. UPD. There was found an $O(n\log n)$ solution by some participants. This solution uses following idea. If we have a good polygon with $xy$ vertices, we also have a good polygon with $x$ vertices. So we can check only prime divisors of $n$ (except 2 - here we must check 4).
|
[
"dp",
"math",
"number theory"
] | 1,600
| null |
71
|
D
|
Solitaire
|
Vasya has a pack of $54$ cards ($52$ standard cards and $2$ distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them.
Vasya lays out $nm$ cards as a rectangle $n × m$. If there are jokers among them, then Vasya should change them with some of the rest of $54 - nm$ cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. \textbf{in a single copy}). Vasya tries to perform the replacements so that the solitaire was solved.
Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares $3 × 3$, inside each of which all the cards either have the same suit, or pairwise different ranks.
Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible.
|
This problem can be divided into some subproblems. Author's solution means following ones: 1. Check validness of square $3 \times 3$. Square is valid if all cards in it has equal suit or different rank. You may not check equal suit because equal suits imply different ranks. 2. Find 2 valid noninetsect squares $3 \times 3$ or return thah there are no ones. You can check all pairs of squares for inetsection. If some pair has no intersections check them with solution of subproblem 1. 3. Build set of cards which can be replaced with jokers. Generate full deck without jokers and drop from it all cards which in rectangle $n \times m$ are present. 4. Find number of jokers and its positions in rectangle. 5. Main subproblem. At first, solve subproblems 3 and 4. Now replace jokers in rectangle with cards from deck from subproblem 3 by all possible ways. For every replace solve subproblem 2. Arter all of variants of replacement just output answer. There are $O(n^{2}m^{2})$ solution with small constant.
|
[
"brute force",
"implementation"
] | 2,200
| null |
71
|
E
|
Nuclear Fusion
|
There is the following puzzle popular among nuclear physicists.
A reactor contains a set of $n$ atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements.
You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times.
The aim is getting a new pregiven set of $k$ atoms.
The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle.
|
At first, you can use some search engine for find periodic table in some printable form. Next use copy-paste (one or several times) and format it by deleting all excess. It is mechanical work for no more than 5 minutes. Also some parser may be written. Note than author's solution does not mean write 100 symbols by hand from a picture. Next build some functions which transform symbols into numbers and vice versa. So, we have some set of numbers. We need summarize some from them and get some another set of numbers. We will use dymanic programming over subsets. Compute the first dp dp1[mask]->sum. For each subset calculate sum of numbers of all atoms in this subset. It can be done in $O(2^{n}n)$. Now compute the second dp dp2[mask]->length. The "length" is a length of some prefix of result sequence of atoms which can be obtained by subset mask. If length -1, it means that it is impossible to get any prefix from this subset. The second dp we can calculate in $O(3^{n})$. Iterate over all masks and if dp2[mask]!=-1, iterate all its subsets of remained atoms (invert mask and get all its submasks). If some subset has sum of numbers which equals number of (dp2[mask]+1)-th atom from result set, recalculate dp2[mask XOR submask]=dp2[mask]+1. At end, if dp2[$2^{n} - 1$]=k, there are solution. There are $O(3^{n} + 2^{n}n)$ solution. In this problem some brutforce solutions are passed because it is difficult to pick up some counterexample. UPD. SkorKNURE found a solution in $O(2^{n}n)$. This solution is some modification of the author's solution. Instead of dp2 calculate dp dp2'[mask]->(i,j), where i is a length of prefix which mask covers and j is part of number of (i+1)-th atom which mask covers. Iterate over all masks. For each mask iterate over all its 0-bits$$ (they are atoms which cover nothing from the finish set). We try to cover with this 0-bit a remainder of number of the (i+1)-th atom from the finish set. Let atomic number of an atom for current 0-bit is p and this atom is q-th in the start set. If we cover with this atom only part of the remainder of number of the (i+1)-th atom, dp2'[mask XOR (1<<q)]=(i,j+p). If we cover with this atom the remainder fully (and exactly this remainder, no more!), dp2'[mask XOR (1<<q)]=(i+1,0). Now dp1 is useless. If at end dp2'[$2^{n} - 1$]=(k,0), solution exists (it is easy to restore it), otherwise there is no solution.
|
[
"bitmasks",
"dp"
] | 2,200
| null |
73
|
A
|
The Elder Trolls IV: Oblivon
|
Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so lovers of two-handed amber hammers should find suitable knife themselves. Secondly, it is necessary to make so many cutting strokes to Unkillable Slug. Extremely many. Too many!
Vasya has already promoted his character to 80-th level and in order to gain level 81 he was asked to kill Unkillable Slug. The monster has a very interesting shape. It looks like a rectangular parallelepiped with size $x × y × z$, consisting of undestructable cells $1 × 1 × 1$. At one stroke Vasya can cut the Slug along an imaginary grid, i.e. cut with a plane parallel to one of the parallelepiped side. Monster dies when amount of parts it is divided reaches some critical value.
All parts of monster do not fall after each cut, they remains exactly on its places. I. e. Vasya can cut several parts with one cut.
Vasya wants to know what the maximum number of pieces he can cut the Unkillable Slug into striking him at most $k$ times.
Vasya's character uses absolutely thin sword with infinite length.
|
Let's call the monster dimension sizes as x1, x2, x3. 1. O(min(k, x1 + x2 + x3)) solution We can make at most (x1 - 1) + (x2 - 1) + (x3 - 1) cuttings, so we may assume that k <= x1 + x2 + x3 - 3. For each of the three dimensions we will store an integer ai - number of cuttings performed through the corresponding dimension. Let's perform the following actions k times: consider all numbers ai which we may increase (ai < xi - 1) , call these dimensions "uncompleted". Select the minimum number aj among all uncompleted ai and perform a cut through the corresponding dimension (aj will be increased by 1 as the result). Now let's consider the resulting set after k actions: {a1, a2, a3}. Using the described algorithm we grant that the maximum element of this set is as little as possible and the minimum element is as big as possible. Because the sum a1 + a2 + a3 = k is fixed, we get the maximum product (a1 + 1) * (a2 + 1) * (a3 + 1) which is the answer for the problem. 2. O(1) solution Instead of simulation all the k actions we may quickly determine values of numbers ai after using the algorithm described above. Let x - the smallest value among (xi - 1). When x * 3 >= k on each of the algorithm iterations all three dimensions will be uncompleted. It means that during the first (k / 3) * 3 steps each of numbers ai will be increased by (k / 3). Then 0, 1 or 2 numbers ai will be increased by 1 subject to value of k % 3. So, we have found values ai. Otherwise (x * 3 < k) during the first x * 3 steps each of ai will be increased by x. After that we will have at most two uncompleted dimensions which can be processed a similar way (we should choose the minimum value x among the remaining uncompleted dimensions).
|
[
"greedy",
"math"
] | 1,600
| null |
73
|
B
|
Need For Brake
|
Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game!
$n$ racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to $n$-th (no two racers share the same place) and first $m$ places are awarded. Racer gains $b_{i}$ points for $i$-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer $i$ is $a_{i}$ points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order.
Unfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship.
|
We may assume that we have exactly n awarded places but some of them give 0 points. Let's sort places by amount of points (bi) and racers by amount of currently gained points (ai). First let's find the best place Vasya can reach. In the best case he will get b0 points (where b0 is the greatest number among bi). So, let the total Vasya's point is v. Now we should to distribute other prize points to racers so that the number of racers better than Vasya will be minimal. For doing that we are to give maximum number of prizes so that corresponding racers will have less than v points. Note that if we can give k prizes keeping this property, than we can give k "cheapest" prizes too. The following statement is also true: if we can get a prize with t points to racer i and to racer j , ai > aj, then it is better to give this prize to racer i. Formally: if there exists a way to give k prizes where this prize will get racer j, than there exists a way to give k prizes where this prize will get racer i. It can be proven the following way. Consider a way to give k prizes where racer j got prize with t points, racer i - s points or didn't get prize at all. In the first case we can swap prizes for racers i and j: ai > aj and ai + s < v (since racer i have got the prize), so aj + s < v, and ai + t < v i.e. this change is acceptable. In the second case we can just give the prize t to racer i instead of racer j. In the both cases we get a way to give k prizes where racer i receive prize t. Now including this statement we may give prizes to racers using the following greedy algorithm. Let's begin to give prizes starting from the cheapest one and check the racers starting from the best one (of course excluding Vasya and the best prize). For each prize i we will go through the racers until applicable racer (j) found: bi + aj < v. If no such racers remain we are unable to give more prizes without violating the rule (racers should have less than v points). In this case we should stop the algorithm and the answer is n - k where k is the number of prizes we have given. If we have found such racer j we can give him prize bi and go to the next prize. Complexity of this step is O(n). Similarly we can find the worst place for Vasya. For doing that we should give him the cheapest prize (note it may have positive points though). After that we should distribute the prizes iterating over prizes from the largest to cheapest and check racers from the worst to the best one trying to make sum of racer's points more than v. Total complexity of the described algorithm is O(n * log(n)) because we have to sort prizes and racers.
|
[
"binary search",
"greedy",
"sortings"
] | 2,000
| null |
73
|
C
|
LionAge II
|
Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character — non-empty string $s$, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than $k$ letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters $x$ and $y$ ($x$ immediately precedes $y$) the bonus $c(x, y)$ is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most $k$ letters in the name of the Vasya's character.
|
It is easy to see that if we put some symbol c at position p of the string s it will not affect symbols at positions (p+2) and greater. So we have a standard DP problem. State of the dynamic is described by three parameters: p - the number of already processed symbols (or the index of currently processed symbol of the string), c - the previous symbol, t - the number of allowed symbol changes. To calculate the answer for a state we should choose the best value among all symbols for current position (when t > 0) or just go to the index (p + 1) with current symbol s[p]. Thus we get the followings formulas: d[n][*][*] = 0 d[p][c][t] = d[p + 1][s[p]][t] + bonus[c][s[p]] when t = 0 d[p][c][t] = max(d[p + 1][c'][t - (c' <> s[p])] + bonus[c][c']) where n is the length of string s. Computation complexity of the algorithm is O(n * k * h^2), where h is the alphabet size (h = 26 for current problem).
|
[
"dp"
] | 1,800
| null |
73
|
D
|
FreeDiv
|
Vasya plays FreeDiv. In this game he manages a huge state, which has $n$ cities and $m$ two-way roads between them. Unfortunately, not from every city you can reach any other one moving along these roads. Therefore Vasya decided to divide the state into provinces so that in every province, one could reach from every city all the cities of the province, but there are no roads between provinces.
Unlike other turn-based strategies, in FreeDiv a player has the opportunity to build tunnels between cities. The tunnels are two-way roads along which one can move armies undetected by the enemy. However, no more than one tunnel can be connected to each city. As for Vasya, he wants to build a network of tunnels so that any pair of cities in his state were reachable by some path consisting of roads and a tunnels. But at that no more than $k$ tunnels are connected to each province (otherwise, the province will be difficult to keep in case other provinces are captured by enemy armies).
Vasya discovered that maybe he will not be able to build such a network for the current condition of the state. Maybe he'll have first to build several roads between cities in different provinces to merge the provinces. Your task is to determine the minimum number of roads Vasya needs to build so that it was possible to build the required network of tunnels in the resulting state.
|
First, let's divide graph to connected components (provinces). Next, we consider only new graph on these components - for each province we assign a vertex of the graph. Let the total number of provinces is n. Initially the graph is empty since there are no roads between different provinces. Also for each province we have a limit of the number of tunnels that can be constructed from this province: ki = min (k, ci) where ci - the number of cities which was originally contained in the province (component) i. The resulting provinces graph should be connected after building tunnels and roads. When k = 1 we have to build at least n - 2 roads, otherwise the graph will have at least 3 components and at least 2 tunnels should be constructed from one of them which is prohibited. Further, we assume that k > = 2. Let's calculate the largest number of tunnels we can build. Let s - the sum of all numbers ki. Obviously we cannot build more than s / 2 tunnels since each tunnel connects exactly two provinces. The following statement is true: we can construct s / 2 (rounded to the lower side) of tunnels or to make a graph connected by constructing n - 1 tunnels (if s / 2 > = n - 1). Let's consider vertices which have ki > 1. We may connect these vertices into a chain using tunnels. After that let's start to connecting vertices with ki = 1to the chain (using tunnels too) while it is possible. Suppose we had less than s / 2 tunnels built and we are unable to build one more tunnel. It means that we have exactly one vertex j with degree no more than kj - 2. Thus kj > 1 and this vertex is included into the chain and all the vertices with ki = 1 are attached to this chain too (otherwise we could build another tunnel), so the graph is connected. If after building the tunnels we have a connected graph then the answer is 0. Otherwise the graph consists of n - s / 2 components, that is we need to build at least n - s / 2 - 1 roads. In fact such a number of roads will be enough. Let's draw each of n - s / 2 - 1 roads the following way. First, choose 2 different connected components in the current graph. Because we have built tunnels (and possibly roads) only between different components each of the chosen components is a tree. So these components have vertices with degree not greater than 1. Now, let's choose one such vertex in each of the selected components and connect the components through these vertices (i.e. the vertices are merged into one keeping the edges from them). Thus we have a new vertex (province) with no more than two tunnels constructed from it, so we did not violate the terms since k >= 2. Thus we can get a connected graph by building additional n - s / 2 - 1 roads which is the answer for the problem.
|
[
"dfs and similar",
"graphs",
"greedy"
] | 2,200
| null |
73
|
E
|
Morrowindows
|
Vasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than $x$ and not less than $2$ items in his inventory. A new patch for the game appeared to view inventory in $n$ different modes. Displaying in mode $i$ is a partition of all inventory items on pages, each of which (except for maybe the last one) shows exactly $a_{i}$ items. In addition, each mode shows how many pages $b_{i}$ is in a complete list. Great! Perhaps this information will be enough for Vasya to find the required number. Moreover, it is very interesting, what is the fewest number of modes in which Vasya can see inventory to determine the number of items in it?
\textbf{Vasya cannot use the information that was received while looking on inventory in some mode for selection of next actions. I. e. Vasya chooses some set of modes first, and then sees all the results and determines the size.}
Knowing the number of $a_{i}$, $x$ and assuming that Vasya is very smart, check whether he can uniquely determine the number of items in his inventory, and how many modes he will need to do that if he knows numbers $a_{i}$, $x$ and he is able to know number $b_{i}$ after viewing items in mode $i$.
|
When x = 2 then the answer is 0. Further we assume that x > 2. In order to uniquely identify the desired number of items t we must choose a set of numbers ai so that for every y from 2 to x the representation in modes ai is unique, i.e. sets of numbers b (y, i) = y / ai (rounded up) are pairwise distinct among all y. Note that for each i function b(y, i) is monotone by y. Hence if for some i and numbers y and z (y < z) holds b(y, i) = b(z, i) then b(y, i) = b(y + 1, i) too. So to select the set of numbers ai it is sufficient to guarantee that for each y from 2 to x - 1 exists a number j such that b(y, j) < b(y + 1, j). It is easy to see that b(y, j) < b(y + 1, j) if and only if y is divisible by aj. Thus, it is necessary that for each y from 2 to x - 1 exists number ai so that y is a multiple of ai. If some number ai is equal to 1 Vasya can just see the list in this mode to find the desired number and the answer for the problem is 1. Otherwise it is necessary and enough to take all the primes pi < x in our set ai to find the number. Indeed if we will not use some prime number pi then we will be unable to distinguish numbers pi and (pi + 1) (since pi is not divisible by some of the selected numbers). On the contrary if we will use all primes less than x then any number from 2 to x - 1 will be divisible by at least one of them. Thus we need to check whether there are all prime numbers less than x among ai. Since the number of primes from 1 to x is about O(x / ln (x)) for large x all prime numbers less than x cannot be in the set of numbers ai. For example the following statement is true: if x > 20 * n then the answer is -1. This means that we can use the Sieve of Eratosthenes to find all primes less than x for x <= 20 * n and to check whether there is at least one number from them which does not occur in ai. If such number exists then the answer for the problem is -1 otherwise the answer is the number of primes less than x.
|
[
"math",
"number theory"
] | 2,400
| null |
73
|
F
|
Plane of Tanks
|
Vasya plays the Plane of Tanks. The tanks in this game keep trying to finish each other off. But your "Pedalny" is not like that... He just needs to drive in a straight line from point $A$ to point B on the plane. Unfortunately, on the same plane are $n$ enemy tanks. We shall regard all the tanks as points. At the initial moment of time Pedalny is at the point $A$. Enemy tanks would be happy to destroy it immediately, but initially their turrets are tuned in other directions. Specifically, for each tank we know the initial rotation of the turret $a_{i}$ (the angle in radians relative to the $OX$ axis in the counterclockwise direction) and the maximum speed of rotation of the turret $w_{i}$ (radians per second). If at any point of time a tank turret will be aimed precisely at the tank Pedalny, then the enemy fires and it never misses. Pedalny can endure no more than $k$ shots. Gun reloading takes very much time, so we can assume that every enemy will produce no more than one shot. Your task is to determine what minimum speed of $v$ Pedalny must have to get to the point $B$. It is believed that Pedalny is able to instantly develop the speed of $v$, and the first $k$ shots at him do not reduce the speed and do not change the coordinates of the tank.
|
If for some velocity v1 we were able to go from point A to point B and receive no more than k hits, then for any velocity v2 > = v1 we also will be able to go from A to B. So we can use the binary search algorithm to find the answer. Suppose we have fixed speed of the tank v. Now we have to count how many enemy tanks will be able to shoot at our tank during the ride. Let's consider enemy tank i located at the point P on the plane. It may aim at our tank in two ways: turn the turret at point B or rotate the turret at point A and then start turning it from point A to point B. In the first case we may just compare the time required for the tank to move from A to B with the time required the enemy to aim the turret to point B. If the enemy tank will be able to take aim to B before we can reach this point then the enemy can make a shot. Next consider the second possible enemy strategy. Let's draw perpendicular PQ to the line AB. So we have divided the segment AB into 2 parts: AQ and QB (if Q does not lie on the segment AB then one of the parts will be empty and the other is a segment of AB. In this case let Q denote the end of segment AB closest to the base of the perpendicular). Let's consider the first part of the segment - AQ (before the base of the perpendicular). It is easy to check that while the angular velocity of the turret is a constant, the linear velocity of the enemy sight along the segment AQ is monotonely decreasing. Given the fact that the speed of our tank along AB is constant we find that the difference between the coordinates of the enemy's sight and the tank at the AQ interval is a convex function of time (second derivative is negative). Also this fact can be verified by finding the second derivative of this function explicitly. Thus we can use the ternary search algorithm for finding the minimum of this function on a time interval corresponding to time when our tank rides at segment AQ. When the minimum value of this function is negative the enemy is able to take aim at our tank and perform a shoot. Otherwise, the tank will ride ahead the enemy sight on the whole interval AQ. (Using similar statements we can find for example the minimum value of the time difference between reaching a point D of the interval AQ by the enemy sight and by our tank). It is possible to avoid the ternary search by finding a moment when the speed of the sight is equal to the speed of our tank and check who is closer to point B at this moment. But in this case we are to carefully handle the cases where one velocity is always greater than the other on the whole interval. Now let's consider the second part of the segment - QB (after the base of the perpendicular). If the enemy is unable to shoot in our tank at the first part of the segment (AQ) then at the time of sighting the enemy on point Q our tank will be located closer to point B than the sight. Similarly the first part of segment AB, we can prove that the linear speed of sight along QB is monotonely increasing. So if at some point C of segment QB the sight of the enemy tank has caught our tank then speed of the sight should be higher than speed of our tank at that moment (otherwise the enemy would not be able to catch the tank). Due to the monotonicity of the sight velocity on the remaining segment CB the sight will be faster than the tank and the sight will reach point B before our tank. Accordingly, if the enemy's sight has reached point B after our tank then the tank was ahead the sight on the whole interval QB too. Thus, to determine whether the enemy can shoot it is sufficient to check only point B. Performing these calculations for each of the n enemies we get the number of hits on our tank and comparing this value with the number k we go to the desired branch of the binary search.
|
[
"brute force",
"geometry"
] | 2,900
| null |
74
|
A
|
Room Leader
|
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.
In the beginning of the round the contestants are divided into rooms. Each room contains exactly $n$ participants. During the contest the participants are suggested to solve five problems, $A$, $B$, $C$, $D$ and $E$. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns $100$ points, for each unsuccessful hack a contestant loses $50$ points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.
You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
|
You can do exactly what is written in a statement. Only one pitfall in this problem is that room leader may have number of points less than zero.
|
[
"implementation"
] | 1,000
| null |
74
|
B
|
Train
|
A stowaway and a controller play the following game.
The train is represented by $n$ wagons which are numbered with positive integers from $1$ to $n$ from the head to the tail. The stowaway and the controller are initially in some two different wagons. Every minute the train can be in one of two conditions — moving or idle. Every minute the players move.
The controller's move is as follows. The controller has the movement direction — to the train's head or to its tail. During a move the controller moves to the neighbouring wagon correspondingly to its movement direction. If at the end of his move the controller enters the $1$-st or the $n$-th wagon, that he changes the direction of his movement into the other one. In other words, the controller cyclically goes from the train's head to its tail and back again during all the time of a game, shifting during each move by one wagon. Note, that the controller always have exactly one possible move.
The stowaway's move depends from the state of the train. If the train is moving, then the stowaway can shift to one of neighbouring wagons or he can stay where he is without moving. If the train is at a station and is idle, then the stowaway leaves the train (i.e. he is now not present in any train wagon) and then, if it is not the terminal train station, he enters the train again into any of $n$ wagons (not necessarily into the one he's just left and not necessarily into the neighbouring one). If the train is idle for several minutes then each such minute the stowaway leaves the train and enters it back.
Let's determine the order of the players' moves. If at the given minute the train is moving, then first the stowaway moves and then the controller does. If at this minute the train is idle, then first the stowaway leaves the train, then the controller moves and then the stowaway enters the train.
If at some point in time the stowaway and the controller happen to be in one wagon, then the controller wins: he makes the stowaway pay fine. If after a while the stowaway reaches the terminal train station, then the stowaway wins: he simply leaves the station during his move and never returns there again.
At any moment of time the players know each other's positions. The players play in the optimal way. Specifically, if the controller wins, then the stowaway plays so as to lose as late as possible. As all the possible moves for the controller are determined uniquely, then he is considered to play optimally always. Determine the winner.
|
In this problem you may find optimal strategy for a stowaway. Next you may just simulate a game. Optimal strategy for the stowaway is placing from a conrtoller as far as possible. In the moving minute the stowaway should go into wagon that farther to the controller. In the idle minute stowaway should go into wagon in which the controller enter as later as possible. It is always the first or the last wagon of train. You may also wrote some dynamic programming solution or a solution fot classic game.
|
[
"dp",
"games",
"greedy"
] | 1,500
| null |
74
|
C
|
Chessboard Billiard
|
Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.
More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed.
It is considered that one billiard ball $a$ beats another billiard ball $b$ if $a$ can reach a point where $b$ is located.
You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard $n × m$ in size.
|
Define a trajectory as a line that center of a billiard ball is drawing while it is moving. At begin of moving, the ball chose one from no more than two trajectoties and is moving along of it. Let a number of trajectories is $k$. Define $z$as maximal number of billiard balls that can be placed into chessboard without hits (it is answer for problem). Theorem. $z = k$. Proof. Every ball covers at least one trajectory. Two different balls cannot cover one trajectory because then they hit each other. Therefore, $z \le k$. Now try to arrange $k$ balls that they don't hit each other. Every cell of perimeter of board belongs to exactly one trajectory. Every trajectory covers at least one from border cells. So, there is exists $k$ cells on perimeter of board whick belongs to different trajectories. Into these cells we should put all billiard balls. End of proof. This theoren gives constructive methode to find $k.$ We may just calculate number of connected component in graph like in a picture below. It can be done by BFS, DFS or disjoint set union in time $O(n + m)$. For example, on picture 4 components are present. In this problem alse some solution by formula exists. $z = gcd(n - 1, m - 1) + 1$. You may wrote some stupid solution for observe it. But this formula is difficult for prove.
|
[
"dfs and similar",
"dsu",
"graphs",
"number theory"
] | 2,100
| null |
74
|
D
|
Hanger
|
In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by $n$ hooks, positioned in a row. The hooks are numbered with positive integers from 1 to $n$ from the left to the right.
The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.
When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.
When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.
From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the $i$-th to the $j$-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.
Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work.
|
You may use some data structire that allows fast insert, search, remove of elements and find a minimum of all elements. There can be used, for example, std::set in C++ or analogicaly container in other languages. In this structure segments of empty hooks can be stored. Minimum element in structure should be a segment into which a current coat can be hanged. In addition, for every arrived employee you may store place of his coat and segments of empty hooks in the left from this place and in the right from one. With help of this structures you can in $O(q\log q)$ emulate a work of cloakroom. Difficults begins with director's queries. We can fastly insert, delete and find sum in a segment. Online solution. There can be written some balanced or decart tree. Offline solution. At first, iterate over all queries "in idle" (we will nor answer for director's queries) and store coordinates of all hooks on which ever coat was hanged. Next, squeeze these coordinates and iterate over all queries again. Now we can answer for director's queries by using Fenwick or segment tree.
|
[
"data structures"
] | 2,400
| null |
74
|
E
|
Shift It!
|
There is a square box $6 × 6$ in size. It contains $36$ chips $1 × 1$ in size. Those chips contain 36 different characters — "0"-"9" and "A"-"Z". There is exactly one chip with each character.
You are allowed to make the following operations: you may choose one of $6$ rows or one of $6$ columns and cyclically shift the chips there to one position to the left or to the right (for the row) or upwards or downwards (for the column). Those operations are allowed to perform several times.
To solve the puzzle is to shift the chips using the above described operations so that they were written in the increasing order (exactly equal to the right picture). An example of solving the puzzle is shown on a picture below.
Write a program that finds the sequence of operations that solves the puzzle. That sequence \textbf{should not necessarily be shortest}, but you should not exceed the limit of $10000$ operations. It is guaranteed that the solution always exists.
|
A following sequence of operations swaps two pieces in positions 0 and 1: D1 R1 D1 L1 D1 R1 D1 L1 D1 R1 D1 L1 D1. This sequence can be found on a paper by hands or by usung bidirectional BFS with limitation of allowable moves (it also can be found by ordinary BFS with very limited number of allowable moves). Analogically you can swap any two neighbouring pieces in 13 moves. Then the solution is trivial and easily fits in the limit of 10000 moves.
|
[
"constructive algorithms"
] | 2,800
| null |
75
|
A
|
Life Without Zeros
|
Can you imagine our life if we removed all zeros from it? For sure we will have many problems.
In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation $a + b = c$, where $a$ and $b$ are positive integers, and $c$ is the sum of $a$ and $b$. Now let's remove all zeros from this equation. Will the equation remain correct after removing all zeros?
For example if the equation is $101 + 102 = 203$, if we removed all zeros it will be $11 + 12 = 23$ which is still a correct equation.
But if the equation is $105 + 106 = 211$, if we removed all zeros it will be $15 + 16 = 211$ which is not a correct equation.
|
In this problem you need to do what is written in the statement. You can do it in the following 3 steps: 1- Calculate C. 2- Remove all zeros from A, B and C. 3- Check if the new values form a correct equation.
|
[
"implementation"
] | 1,000
|
#include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <complex>
#include <list>
#include <climits>
#include <cctype>
using namespace std;
int removeZeros(int num) {
int ret = 0;
int ten = 1;
while (num) {
int dig = num % 10;
num /= 10;
if (dig) {
ret += dig * ten;
ten *= 10;
}
}
return ret;
}
int main() {
int a, b, c;
cin >> a >> b;
c = a + b;
a = removeZeros(a);
b = removeZeros(b);
c = removeZeros(c);
if (a + b == c)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
|
75
|
B
|
Facetook Priority Wall
|
Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described).
This priority factor will be affected by three types of actions:
- 1. "$X$ posted on $Y$'s wall" (15 points),
- 2. "$X$ commented on $Y$'s post" (10 points),
- 3. "$X$ likes $Y$'s post" (5 points).
$X$ and $Y$ will be two distinct names. And each action will increase the priority factor between $X$ and $Y$ (and vice versa) by the above value of points (the priority factor between $X$ and $Y$ is the same as the priority factor between $Y$ and $X$).
You will be given $n$ actions with the above format (without the action number and the number of points), and you have to print all the distinct names in these actions sorted according to the priority factor with you.
|
This problem is a direct simulation to the rules written in the problem statement. You need to iterate over all actions and parse each one to know the type of the action, and the 2 names X and Y, and if your name is X or Y then update your priority factor with this person with the action corresponding value. And take care about some special names like "post", "wall", "commented" and "on". Then sort all names according to the sorting criteria mentioned in the statement. Just make sure to print all names which are mentioned in the input (excluding yourself), even if the priority factor with you is 0.
|
[
"expression parsing",
"implementation",
"strings"
] | 1,500
|
#include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <complex>
#include <list>
#include <climits>
#include <cctype>
using namespace std;
int main() {
string myName;
cin >> myName;
int n;
cin >> n;
map<string, int> factor;
string name1, action, temp, name2;
for (int i = 0; i < n; i++) {
cin >> name1;
cin >> action;
if (action == "posted" || action == "commented")
cin >> temp;
cin >> name2;
name2 = name2.substr(0, name2.length() - 2);
cin >> temp;
int val = 5;
if (action == "posted")
val = 15;
else if (action == "commented")
val = 10;
if (name1 == myName)
factor[name2] += val;
else
factor[name1];
if (name2 == myName)
factor[name1] += val;
else
factor[name2];
}
vector<pair<int, string> > ret;
for (map<string, int>::iterator it = factor.begin(); it != factor.end(); it++)
ret.push_back(make_pair(-it->second, it->first));
sort(ret.begin(), ret.end());
int m = ret.size();
for (int i = 0; i < m; i++)
cout << ret[i].second << endl;
return 0;
}
|
75
|
C
|
Modified GCD
|
Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.
A common divisor for two positive numbers is a number which both numbers are divisible by.
But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor $d$ between two integers $a$ and $b$ that is in a given range from $low$ to $high$ (inclusive), i.e. $low ≤ d ≤ high$. It is possible that there is no common divisor in the given range.
You will be given the two integers $a$ and $b$, then $n$ queries. Each query is a range from $low$ to $high$ and you have to answer each query.
|
In this problem you will need to generate all common divisors between a and b before answering any query. The first step in this problem is to factorize a and b, you can use the trial division technique which runs in O(sqrt(N)), you can check getFactors function in my solutions. Then using a recursive function you can generate all divisors for a and b from their prime factors, you can check getDivisors function in my solutions. Then intersect the 2 sets of divisors for both to get all common divisors, you can do this in O(N+M) where N and M are the lengths of the 2 sets, and also you can do a trivial O(N*M) intersection algorithm, because the maximum number of divisors is not too big (it's 1344). Now for each query you need to find the largest common divisor which lies in the given range, you can do this by sorting all common divisors and do binary search for the largest one which lies in the given range. Also you can do this using linear search, because the total number of queries is not too big. Also there is much shorter solution for this problem. Here is a hint for it, the GCD between a and b should be dividable by all common divisors of a and b.
|
[
"binary search",
"number theory"
] | 1,600
|
#include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <complex>
#include <list>
#include <climits>
#include <cctype>
using namespace std;
vector<pair<int, int> > factors;
void getFactors(int n) {
factors.clear();
int d = 1;
for (int i = 2; i * i <= n; i += d, d = 2)
if (n % i == 0) {
factors.push_back(make_pair(i, 0));
while (n % i == 0) {
n /= i;
factors.back().second++;
}
}
if (n != 1)
factors.push_back(make_pair(n, 1));
}
vector<int> divisors;
void getDivisors(int ind = 0, int res = 1) {
if (ind == (int) factors.size()) {
divisors.push_back(res);
return;
}
for (int i = 0; i <= factors[ind].second; i++) {
getDivisors(ind + 1, res);
res *= factors[ind].first;
}
}
int main() {
int a, b, n;
scanf("%d", &a);
getFactors(a);
getDivisors();
vector<int> d1 = divisors;
scanf("%d", &b);
getFactors(b);
divisors.clear();
getDivisors();
vector<int> d2 = divisors;
sort(d1.begin(), d1.end());
sort(d2.begin(), d2.end());
vector<int> cd;
set_intersection(d1.begin(), d1.end(), d2.begin(), d2.end(), inserter(cd,
cd.begin()));
scanf("%d", &n);
int low, high, ind;
for (int i = 0; i < n; i++) {
scanf("%d%d", &low, &high);
ind = upper_bound(cd.begin(), cd.end(), high) - cd.begin();
ind--;
if (ind == -1 || cd[ind] < low)
printf("-1
");
else
printf("%d
", cd[ind]);
}
return 0;
}
|
75
|
D
|
Big Maximum Sum
|
Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.
This problem is similar to a standard problem but it has a different format and constraints.
In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.
But in this problem you are given $n$ small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.
For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.
Can you help Mostafa solve this problem?
|
This problem is my favorite one in this problem set. Maybe it will be easier to solve this problem if you know how to solve the standard one. But because we can't construct the big array, so we can't apply the standard solution for this problem. Let's see first how to solve the standard problem, the following code solves it for a given array arr with length len: int mx = -(1 << 30); int sum = 0; for (int j = 0; j < len; j++) { mx = max(mx, arr[i]); // we need this for the case where all elements in the array are negatives sum += arr[i]; if (sum < 0) sum = 0; else mx = max(mx, sum); } Now let's solve the big array problem, the first step is to calculate 4 values for each small array: 1- The total sum of it, let's call it tot. 2- The maximum sum of 0 or more consecutive elements starting from the first element in the array, let's call it lft. 3- The maximum sum of 0 or more consecutive elements ending at the last element in the array, let's call it rght. 4- The maximum sum of 1 or more consecutive elements, let's call it gen. The final result will be 1 of 2 cases: 1- The consecutive elements with the maximum sum will start and end inside the same small array. 2- The consecutive elements with the maximum sum will start and end inside different small arrays. For the first case, we can simply pick the maximum gen for all small arrays which exist in the big array. For the second case, we can apply something similar to the standard solution, we will keep a variable called sum, and it's initialized to 0, this will be the maximum sum of 0 or more consecutive elements ending at the last element in the previous small array. Now for each small array, if the maximum possible sum will end in this small array, so it will be sum+lft and maximize over this value (make sure this will be for 1 or more elements). And we need to update sum to be the maximum of the following 3 values: 1- sum+tot (we will include all elements of this small array to the old sum). 2- rght (we will take the maximum sum ending at the last element in the current small array). 3- 0 (we will not take any elements in sum). The running time for this solution will be just for reading the input, in my solutions I have no iterations except for reading the input. You can check my solutions for more clarification.
|
[
"data structures",
"dp",
"greedy",
"implementation",
"math",
"trees"
] | 2,000
|
#include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <complex>
#include <list>
#include <climits>
#include <cctype>
using namespace std;
int n, m;
long long gen[50], lft[50], rght[50], tot[50];
int main() {
scanf("%d%d", &n, &m);
int len, num;
for (int i = 0; i < n; i++) {
scanf("%d", &len);
int mx = -(1 << 30);
int sum = 0;
for (int j = 0; j < len; j++) {
scanf("%d", &num);
tot[i] += num;
lft[i] = max(lft[i], tot[i]);
rght[i] = min(rght[i], tot[i]);
mx = max(mx, num);
sum += num;
if (sum < 0)
sum = 0;
else
mx = max(mx, sum);
}
gen[i] = mx;
rght[i] = tot[i] - rght[i];
}
long long cur = 0;
long long best = (long long) (-1e18);
while (m--) {
int i;
scanf("%d", &i);
i--;
best = max(best, gen[i]);
if (cur)
best = max(best, cur + lft[i]);
cur = max(0ll, max(rght[i], cur + tot[i]));
}
cout << best << endl;
return 0;
}
|
75
|
E
|
Ship's Shortest Path
|
You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.
And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.
You can \textbf{only} move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.
But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.
You can move your ship on the island edge, and it will be considered moving in the sea.
Now you have a sea map, and you have to decide what is the minimum cost for your trip.
Your starting point is ($xStart$, $yStart$), and the end point is ($xEnd$, $yEnd$), both points will be different.
The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.
|
The main idea for this problem is not hard, but maybe the hard part is implementing it. First we need to know if the straight line segment between the source and destination points intersect with the island or not. So we will intersect this line segment with all the polygon sides. If there are 2 segments intersect in more than 1 point we will consider as they don't intersect, because it's mentioned in the problem statement that you can move on the island's edge and it will be considered in the sea. Now we have a set of all distinct intersection points of the polygon and the straight line segment between the source and destination points. Because the polygon is convex, this set will contain at most 2 points. We have 3 different cases now: 1- This set contains less than 2 points. 2- This set contains 2 points and they are on the same polygon side. 3- This set contains 2 points and they are not on the same polygon side. In the first 2 cases the result will be simply the length of the straight line segment. In the 3rd case you can do the following: 1- Move from the source point to the nearest point of the 2 intersection points. 2- You have 3 options here: a- Move inside the island to the other intersection point. b- Move in clockwise direction on the island's edge to the other intersection point. c- Move in anti-clockwise direction on the island's edge to the other intersection point. First option will be considered moving inside the island, and the other 2 options will be considered moving in the sea. You should pick the minimum one. 3- Move from the 2nd intersection point to the destination point. Another solution: You can construct a graph where the nodes are the source point, the destination point, the intersection points and the polygon corner points. Then add an edge between any 2 points which you can move between them with the corresponding cost. Then run any shortest path algorithm, Floyd Warshall for example. You can check my solutions for more clarification.
|
[
"geometry",
"shortest paths"
] | 2,400
|
#include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <set>
#include <complex>
#include <list>
#include <climits>
#include <cctype>
using namespace std;
typedef complex<double> point;
#define cross(a,b) ((conj(a)*(b)).imag())
#define X real()
#define Y imag()
const double eps = 1e-9;
int comp(double a, double b) {
if (fabs(a - b) < eps)
return 0;
return a > b ? 1 : -1;
}
struct pComp {
bool operator()(const point &A, const point &B) const {
if (comp(A.X, B.X))
return A.X < B.X;
if (comp(A.Y, B.Y))
return A.Y < B.Y;
return 0;
}
};
double len(point A, point B) {
return hypot(A.X - B.X, A.Y - B.Y);
}
bool pointOnSeg(point A, point B, point R) {
return comp(len(A, B), len(A, R) + len(B, R)) == 0;
}
bool lineInter(point A, point B, point P, point Q, point &R) {
double d1 = cross(P-A,B-A);
double d2 = cross(Q-A,B-A);
if (comp(d1, d2) == 0)
return false;
R = (d1 * Q - d2 * P) / (d1 - d2);
if (!pointOnSeg(A, B, R) || !pointOnSeg(P, Q, R))
return false;
return true;
}
int n;
point st, en;
vector<point> pol;
double mat[34][34];
int main() {
int x, y;
cin >> x >> y;
st = point(x, y);
cin >> x >> y;
en = point(x, y);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x >> y;
pol.push_back(point(x, y));
}
double ret = len(st, en);
set<point, pComp> intrs;
for (int i = 0; i < n; i++) {
point R;
if (lineInter(st, en, pol[i], pol[(i + 1) % n], R))
intrs.insert(R);
}
if (intrs.size() == 2) {
point p1 = *intrs.begin();
point p2 = *(++intrs.begin());
double d1 = -1, d2 = 0;
for (int i = 0; i < n; i++) {
int j = (i + 1) % n;
d2 += len(pol[i], pol[j]);
if (d1 == -1 && pointOnSeg(pol[i], pol[j], p1)) {
if (pointOnSeg(pol[i], pol[j], p2))
goto PRINT;
d1 = len(p1, pol[j]);
while (1) {
int j2 = (j + 1) % n;
if (pointOnSeg(pol[j], pol[j2], p2)) {
d1 += len(pol[j], p2);
break;
}
d1 += len(pol[j], pol[j2]);
j = j2;
}
}
}
d2 -= d1;
double d3 = len(p1, p2);
ret -= d3;
d3 *= 2;
ret += min(d3, min(d1, d2));
}
PRINT: ;
printf("%.9lf
", ret);
return 0;
}
|
76
|
A
|
Gift
|
The kingdom of Olympia consists of $N$ cities and $M$ bidirectional roads. Each road connects exactly two cities and two cities can be connected with more than one road. Also it possible that some roads connect city with itself making a loop.
All roads are constantly plundered with bandits. After a while bandits became bored of wasting time in road robberies, so they suggested the king of Olympia to pay off. According to the offer, bandits want to get a gift consisted of gold and silver coins. Offer also contains a list of restrictions: for each road it is known $g_{i}$ — the smallest amount of gold and $s_{i}$ — the smallest amount of silver coins that should be in the gift to stop robberies on the road. That is, if the gift contains $a$ gold and $b$ silver coins, then bandits will stop robberies on all the roads that $g_{i} ≤ a$ and $s_{i} ≤ b$.
Unfortunately kingdom treasury doesn't contain neither gold nor silver coins, but there are Olympian tugriks in it. The cost of one gold coin in tugriks is $G$, and the cost of one silver coin in tugriks is $S$. King really wants to send bandits such gift that for any two cities there will exist a safe path between them. Your task is to find the minimal cost in Olympian tugriks of the required gift.
|
Suppose that the pair $(A, B)$ is an optimal solution, where $A$ is the number of gold coins in a gift and $B$ is a number of silver coins. It is easy to see that there exist two (probably equal) indexes $i$ and $j$ such that $g_{i} = A$ and $s_{j} = B$. It is true, because in the other case we could decrease either $A$ or $B$ without changing connectivity of the graph. Let $R(A, B)$ be the graph in which for all $i$ the following statement holds: $g_{i}\leq A\wedge s_{i}\leq B$. Let $T(A)$ be the weighted graph in which for all edges $g_{i} \le A$. For each edge $i$ we will assign a weight equal to $s_{i}$. Let's find a spanning tree of this graph, which has the property that its maximal edge is minimal possible. It can be shown that for the fixed $A$ the minimal value of $B$ for which graph $R(A, B)$ is still connected is equal to the weight of the maximal edge in this spanning tree. Claim. Minimal spanning tree of a graph has the property that its maximal edge is minimal possible among all spanning trees. Proof. Let $L$ be the minimal spanning tree of a graph. Suppose there exists a spanning tree $P$ in which all edges have smaller weight than the weight of the maximal edge of $L$. We can then remove the maximal edge from $L$ and add some edge from $P$ to it which will connect the graph back. After that $L$ will have strictly smaller weight, which is impossible because it is a minimal spanning tree. Let's sort all edges of the graph in ascending order of $g_{i}$. Then the edges of graph $T(A)$ for the fixed $i$ will be all edges with indexes $j \le i$. Suppose that for some value of $i$ we have already found minimal spanning tree in every connected component of the graph $T(g_{i})$. Let's add an edge with index $i + 1$ into it. If it connects two different components, then after this operation they will be merged into one big component and it is obviously that the spanning tree we have in it is the minimal spanning tree. If $i + 1$-th edge connects two vertices from the same connected component, then it will create exactly one cycle in the graph. We can find the maximal edge in this cycle and remove it from the graph. It can be proven that the remaining tree will be the minimal spanning tree of this connected component. We can perform the search of the maximal edge in a cycle as well as the insertion and removal of the edges in O(N). The total complexity is $O(NM + MlogM)$.
|
[
"dsu",
"graphs",
"sortings",
"trees"
] | 2,200
| null |
76
|
B
|
Mice
|
Modern researches has shown that a flock of hungry mice searching for a piece of cheese acts as follows: if there are several pieces of cheese then each mouse chooses the closest one. After that all mice start moving towards the chosen piece of cheese. When a mouse or several mice achieve the destination point and there is still a piece of cheese in it, they eat it and become well-fed. Each mice that reaches this point after that remains hungry. Moving speeds of all mice are equal.
If there are several ways to choose closest pieces then mice will choose it in a way that would minimize the number of hungry mice. To check this theory scientists decided to conduct an experiment. They located $N$ mice and $M$ pieces of cheese on a cartesian plane where all mice are located on the line $y = Y_{0}$ and all pieces of cheese — on another line $y = Y_{1}$. To check the results of the experiment the scientists need a program which simulates the behavior of a flock of hungry mice.
Write a program that computes the minimal number of mice which will remain hungry, i.e. without cheese.
|
It is easy to see that the number of closest pieces of cheese for each mouse is not greater than 2. Let's find the closest pieces of cheese for each mouse to the left and to the right from it. From two directions we will choose the one which gives us shorter way to cheese or both of them if their lengths are equal. If on the chosen way between the mouse and the cheese stands another mouse, then we should exclude this way from consideration, because another mouse will get to the cheese faster. Now all the directions lead to cheese and for each piece of cheese there is at most one mouse which can potentially eat it from each direction. We will process mice from left to right. If the current mouse can move left and the cheese to the left of it is not chosen by any other mouse or it is chosen by a mouse with the same distance to it, then the current mouse can move to the left and eat this piece of cheese without interfering with other mice. This choice will not affect any choices of the next mice, because only one mouse can go to this piece of cheese from the right (see previous paragraph). Thus, this choice can not decrease the answer. In all other cases the current mouse can not increase the answer by moving left, so it should move to the right if it has such opportunity. The complexity is $O(N + M)$. This problem can be also solved using dynamic programming.
|
[
"greedy",
"two pointers"
] | 2,100
| null |
76
|
C
|
Mutation
|
Scientists of planet Olympia are conducting an experiment in mutation of primitive organisms. Genome of organism from this planet can be represented as a string of the first $K$ capital English letters. For each pair of types of genes they assigned $a_{i, j}$ — a risk of disease occurence in the organism provided that genes of these types are adjacent in the genome, where $i$ — the 1-based index of the first gene and $j$ — the index of the second gene. The gene 'A' has index 1, 'B' has index 2 and so on. For example, $a_{3, 2}$ stands for the risk of 'CB' fragment. Risk of disease occurence in the organism is equal to the sum of risks for each pair of adjacent genes in the genome.
Scientists have already obtained a base organism. Some new organisms can be obtained by mutation of this organism. Mutation involves removal of all genes of some particular types. Such removal increases the total risk of disease occurence additionally. For each type of genes scientists determined $t_{i}$ — the increasement of the total risk of disease occurence provided by removal of all genes having type with index $i$. For example, $t_{4}$ stands for the value of additional total risk increasement in case of removing all the 'D' genes.
Scientists want to find a number of different organisms that can be obtained from the given one which have the total risk of disease occurence not greater than $T$. They can use only the process of mutation described above. Two organisms are considered different if strings representing their genomes are different. Genome should contain at least one gene.
|
In the editorial we will replace terms "risk", "genome" and "gene" with "cost", "string" and "character", respectively. Let $S$ be the starting string. Let $M$ be the bitmask of chars which will be removed. Let's iterate over all possible values of $M$. For the fixed $M$ we need to find a cost of the string, which remained after removal of $M$ and if this cost doesn't exceed $T$ we will increase the answer by 1. Naive implementation of this idea has the complexity $O(2^{K}N)$. We can not get rid of iterating over all $M$, so we will try to optimize a part of the algorithm which finds a cost of the remaining string. Let's take two indexes $l$ and $r$ from the beginning string $l < r$. Let $M'$ be the bitmask of all characters which are located strictly between them. It is obviously that if $S_{l}\in M^{\prime}$ or $S_{r}\in M^{\prime}$ then $l$ and $r$ can not be neighbours in the remaining string. Hence for the fixed $l$ there are not more than $K$ possible candidates for $r$, which means that there are $O(NK)$ pairs of such potential neighbours. We will call such pairs "good". We want to find out what form should have the set $M$ that after its removal indexes $l$ and $r$ became adjacent. It is easy to see that the following two conditions should be true: 1. $M^{\prime}\subset M$ 2. $S_{l}\not\in M\wedge S_{r}\not\in M$ Let's iterate over all good pairs of $l$ and $r$ and for each of them we will find the set $M'$. For each triple $(a, b, P)$ we will store the sum of costs of neighborhood of all pairs $l$ and $r$ for which $S_{l} = a$, $S_{r} = b$, $M' = P$. After that for the fixed $M$ we will iterate over all pairs of characters $(a, b)$ and its subsets $P$ and add all their costs together. Also we need to add the cost of removal of $M$ and the resulting sum will be the cost of the string which will left after removal of $M$. The complexity of such solution is $O(3^{K} * K^{2} + NK)$. We will optimize the previous solution by decreasing a factor near $3^{K}$. Let's look at the following (incorrect) algorithm: We will iterate over all good pairs $l$ and $r$ and for each of them we will find $M'$. Let's create an array $v$ in which for each mask $P$ we will store the sum of costs of neighborhood of all pairs $l$ and $r$ for which $M' = P$. For the fixed $M$ we will find a sum of all values from $v$ for all submasks of $M$, then add the cost of removal of $M$ to it and the resulting sum will be the cost of the remaining string. This algorithm is incorrect, because some costs of neighborhood are added to the total cost, but in fact the respective $l$ or $r$ are removed. Let's use inclusion-exclusion principle and make the following at the phase of filling array $v$: $v[M'] + = cost$ $v[M^{\prime}\cup\{S_{i}\}]-=c o s l$ $v[M^{\prime}\cup\{S_{r}\}]-=c o s t$ $v[M^{\prime}\cup\{S_{l},S_{r}\}]+=c o s t$ With such filling of $v$ the algorithm described above is correct and the total complexity becomes $O(3^{K} + NK)$. This is still not enough for the full solution, but we are almost there. We only need to find a fast way of finding the sum of the values of $v$ for all submasks of all masks $M$. We will use the following iterative algorithm for this purpose: Before the first iteration we have an array $v$ in which the starting values are stored. After iteration with number $i$ in $v[mask]$ we will store the sum of all the values from the original array $v$ for all submasks of $mask$ for which the first $K - i$ bits are equal to the respective bits of $mask$. On iteration with number $i$ for all masks in which the $i$-th bit is equal to 1 (bits are numbered from 1) we will perform the following: $v[mask] + = v[mask\{i}]$. It is easy to see that after the $K$-th iteration of this algorithm we will have the values we were looking for in array $v$. The complexity is $O(2^{K}K + NK)$.
|
[
"bitmasks",
"dp",
"math"
] | 2,700
| null |
76
|
D
|
Plus and xor
|
Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions in the operands are different.
For example, if $X = 109_{10} = 1101101_{2}$, $Y = 41_{10} = 101001_{2}$, then:
\begin{center}
$X$ xor $Y = 68_{10} = 1000100_{2}$.
\end{center}
Write a program, which takes two non-negative integers $A$ and $B$ as an input and finds two non-negative integers $X$ and $Y$, which satisfy the following conditions:
- $A = X + Y$
- $B = X$ xor $Y$, where xor is bitwise exclusive or.
- $X$ is the smallest number among all numbers for which the first two conditions are true.
|
Let's take a look at some bit in X, which is equal to 1. If the respective bit in Y is equal to 0, then we can swap these two bits, thus reducing X and increasing Y without changing their sum and xor. We can conclude that if some bit in X is equal to 1 then the respective bit in Y is also equal to 1. Thus, $Y = X + B$. Taking into account that $X + Y = X + X + B = A,$ we can obtain the following formulas for finding $X$ and $Y$: $X = (A - B) / 2$ $Y = X + B$ One should also notice that if $A < B$ or $A$ and $B$ have different parity, then the answer doesn't exist and we should output -1. If $X$ $and$ $(A - X) \neq X$ then the answer is also -1.
|
[
"dp",
"greedy",
"math"
] | 1,700
| null |
76
|
E
|
Points
|
You are given $N$ points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
|
Let's regroup summands and split the sum of squares of distances we are looking for into two sums: ${\textstyle\sum_{i=1}^{N}\sum_{j=1}^{i-1}(x_{i}-x_{j})^{2}+(y_{i}-y_{j})^{2}}$ $\begin{array}{r}{\sum_{i=1}^{N}\sum_{j=1}^{k-1}(x_{i}-x_{j})^{2}+\sum_{i=1}^{N}\sum_{j=1}^{i-1}(y_{i}-y_{j})^{2}}\end{array}$ Now we need to rewrite each of these sums in the following way (it will be shown for the first sum): $\textstyle{\sum_{i=1}^{N}\sum_{j=1}^{i-1}(x_{i}-x_{j})^{2}=\sum_{i=1}^{N}\sum_{j=1}^{i-1}(x_{i}^{2}-2x_{i}x_{j}+x_{j}^{2})=}$ $\textstyle\sum_{i=1}^{N}((i-1)x_{i}^{2}-2x_{i}\sum_{j=1}^{i-1}x_{j}+\sum_{j=1}^{i-1}x_{j}^{2})$ This formula allows us to find an answer in one pass through the array. The complexity is O(N).
|
[
"implementation",
"math"
] | 1,700
| null |
76
|
F
|
Tourist
|
Tourist walks along the $X$ axis. He can choose either of two directions and any speed not exceeding $V$. He can also stand without moving anywhere. He knows from newspapers that at time $t_{1}$ in the point with coordinate $x_{1}$ an interesting event will occur, at time $t_{2}$ in the point with coordinate $x_{2}$ — another one, and so on up to ($x_{n}, t_{n}$). Interesting events are short so we can assume they are immediate. Event $i$ counts visited if at time $t_{i}$ tourist was at point with coordinate $x_{i}$.
Write program tourist that will find maximum number of events tourist if:
- at the beginning (when time is equal to 0) tourist appears at point 0,
- tourist can choose initial point for himself.
Yes, you should answer on two similar but different questions.
|
We can get to the event $j$ from the event $i$ if the following statements are true: $t_{i} \le t_{j}$ $|x_{i} - x_{j}| \le |t_{i} - t_{j}| \cdot V$ We can represent all the events as points on a plane with coordinates $(x_{i}, t_{i})$. Now we can reformulate the two statements written above in the following way: From the event $i$ we can get to the event $j$ if the point $(x_{j}, t_{j})$ lise inside an angle pointed to the top with its vertex in $(x_{i}, t_{i})$ and its sides form an angle $arctg(V)$ with vertical axis. Let's make coordinate transformation according to which the point with coordinates $(x_{i}, t_{i})$ will transform into the point $(p_{i}, q_{i})$, where $p_{i} = - x_{i} + t_{i} * V$ $q_{i} = x_{i} + t_{i} * V$ Now we can get to the event $j$ from the event $i$ if $p_{i} \le p_{j}$ and $q_{i} \le q_{j}$. Let's sort all points in ascending order of $p$. If several points have the same $p$ we will sort them by $q$. The second subproblem of our problem can be solved by finding a longest increasing subsequence by $q$ in this array. It can be done in $O(NlogN)$. To solve the first subproblem we can add dummy event with coordinate 0 and time 0 (if it is not present in our set of events yet) and force tourist's start from it. The total complexity if $O(NlogN)$.
|
[
"binary search",
"data structures",
"dp"
] | 2,300
| null |
77
|
A
|
Heroes
|
The year of 2012 is coming...
According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil.
The seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: $a$ for Mephisto, $b$ for Diablo and $c$ for Baal.
Here's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a $\scriptstyle{\frac{\pi}{y}}$ of experience, rounded down, where $x$ will be the amount of experience for the killed megaboss and $y$ — the number of people in the team.
Heroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which \underline{the total amount of liking in teams} were maximum.
It is known that some heroes like others. But if hero $p$ likes hero $q$, this does not mean that the hero $q$ likes hero $p$. No hero likes himself.
The total amount of liking in teams is the amount of ordered pairs $(p, q)$, such that heroes $p$ and $q$ are in the same group, and hero $p$ likes hero $q$ (but it is not important if hero $q$ likes hero $p$). In case of heroes $p$ and $q$ likes each other and they are in the same group, this pair should be counted twice, as $(p, q)$ and $(q, p)$.
A team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team.
It is guaranteed that every hero is able to destroy any megaboss alone.
|
It is possble to solve this problem by full search because there are only $k = 7$ heroes and three team. Let's find all dividings - move every hero in every team and drop away incorrect dividings when al least one team is empty. In each correct dividing we should find value of experience between two heroes who will receive the maximum and minimum number of experience points and value of total amount of liking in teams. Now we should choose the best way and write it. Complexity is $O(3^{k} \cdot k^{2})$.
|
[
"brute force",
"implementation"
] | 1,400
| null |
77
|
B
|
Falling Anvils
|
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height $p$ of the potential victim vary in the range $[0;a]$ and the direction of the wind $q$ vary in the range $[ - b;b]$. $p$ \textbf{and} $q$ \textbf{could be any real (floating) numbers.} Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
\begin{center}
$x^{2}+{\sqrt{p}}\cdot x+q=0$
\end{center}
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the $p$ and $q$ coefficients are chosen equiprobably and independently in their ranges.
|
In this problem you were to determine the probability if the equation $x^{2}+{\sqrt{p}}\cdot x+q=0$ has at least one real root, assuming that values $p$ and $q$ are independent and equiprobable. It's equivalent to the condition of non-negativity of the discriminant $D = p - 4q$. To solve this problem you might draw a rectangle on the (p,q)-plane with the vertices in points $(0, - b)$, $(a, - b)$, $(a, b)$ and $(0, b)$ and line $p = 4q$. Every point of the rectangle corresponds to possible value of $p$ and $q$ and the line divides the plane into two parts where the equation has real solutions and where it hasn't. Then because of equiprobability and independence of choosing $p$ and $q$ the answer is the area of the intersection of the rectangle and $p \ge 4q$ set divided by the area of the rectangle in case of it's nonsingularity ($a, b \neq 0$). If single number among $a$ and $b$ is equal to zero, the rectangle degenerates to the segment and the sough-for probability is equal to ratio of length of intersection of the segment and $p \ge 4q$ set and the lenght of the whole segment. In case $a = b = 0$ the answer is evident and equal to 1. Complexity is $O(t)$. If you are interested in why your solution gets "wrong answer" the mini-tests "0 1", "1 0" and "0 0" maybe helps you.
|
[
"math",
"probabilities"
] | 1,800
| null |
77
|
C
|
Beavermuncher-0xFF
|
"Eat a beaver, save a tree!" — That will be the motto of ecologists' urgent meeting in Beaverley Hills.
And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with trees harms the nature and the humankind. The amount of oxygen in the atmosphere has dropped to 17 per cent and, as the best minds of the world think, that is not the end.
In the middle of the 50-s of the previous century a group of soviet scientists succeed in foreseeing the situation with beavers and worked out a secret technology to clean territory. The technology bears a mysterious title "Beavermuncher-0xFF". Now the fate of the planet lies on the fragile shoulders of a small group of people who has dedicated their lives to science.
The prototype is ready, you now need to urgently carry out its experiments in practice.
You are given a tree, completely occupied by beavers. A tree is a connected undirected graph without cycles. The tree consists of $n$ vertices, the $i$-th vertex contains $k_{i}$ beavers.
"Beavermuncher-0xFF" works by the following principle: being at some vertex $u$, it can go to the vertex $v$, if they are connected by an edge, and eat \textbf{exactly one} beaver located at the vertex $v$. It is impossible to move to the vertex $v$ if there are no beavers left in $v$. "Beavermuncher-0xFF" \textbf{cannot} just stand at some vertex and eat beavers in it. "Beavermuncher-0xFF" must move without stops.
Why does the "Beavermuncher-0xFF" works like this? Because the developers have not provided place for the battery in it and eating beavers is necessary for converting their mass into pure energy.
It is guaranteed that the beavers will be shocked by what is happening, which is why they will not be able to move from a vertex of the tree to another one. As for the "Beavermuncher-0xFF", it can move along each edge in both directions while conditions described above are fulfilled.
The root of the tree is located at the vertex $s$. This means that the "Beavermuncher-0xFF" begins its mission at the vertex $s$ and it must return there at the end of experiment, because no one is going to take it down from a high place.
Determine the maximum number of beavers "Beavermuncher-0xFF" can eat and return to the starting vertex.
|
Let's assume that in vertix $v$ it is possible to find pair of values $< x_{i}, y_{i} >$ for every child $v_{i}$ where $x_{i}$ is maximal amount of beavers which can eat beavermuncher if it comes to vertix $v_{i}$ and return back, and $y_{i}$ is amount of beavers which will still alive in vertix $v_{i}$ after beavermuncher's ride. Let's sort all children $v_{i}$ by value of $x_{i}$. We should visit $v_{i}$ in sorted order from highest value of $x_{i}$ to lowest while there is possible to return back to root. If after ride to all children vertix $v$ contains of some non-eaten beavers we must continue eating by following way. Let's find some value of $y_{j}$ which is greater than zero. We should move to vertix $v_{j}$ and after that move back to $v$. This operation must be executed as many times as possible. Of course, the process shouldn't be emulated, we may repeat this way with vertix $v_{j}$ for $min(b, y_{j})$ times, where $b$ is amount of beavers in vertix $v$ which are remaining. So we find a pair $< x, y >$ for vertix $v$ by knowing values $< x_{i}, y_{i} >$ for every child $v_{i}$, where $x$ is amount of eaten beavers and $y$ is $b$ - number of remaining beavers. Answer is a value of $x$ for staring vertix $s$. Complexity is $O(n \cdot logn)$. If you are interested in why your solution gets "wrong answer" the tests with $n = 1$ maybe helps you.
|
[
"dfs and similar",
"dp",
"dsu",
"greedy",
"trees"
] | 2,100
| null |
77
|
D
|
Domino Carpet
|
...Mike the TV greets you again!
Tired of the monotonous furniture? Sick of gray routine? Dreaming about dizzying changes in your humble abode? We have something to offer you!
This domino carpet for only $99.99 will change your life! You can lay it on the floor, hang it on the wall or even on the ceiling! Among other things ...
Having watched the commercial, virus Hexadecimal also wanted to get a Domino Carpet and wanted badly to be photographed in front of it. But of course, a virus will never consent to buying a licensed Carpet! So she ordered a truck of dominoes and decided to make such a Carpet herself.
The original Domino Carpet is a field of squares $n × m$ in size. Each square is half of a domino, and can be rotated either vertically or horizontally, independently from its neighbors. Vertically rotated domino halves look like this:
And horizontally rotated halves look like this:
Notice, that some halves looks the same in both rotations, but other halves differ.
Dominoes bought by Hexadecimal are represented by uncuttable chips $1 × 2$ in size, which can be laid either vertically or horizontally. If the chip is laid vertically, then both of it's halves should be laid vertically orientated; if the chip is laid horizontally, then both of it's halves should be laid horizontally.
The samples of valid and invalid dominoes laid vertically and horizontally are:
Virus Hexadecimal assembles her own Domino Carpet so that the following conditions are satisfied:
- each carpet square is covered by a domino chip, i.e. there are no empty squares;
- all domino chips lie entirely within the carpet and don't overlap with each other;
- if there is a horizontal domino chip with its left half in column $j$ then there are no horizontal domino chips with their left halves in columns $j - 1$ or $j + 1$.
Before starting to assemble her own Domino Carpet, the virus wants to know the number of ways to achieve the intended purpose modulo $10^{9} + 7$.
You can assume that the virus has an infinitely large number of dominoes of each type.
|
Look at squares of Domino Carpet. They are can be only in one of this three states: 1. Here can be any domino chip 2. Here can be only horizontal domino chip 3. Here can be only vertical domino chip No matter what is in squares, only their states are important. Look at the any pair of columns $j$ and $j + 1$ where in some row located horizontally chip of domino. We may cut this pair of jointed columns $n \times 2$ from carpet and don't be afraid about cutting some another chips. So, this pair of columns may be completed independently from another columns. If $n$ is even number it is possible to complete some columns of single width, not only pair of columns. There is only way to do this - we should put all dominoes vertically. This formula is describing all situations above: $d_{j} = (d_{j} - _{2} \cdot q_{j} - _{2}) + (d_{j} - _{1} \cdot p_{j} - _{1})$, where $j$ is an amount of completed columns, $p_{j}$ is an amount of all possible ways to complete only $j$-th column (it can be only 0 or 1) and $q_{j}$ is an amount of all possible ways to complete $j$-th and $j + 1$-th columns. Obviously, this formula is incorrect. If some pair of jointed columns we will complete by only vertical dominoes then this way will be counted twice. Let's use the fact that it is unique situation when this formula is incorrect and improve it: So, $d_{j} = (d_{j} - _{2} \cdot q_{j} - _{2}) + (d_{j} - _{1} \cdot p_{j} - _{1}) - (d_{j} - _{2} \cdot p_{j} - _{2} \cdot p_{j} - _{1})$. In $d_{m}$ is answer to the problem. The only trouble is we need to count $p_{j}$ and $q_{j}$. $p_{j}$ is 1 when $n$ is even and in $j$-th column there are no squares in state "here can be only horizontal domino chip". Otherwise $p_{j}$ is 0. $q_{j}$ can be found by dynamic programming. For every row we should try to put one horizontally oriented domino chip or two vertically oriented and use information about states in observable squares of carpet. Complexity is $O(n \cdot m)$.
|
[
"dp",
"implementation"
] | 2,300
| null |
77
|
E
|
Martian Food
|
Have you ever tasted Martian food? Well, you should.
Their signature dish is served on a completely black plate with the radius of $R$, flat as a pancake.
First, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of $r$ and is located as close to the edge of the plate as possible staying entirely within the plate. I. e. Golden Honduras touches the edge of the plate from the inside. It is believed that the proximity of the portion of the Golden Honduras to the edge of a plate demonstrates the neatness and exactness of the Martians.
Then a perfectly round portion of Pink Guadeloupe is put on the plate. The Guadeloupe should not overlap with Honduras, should not go beyond the border of the plate, but should have the maximum radius. I. e. Pink Guadeloupe should touch the edge of the plate from the inside, and touch Golden Honduras from the outside. For it is the size of the Rose Guadeloupe that shows the generosity and the hospitality of the Martians.
Further, the first portion (of the same perfectly round shape) of Green Bull Terrier is put on the plate. It should come in contact with Honduras and Guadeloupe, should not go beyond the border of the plate and should have maximum radius.
Each of the following portions of the Green Bull Terrier must necessarily touch the Golden Honduras, the previous portion of the Green Bull Terrier and touch the edge of a plate, but should not go beyond the border.
To determine whether a stranger is worthy to touch the food, the Martians ask him to find the radius of the $k$-th portion of the Green Bull Terrier knowing the radii of a plate and a portion of the Golden Honduras. And are you worthy?
|
The problem can be solved using the inversion conversion. Inversion is the conversion transfering a point with the polar coordinates $(r, \phi )$ to a point $\bigl({\frac{1}{\tau}},\varphi\bigr)$. It's stated that the inversion transfers straight lines or circles to straight lines or circles. Straight line can be image only of line or circle that includes home (center of the inversion). Assume the plate a circle with center in $(R, 0)$ and radius $R$ and Honduras - circle with center in $(r, 0)$ ans radius $r$. Then Guadeloupe and Bull Terriers are situated as on the first picture. Picture 1. Original picture Picture 2. After inversion conversion After applying the inversion conversion the border of the plate transfers to the line $x={\frac{1}{2R}}$ and the border of the honduras - to the line $x={\frac{1}{2r}}$, Guadeloupe and Bull Terriers becomes circles between them, see the second picture. It's easy to find the $k$-th bull terrier on the picture after applying the conversion, the coordinates of it's center are $\left({\frac{R+r}{4r R}},k\,{\frac{k\,\ell-r}{2r R}}\right)$. To find the radius of the bull terier draw a line through the home and the center of the image of the need honduras. It's possible to prove that the prototypes of this points are diametral points on the bull terrier. So the answer is the distance between them divided by two. Complexity is $O(t)$.
|
[
"geometry"
] | 2,800
| null |
78
|
A
|
Haiku
|
Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.
To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".
Three phases from a certain poem are given. Determine whether it is haiku or not.
|
You should count a number of vowels for every of three phrases. Next, you should compare this numbers with numbers 5, 7 and 5. If all is matched, answer is YES, otherwise answer is NO.
|
[
"implementation",
"strings"
] | 800
| null |
78
|
B
|
Easter Eggs
|
The Easter Rabbit laid $n$ eggs in a circle and is about to paint them.
Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:
- Each of the seven colors should be used to paint at least one egg.
- Any four eggs \textbf{lying sequentially} should be painted different colors.
Help the Easter Rabbit paint the eggs in the required manner. We know that it is always possible.
|
At first, you can $[n / 7]$ times output string "ROYGBIV" ($[]$ is a rounding down). After than you can output "", "G", "GB", "YGB", "YGBI", "OYGBI" or "OYGBIV" according to remainder of division $n$ by 7. A resulting string will satisfy problem's requirements. You can also build answer in other way.
|
[
"constructive algorithms",
"implementation"
] | 1,200
| null |
78
|
C
|
Beaver Game
|
Two beavers, Timur and Marsel, play the following game.
There are $n$ logs, each of exactly $m$ meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of \textbf{equal} parts, the length of each one is expressed by an integer and is no less than $k$ meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
|
If $n$ is even, Marsel wins - he just symmetrically repeats moves of Timur. Now consider a case of odd $n$. If Timur cannot move - he is losing automatically. If he can do a move, he always can split one log into few parts that this parts cannot be splitted again. It can be done if we have find minimal $t$ that $k \le t < m$ and $t|m$. Next we split log into parts with length $t$. Thereafter Timur symmetrically repeats moves of Marsel and wins. For checking that Timur could move or not, you can iterate over all divisors of $m$. If there is exists some divisor $t$ that $k \le t < m$, Timar can do a move. Chech of all divisors can be done in $O({\sqrt{m}})$ time.
|
[
"dp",
"games",
"number theory"
] | 2,000
| null |
78
|
D
|
Archer's Shot
|
A breakthrough among computer games, "Civilization XIII", is striking in its scale and elaborate details. Let's take a closer look at one of them.
The playing area in the game is split into congruent cells that are regular hexagons. The side of each cell is equal to 1. Each unit occupies exactly one cell of the playing field. The field can be considered infinite.
Let's take a look at the battle unit called an "Archer". Each archer has a parameter "shot range". It's a positive integer that determines the radius of the circle in which the archer can hit a target. The center of the circle coincides with the center of the cell in which the archer stays. A cell is considered to be under the archer’s fire if and only if all points of this cell, including border points are located inside the circle or on its border.
The picture below shows the borders for shot ranges equal to $3$, $4$ and $5$. The archer is depicted as $A$.
Find the number of cells that are under fire for some archer.
|
It should be solved like a classical problem "count the number of square cells 1x1 lying inside the circle". Firstly, lets find the highest hexagon that lies inside the circle. Then we move to the right and up from this hexagon, and then go down until we find hexagon lying inside the circle. Repeat this process until you reach the rightmost part of the circle. Thus we can count number of hexagons in each column, answer is sum of this numbers. Total number of operations is $O(n)$. Few words about implementation. Coordinates of every considered point looks like $(\frac{1}{2}x, \frac{\sqrt{3}}{2}y)$. That's why distance between this points and (0,0) should be calculated using integers only. For example, criteria "point $(\frac{1}{2}x, \frac{\sqrt{3}}{2}y)$ lies inside circle of radius $R$" looks like $x^{2} + 3y^{2} \le 4R^{2}$. Also you can solve this problem in $O(n\log n)$. For every column of hexagons you can find number of hexagons inside circle by using binary search.
|
[
"binary search",
"geometry",
"math",
"two pointers"
] | 2,300
| null |
78
|
E
|
Evacuation
|
They've screwed something up yet again... In one nuclear reactor of a research station an uncontrolled reaction is in progress and explosion which will destroy the whole station will happen soon.
The station is represented by a square $n × n$ divided into $1 × 1$ blocks. Each block is either a reactor or a laboratory. There can be several reactors and exactly one of them will explode soon. The reactors can be considered impassable blocks, but one can move through laboratories. Between any two laboratories, which are in adjacent blocks, there is a corridor. Blocks are considered adjacent if they have a common edge.
In each laboratory there is some number of scientists and some number of rescue capsules. Once the scientist climbs into a capsule, he is considered to be saved. Each capsule has room for not more than one scientist.
The reactor, which is about to explode, is damaged and a toxic coolant trickles from it into the neighboring blocks. The block, which contains the reactor, is considered infected. Every minute the coolant spreads over the laboratories through corridors. If at some moment one of the blocks is infected, then the next minute all the neighboring laboratories also become infected. Once a lab is infected, all the scientists there that are not in rescue capsules die. The coolant does not spread through reactor blocks.
There are exactly $t$ minutes to the explosion. Any scientist in a minute can move down the corridor to the next lab, if it is not infected. On any corridor an unlimited number of scientists can simultaneously move in both directions. It is believed that the scientists inside a lab moves without consuming time. Moreover, any scientist could get into the rescue capsule instantly. It is also believed that any scientist at any given moment always has the time to perform their actions (move from the given laboratory into the next one, or climb into the rescue capsule) before the laboratory will be infected.
Find the maximum number of scientists who will be able to escape.
|
Firstly, let's calculate the following value: dp[t][x0][y0][x][y] == true iff scientist from block (x0,y0) can reach block (x,y) in time t, considering toxic coolant. Secondly, let's consider a graph consisting of 4 parts: 1 - source (one vertex) 2 - first fraction (nxn vertices) 3 - second fraction (nxn vertices) 4 - sink (one vertex) Each vertex of each fraction is for one block. Build edge from source to each vertex of the first fraction with capability as number of scientists in corresponding block. Build edge from each vertex of the second fraction to sink with capability as number of rescue capsules in corresponding block. Build edge from vertex (x0,y0) of the first fraction to vertex (x,y) of the second fraction iff dp[T][x0][y0][x][y]==true for at least one T. Capability of this edges is infinity. As one can see, value of maxflow in this graph is answer for the problem. Complexity of this solution is $O(tn^{4} + kn^{6})$, where $k$ is maximum possible number of scientists in each block(in this problem $k = 9$).
|
[
"flows",
"graphs",
"shortest paths"
] | 2,300
| null |
79
|
A
|
Bus Game
|
After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus.
- Initially, there is a pile that contains $x$ 100-yen coins and $y$ 10-yen coins.
- They take turns alternatively. Ciel takes the first turn.
- In each turn, they must take exactly 220 yen from the pile. In Ciel's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 100-yen coins. In Hanako's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 10-yen coins.
- If Ciel or Hanako can't take exactly 220 yen from the pile, she loses.
Determine the winner of the game.
|
Brute force simulation works in this problem. In Ciel's turn, if she has at least 2 100-yen coins and at least 2 10-yen coins, pay those coins. Otherwise, if she has at least 1 100-yen coins and at least 12 10-yen coins, pay those coins. Otherwise, if she has at least 22 10-yen coins, pay those coins. Otherwise, she loses. In Hanako's turn, do similar simulation in reverse order. The complexity of this solution is $O(x + y)$.
|
[
"greedy"
] | 1,200
| null |
79
|
B
|
Colorful Field
|
Fox Ciel saw a large field while she was on a bus. The field was a $n × m$ rectangle divided into $1 × 1$ cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes.
After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure:
- Assume that the rows are numbered $1$ to $n$ from top to bottom and the columns are numbered $1$ to $m$ from left to right, and a cell in row $i$ and column $j$ is represented as $(i, j)$.
- First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of $(1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m)$. Waste cells will be ignored.
- Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on.
The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell.
Now she is wondering how to determine the crop plants in some certain cells.
|
A solution that uses an array of $N \times M$ will absolutely get (Time|Memory)LimitExceeded, so we cannot simulate it naively. Both the number of queries and the number of waste cells $K$ are not more than 1,000, so it is enough to answer each queries in $O(K)$ runtime. Let $(a, b)$ be a query cell. Whether $(a, b)$ is waste or not is determined by simple iteration. So let's consider about the case $(a, b)$ is not waste. Let $I$ be the number of cells including waste ones that will be sweeped before $(a, b)$, and $J$ be the number of waste cells that will be sweeped before $(a, b)$. Then, the answer is classified by the value of $(I - J)$ mod $3$ (for example, if the value = 0, the answer = "Carrots", and so on). By simple calculation, $I = (a - 1)M + (b - 1)$, and $J$ is calculated by $O(K)$ iteration. Overall, this problem can be solved in $O(KT)$ runtime, where $T$ is the number of queries.
|
[
"implementation",
"sortings"
] | 1,400
| null |
79
|
C
|
Beaver
|
After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string $s$, and she tried to remember the string $s$ correctly.
However, Ciel feels $n$ strings $b_{1}, b_{2}, ... , b_{n}$ are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of $s$.
Determine the longest contiguous substring of $s$ that does not contain any boring string, so that she can remember the longest part of Taro's response.
|
We can regard a substring that is equal to one of boring strings as an interval. The number of such intervals are at most $|s| \cdot n$, and the required time to determine whether each of them is a boring string is $|b_{i}|$, so all intervals can be calculated in $O(|s| \cdot n \cdot |b_{i}|)$ runtime, by naive way. (Yes, no special string algorithm is required here.) The original problem can be rewritten as follows: you are given at most $10^{6}$ intervals on $[0, 10^{5}]$, determine the longest interval that does not contain any given interval. To solve this rewritten problem, define $right[i]$ be the leftest position of an interval whose left-endpoint is equal to $i$. If there is no interval whose left-endpoint is $i$, define $right[i]$ is $ \infty $. Now we will calculate the optimal interval whose left-endpoint is $i$, in the order of $i = |s|, |s| - 1, |s| - 2, ... 0$. When $i = |s|$, corresponding right-endpoint is only $|s|$. Let's think the case when corresponding right-endpoint to $i + 1$ is $j$. If $right[i] > j$, then corresponding right-point to $i$ remains $j$. Otherwise, that right-point is updated to $right[i] - 1$. This iteration will be done in $O(|s|)$. Overall, $O(|s| \cdot n \cdot |b_{i}|)$ runtime.
|
[
"data structures",
"dp",
"greedy",
"hashing",
"strings",
"two pointers"
] | 1,800
| null |
79
|
D
|
Password
|
Finally Fox Ciel arrived in front of her castle!
She have to type a password to enter her castle. An input device attached to her castle is a bit unusual.
The input device is a $1 × n$ rectangle divided into $n$ square panels. They are numbered $1$ to $n$ from left to right. Each panel has a state either ON or OFF. Initially all panels are in the OFF state. She can enter her castle if and only if $x_{1}$-th, $x_{2}$-th, $...$, $x_{k}$-th panels are in the ON state and other panels are in the OFF state.
She is given an array $a_{1}$, $...$, $a_{l}$. In each move, she can perform the following operation: choose an index $i$ ($1 ≤ i ≤ l$), choose consecutive $a_{i}$ panels, and flip the states of those panels (i.e. ON$ → $OFF, OFF$ → $ON).
Unfortunately she forgets how to type the password with only above operations. Determine the minimal number of operations required to enter her castle.
|
Define an array $b_{0}, b_{1}, ..., b_{n}$ as follows: If the states of $i$-th panel and $(i + 1)$-th panel are same, $b_{i} = 0$. If the states of $i$-th panel and $(i + 1)$-th panel are different, $b_{i} = 1$. (The states of $0$-th panel and $(n + 1)$-th panel are considered to be OFF.) If Ciel flips panels between $x$-th and $(x + a - 1)$-th, inclusive, the values of $b_{x}$ and $b_{x + a}$ are changed and other elements of b aren't changed. We can rewrite the problem: <Problem D'> You are given an 0-1 array $b_{0}, b_{1}, ..., b_{n}$. At most 20 (=$2k$) of them are $1$. In each move, you can change the values of $b_{x}$ and $b_{x + a}$, where a is an element of the given array and $0 \le x \le n - a$. Determine the minimal number of moves required to change all elements in $b$ to $0$. The order of moves is not important. If there is an index $x$ s.t. $b_{x} = 1$, you must change $b_{x}$ at least once, so you can assume that the next move is performed on $x$. Assume that when you change the values of $b_{x}$ and $b_{x + a}$, at least one of them is $1$. <Problem D''> Let $V$ be the graph with $(n + 1)$ vertices. Vertices are numbered $0$ to $n$. There is an edge between vertex $v_{1}$ and vertex $v_{2}$ if and only if $|v_{1} - v_{2}|$ is an element of array a. Initially at most 20 vertices contain tokens. In each move, you can move a token along an edge. When two tokens meet, they disappear. Determine the minimal number of moves required to erase all tokens. First, calculate the distances between all pair of tokens by doing bfs $2k$ times. Next, do DP with bitmasks: Let $dp[S]$ (where $S$ is a set of tokens) be the minimal number of moves required to erase all tokens. If $S$ is empty, $dp[S] = 0$. If $S = {s_{0}, s_{1}, ..., s_{m - 1}}$ is nonempty, $dp[S] = min{dp[S\{s_{0}, s_{i}}] + dist(s_{0}, s_{i})}$ where $1 \le i \le m - 1$. The complexity of this solution is $O(knl + k \cdot 2^{2k})$.
|
[
"bitmasks",
"dp",
"shortest paths"
] | 2,800
| null |
79
|
E
|
Security System
|
Fox Ciel safely returned to her castle, but there was something wrong with the security system of the castle: sensors attached in the castle were covering her.
Ciel is at point $(1, 1)$ of the castle now, and wants to move to point $(n, n)$, which is the position of her room. By one step, Ciel can move from point $(x, y)$ to either $(x + 1, y)$ (rightward) or $(x, y + 1)$ (upward).
In her castle, $c^{2}$ sensors are set at points $(a + i, b + j)$ (for every integer $i$ and $j$ such that: $0 ≤ i < c, 0 ≤ j < c$).
Each sensor has a count value and decreases its count value every time Ciel moves. Initially, the count value of each sensor is $t$. Every time Ciel moves to point $(x, y)$, the count value of a sensor at point $(u, v)$ decreases by ($|u - x| + |v - y|$). When the count value of some sensor becomes \textbf{strictly less than} $0$, the sensor will catch Ciel as a suspicious individual!
Determine whether Ciel can move from $(1, 1)$ to $(n, n)$ without being caught by a sensor, and if it is possible, output her steps. Assume that Ciel can move to every point even if there is a censor on the point.
|
Lemma. The sensors we should consider are only four sensors at the corner. proof: Let's think about sensors at a fixed row $v$. As the definition, when Ciel entered to $(x, y)$, a sensor at $(u, v)$ decreases its count by $|x - u| + |y - v|$. Let this value be $f_{x, y}(u)$. If we fix Ciel's path, the total decrease of each sensor is expressed as the summation of $f_{x, y}(u)$, where $x, y$ is one of the path. Because $f_{x, y}(u)$ is a convex function about variable $u$ and the fact that "the summation of convex functions is also a convex function", we can ignore sensors at center points: i.e. $a < u < a + c - 1$. The same thing holds true for vertical direction, so it is enough to consider only four sensors at corner: $(a, b), (a + c - 1, b), (a, b + c - 1), (a + c - 1, b + c - 1)$. - Because we need the lexicographically first solution, we want to use 'R' rather than 'U' in each step. Thus, it is enough if we can determine whether a feasible path exists with constraints that Ciel is at $(x, y)$ and the rest counts of four corners are $T_{1}, T_{2}, T_{3}, T_{4}$. Lemma. Optimal step is following (except sensors region): proof: A following figure shows that if a blue path is good a brown path is also good. (Here, the blue path means arbitrary one, and the brown path means optimal one.) - The problem is sensors region. In sensors region, it is possible to assume that the optimal path always passes a right-top sensor. While Ciel moves in sensors region to right-top sensor, the total decrease of both left-bottom and right-top sensor is constant. So we should think about only two sensors: left-top and right-bottom. In addition, let the total decrease of left-top and right-bottom be $D_{1}$ and $D_{2}$. Then following holds: $D_{1} + D_{2} = const$. The smallest value for $D_{1}$ is the total decrease when Ciel moves upward then moves rightward, and the smallest value for $D_{2}$ is in the same way (moves rightward $ \rightarrow $ upward). So we can calculate the minimal value and the maximal value of $D_{1}$. And actually, $D_{1}$ can be an arbitrary value between them with interval of 2. A following picture shows it. Complexity at a simulation part is O(1). Overall, the complexity is $O(N)$.
|
[
"math"
] | 2,900
| null |
80
|
A
|
Panoramix's Prediction
|
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers $2$, $7$, $3$ are prime, and $1$, $6$, $4$ are not.
{The next prime number after $x$ is the \textbf{smallest} prime number greater than $x$. For example, the next prime number after $2$ is $3$, and the next prime number after $3$ is $5$. Note that there is exactly one next prime number after each number. So $5$ \textbf{is not} the next prime number for $2$.}
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly $x$ Roman soldiers, where $x$ is a prime number, and next day they beat exactly $y$ Roman soldiers, where $y$ is \textbf{the next prime number} after $x$, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat $n$ Roman soldiers and it turned out that the number $n$ was prime! Today their victims were a troop of $m$ Romans ($m > n$). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
|
In the very beginning of statement you may find some words about what is prime number and what is next prime number. Main point of problem is to check is $m$ next prime after $n$ or not. Problem statement guarantees that $n$ is prime number. We need to check only two cases: 1. Number $m$ is prime, and 2. There is no any prime number between $n$ and $m$ Really, if there is prime number $k$ between $n$ and $m$ then $m$ cannot be next prime after $n$. Restrictions in this problem are really small and there is a way to solve it: for(int i=n+1;i<=m;i++) { if (prime(i)) { if (i==m) return "YES"; else return "NO"; } } return "NO"; where prime(i) is any correct way to check is number $i$ is prime. Another simple solution of this problem is to conside the fact that restrictions are no more than 50. It is possible to find all pairs $n$ and $m$ by hands and write solution formed by series of cases like this: if (n==2 && m==3) return "YES"; else if (n==3 && m==5) return "YES"; else ... else if (n==43 && m==47) return "YES"; else return "NO"; This solution gets "accepted" too. Complexity may be various because of diffenent realizations and is in range from $O(1)$ to $O(n + m)$. If you are interested in why your solution gets "wrong answer" the test "2 5" maybe helps you.
|
[
"brute force"
] | 800
| null |
80
|
B
|
Depression
|
Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels!
There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle...
Everybody was upset. The beautiful Belle was upset, so was the Beast, so was Lumiere the candlestick. But the worst thing was that Cogsworth was upset. Cogsworth is not a human, but is the mantel clock, which was often used as an alarm clock.
Due to Cogsworth's frustration all the inhabitants of the castle were in trouble: now they could not determine when it was time to drink morning tea, and when it was time for an evening stroll.
Fortunately, deep in the basement are lying digital clock showing the time in the format HH:MM. Now the residents of the castle face a difficult task. They should turn Cogsworth's hour and minute mustache hands in such a way, that Cogsworth began to show the correct time. Moreover they need to find turn angles in degrees for each mustache hands. The initial time showed by Cogsworth is 12:00.
You can only rotate the hands forward, that is, as is shown in the picture:
As since there are many ways too select such angles because of full rotations, choose the smallest angles in the right (non-negative) direction.
Note that Cogsworth's hour and minute mustache hands move evenly and continuously. Hands are moving independently, so when turning one hand the other hand remains standing still.
|
The first I pay your attention is while we are moving first arrow the second one is stay motionless. In fact this means that we can solve next two problems independently: 1. Find the angle to turn the minute hand, and 2. Find the angle to turn the hours hand Next, you may find in statement phrase: "Cogsworth's hour and minute mustache hands move evenly and continuously". It means that after every little increasing of time $ \Delta t$ both hands will move for some little angles. Number of minutes is always integer because of format HH:MM so every new minute will add $360 / 60 = 6$ angles to minute hand. For angle of hours hand influence number of hours and number of minutes. Every new hour will add $360 / 12 = 30$ angles to rotate and every new minute will add $(360 / 12) / 60 = 0.5$ angles. Thus, we should cut number of hours and number of minutes from HH:MM entry and use formulaes described above for finding the answer. Look at the time before midday and after noon carefully, analog watch has no difference between them and answers for 08:15 and 20:15 should be equal. Complexity is $O(1)$. If you are interested in why your solution gets "wrong answer" the tests "20:15" and "00:00" maybe helps you.
|
[
"geometry",
"math"
] | 1,200
| null |
82
|
A
|
Double Cola
|
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. This process continues ad infinitum.
For example, Penny drinks the third can of cola and the queue will look like this: Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny.
Write a program that will print the name of a man who will drink the $n$-th can.
Note that in the very beginning the queue looks like that: Sheldon, Leonard, Penny, Rajesh, Howard. The first person is Sheldon.
|
Let's designate characters on the first letter of the name. The queue looks like: SH-L-P-R-G, through 5 cans: SH-SH-L-L-P-P-R-R-G-G, through 10 cans: SH-SH-SH-SH-L-L-L-L-P-P-P-P-R-R-R-R-G-G-G-G. The regularity is clear, and the solution is very simple: we will be iterated on $p$ - we will find such minimum $p$ that $5 \cdot 2^{p} > n$ (thus if this number is less or equally we will subtract it from $n$) then we know that at first $2^{p}$ Sheldon's stand, then $2^{p}$ Leonard's and so on. And now we can easily answer who took a can number $n$ (namely there was a person with number $n / 2^{p}$ in sequence SH-L-P-R-G (in 0-indexation).
|
[
"implementation",
"math"
] | 1,100
| null |
82
|
B
|
Sets
|
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose $n$ non-empty sets in such a way, that no two of them have common elements.
One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on $n·(n - 1) / 2$ pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.
For example, if $n = 4$, and the actual sets have the following form ${1, 3}$, ${5}$, ${2, 4}$, ${7}$, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers:
- $2, 7, 4$.
- $1, 7, 3$;
- $5, 4, 2$;
- $1, 3, 5$;
- $3, 1, 2, 4$;
- $5, 7$.
Then Vasya showed the pieces of paper to his friends, but kept the $n$ sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?
|
For the solution the following important fact is required to us: we will admit elements $v$ and $u$ are in one set then in any of $n \cdot (n - 1) / 2$ of sequences from the input data where meets $v$ $u$ necessarily meets. And also if $v$ and $u$ are in different sets there is such sequence in which is $v$, but isn't present $u$. Then it is possible to enter the equivalence relation for all elements of all sets - two elements are equivalent, if there is no sequence where one element meets, and another isn't present. Classes of equivalence also are required sets. It was possible to consider the answer as following algorithm: we will write out for each number the list of numbers of sequences where there is this number, and will unite two numbers if these lists are equal. This algorithm can be realized for $O(n^{2} * log(n))$ however the solution for $O(n^{3})$ passes all tests with time large supply too. The special case is a test with $n = 2$. This test was used for a considerable quantity of hacks.
|
[
"constructive algorithms",
"hashing",
"implementation"
] | 1,700
| null |
82
|
C
|
General Mobilization
|
The Berland Kingdom is a set of $n$ cities connected with each other with $n - 1$ railways. Each road connects exactly two different cities. The capital is located in city $1$. For each city there is a way to get from there to the capital by rail.
In the $i$-th city there is a soldier division number $i$, each division is characterized by a number of $a_{i}$. It represents the priority, the smaller the number, the higher the priority of this division. All values of $a_{i}$ are different.
One day the Berland King Berl Great declared a general mobilization, and for that, each division should arrive in the capital. Every day from every city except the capital a train departs. So there are exactly $n - 1$ departing trains each day. Each train moves toward the capital and finishes movement on the opposite endpoint of the railway on the next day. It has some finite capacity of $c_{j}$, expressed in the maximum number of divisions, which this train can transport in one go. Each train moves in the direction of reducing the distance to the capital. So each train passes exactly one railway moving from a city to the neighboring (where it stops) toward the capital.
In the first place among the divisions that are in the city, division with the smallest number of $a_{i}$ get on the train, then with the next smallest and so on, until either the train is full or all the divisions are be loaded. So it is possible for a division to stay in a city for a several days.
The duration of train's progress from one city to another is always equal to $1$ day. All divisions start moving at the same time and end up in the capital, from where they don't go anywhere else any more. Each division moves along a simple path from its city to the capital, regardless of how much time this journey will take.
Your goal is to find for each division, in how many days it will arrive to the capital of Berland. The countdown begins from day $0$.
|
At first we will estimate from above the maximum time to which all divisions will reach capital - obviously it is required no more $n$ days for this purpose. Therefore restrictions quite allowed model movements of divisions. The key moment of the solution - we will always consider divisions in priority order. Then in every day we will consider the list of those divisions who hasn't reached yet capital, and we will put in priority order on the necessary train. If the train is already filled, the division remains in a current city, differently we will change its position, and in day when the division will reach capital we will write down the answer. Total: in total days which it is necessary model, no more $n$, and every day we move no more $n$ divisions. So our solution has asymptotic form no more $O(n^{2})$. The solutions using various structures of the data (sets, turns with priorities etc.) work for $O(n^{2} \cdot log(n))$ and it didn't always keep within in TL.
|
[
"data structures",
"dfs and similar",
"sortings"
] | 2,000
| null |
82
|
D
|
Two out of Three
|
Vasya has recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem.
Let the queue to the cashier contain $n$ people, at that each of them is characterized by a positive integer $a_{i}$ — that is the time needed to work with this customer. What is special about this very cashier is that it can serve two customers simultaneously. However, if two customers need $a_{i}$ and $a_{j}$ of time to be served, the time needed to work with both of them customers is equal to $max(a_{i}, a_{j})$. Please note that working with customers is an uninterruptable process, and therefore, if two people simultaneously come to the cashier, it means that they begin to be served simultaneously, and will both finish simultaneously (it is possible that one of them will have to wait).
Vasya used in his algorithm an ingenious heuristic — as long as the queue has more than one person waiting, then some two people of the first three standing in front of the queue are sent simultaneously. If the queue has only one customer number $i$, then he goes to the cashier, and is served within $a_{i}$ of time. Note that the total number of phases of serving a customer will always be equal to $⌈n / 2⌉$.
Vasya thinks that this method will help to cope with the queues we all hate. That's why he asked you to work out a program that will determine the minimum time during which the whole queue will be served using this algorithm.
|
The problem dares the dynamic programming. We will consider a state $(i, j)$ meaning that in the current turn there is a person number $i$ and also all people from $j$ to $n$ inclusive. Any turn achievable of the initial can be presented by corresponding condition. The quantity of conditions is $O(n^{2})$, the quantity of transitions is only 3, that is $O(1)$. So the total asymptotic form is $O(n^{2})$.
|
[
"dp"
] | 2,000
| null |
82
|
E
|
Corridor
|
Consider a house plan.
Let the house be represented by an infinite horizontal strip defined by the inequality $ - h ≤ y ≤ h$. Strictly outside the house there are two light sources at the points $(0, f)$ and $(0, - f)$. Windows are located in the walls, the windows are represented by segments on the lines $y = h$ and $y = - h$. Also, the windows are arranged symmetrically about the line $y = 0$.
Your task is to find the area of the floor at the home, which will be lighted by the sources of light.
|
This problem has some solutions based on the various methods of the search of the area of the association of the figures on a plane. One of such methods is the method of vertical decomposition (more in detail you can esteem in various articles) and also it was possible to notice that among figures there are no three having non-zero crossing and consequently was to learn to find a total area of two figures enough. For this purpose also it was possible to use the various methods, for example, the author's solution is based on algorithm of cutting off of a convex polygon by a semiplane. Authors supposed the solution for $O(n^{2})$.
|
[
"geometry"
] | 2,600
| null |
83
|
A
|
Magical Array
|
\underline{Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.}
Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its \textbf{minimum and maximum coincide}.
He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as \textbf{non-empty sequence of consecutive elements}.
|
We must find out all the intervals that consist of the same integers. For an interval with $P$ integers, the number of reasonable subsequences is $\frac{P(P+1)}{2}$. Thus, we can adopt two pointers to find out all the target intervals, and calculate the answer.
|
[
"math"
] | 1,300
| null |
83
|
B
|
Doctor
|
There are $n$ animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number $i$ in the queue will have to visit his office exactly $a_{i}$ times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home.
Doctor plans to go home after receiving $k$ animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out.
|
The basic idea is still binary search. We use $a[n]$ to denote the given array. We use binary search to find out the maximum $T$ so that $S=\sum_{0}^{n-1}m i n(a[i],T)\leq K$. Moreover, we compute $K - S$ as the remainder. Then, any $a[i]$ that is not larger than $T$ should be firstly eliminated. Next we enumerate the first $K - S$ survived $a[j]$ in the natural order while decreasing them by one, and eliminate those $a[i] \le T$ again. Finally, we start from the current position and output the survived indices one by one, by shifting to the right in a circular manner.
|
[
"binary search",
"math",
"sortings"
] | 1,800
| null |
83
|
C
|
Track
|
You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest.
The track's map is represented by a rectangle $n × m$ in size divided into squares. Each square is marked with a lowercase Latin letter (which means the type of the plot), with the exception of the starting square (it is marked with a capital Latin letters $S$) and the terminating square (it is marked with a capital Latin letter $T$). The time of movement from one square to another is equal to $1$ minute. The time of movement within the cell can be neglected. We can move from the cell only to side-adjacent ones, but it is forbidden to go beyond the map edges. Also the following restriction is imposed on the path: it is not allowed to visit more than $k$ \textbf{different types} of squares (squares of one type can be visited an infinite number of times). Squares marked with $S$ and $T$ have no type, so they are not counted. But $S$ must be visited exactly once — at the very beginning, and $T$ must be visited exactly once — at the very end.
Your task is to find the path from the square $S$ to the square $T$ that takes minimum time. Among all shortest paths you should choose the \textbf{lexicographically minimal} one. When comparing paths you should lexicographically represent them as a sequence of characters, that is, of plot types.
|
I spent about three hours modifying the algorithm to avoid the time limit....The most impressive modification I used is scaling the constant from $1$ to $\frac{1}{6}$. This is the first time that I realized what an important role that a constant can play. The general idea is to generate all the feasible patterns of maps and find out the one with the minimum distance and order. For instance, if letter 'a' and 'b' can be used, then we will obtain a map where we can move to positions of 'a' and 'b' while the other ones can not be used. With this equivalent map, we can implement BFS from the starting position until the terminating position is reached. During this process, we update the distance and also the minimum order if necessary. As $k$ can take values up to $4$, we may have to check as many as $C_{26}^{4}$ patterns for the worst case. It turns out that this will lead to TLE. Therefore, we have to further reduce the complexity. Instead of beginning from the starting position, we can begin from every one of the four positions that can be reached from the starting position. Each time we select one position, we have determined one letter that must be used and thus the number of feasible patterns is reduced to $C_{25}^{3}$, which is supposed to satisfy the time limit as I consider. However, I made a mistake that the number of generated patterns is in fact $A_{25}^{3}$ rather than $C_{25}^{3}$. As these two values only differ by a constant of $\frac{1}{6}$, I did not realize (or believe) that such a constant matters so much. After I correct the mistake, it passed... What a fascinating problem!!
|
[
"graphs",
"greedy",
"shortest paths"
] | 2,400
| null |
84
|
A
|
Toy Army
|
The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows.
There are two armies on the playing field each of which consists of $n$ men ($n$ is always even). The current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. This is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die. It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore.
The game "GAGA" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends.
You are asked to calculate the maximum total number of soldiers that may be killed during the game.
|
The strict proof seems to be a little complicated as far as I consider, however an intuitive understanding suggests that the answer is $n + n / 2$, and it is accpeted...
|
[
"math",
"number theory"
] | 900
| null |
84
|
C
|
Biathlon
|
Perhaps many have heard that the World Biathlon Championship has finished. Although our hero Valera was not present at this spectacular event himself and only watched it on TV, it excited him so much that he decided to enroll in a biathlon section.
Of course, biathlon as any sport, proved very difficult in practice. It takes much time and effort. Workouts, workouts, and workouts, — that's what awaited Valera on his way to great achievements in biathlon.
As for the workouts, you all probably know that every professional biathlete should ski fast and shoot precisely at the shooting range. Only in this case you can hope to be successful, because running and shooting are the two main components of biathlon. Valera has been diligent in his ski trainings, which is why he runs really fast, however, his shooting accuracy is nothing to write home about.
On a biathlon base where Valera is preparing for the competition, there is a huge rifle range with $n$ targets. Each target have shape of a circle, and \textbf{the center of each circle is located on the $Ox$ axis}. At the last training session Valera made the total of $m$ shots. To make monitoring of his own results easier for him, one rather well-known programmer (of course it is you) was commissioned to write a program that would reveal how many and which targets Valera hit. More specifically, for each target the program must print the number of \textbf{the first} successful shot (in the target), or "-1" if this was not hit. \textbf{The target is considered hit if the shot is inside the circle or on its boundary.} Valera is counting on you and perhaps, thanks to you he will one day win international competitions.
|
As it has been guaranteed that no two circles intersect with each other, the given point can only fall into at most one particular circle (one special case is that two circles touch each other at the given point). Thus, we first sort the circles in an increasing order of their X-coordinates, and find out two circles between which the give point falls (check the X-coordinate of the given point as well, and a special case is that the given point falls at one of two ends of all the circles), which can be achieved by using binary search. Then, the final step is to check which circle it falls inside, or completely outside all the circles.
|
[
"binary search",
"implementation"
] | 1,700
| null |
85
|
C
|
Petya and Tree
|
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.
Thus, you are given a \underline{binary search tree}, that is a tree containing some number written in the node. This number is called the \underline{node key}. The number of children of every node of the tree is equal either to $0$ or to $2$. The nodes that have $0$ children are called \underline{leaves} and the nodes that have $2$ children, are called \underline{inner}. An inner node has the \underline{left child}, that is the child whose key is less than the current node's key, and the \underline{right child}, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.
Also you are given a set of \underline{search keys}, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the \underline{search result}.
It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.
|
So, let remember statement of the problem. We have the correct binary search tree and the set of request keys. For each request key we consider paths in the tree with one error. These paths are constructed by the search of request key in the tree with one wrong choice of the next vertice. Each wrong choice generate one search path in the tree. At the beginning solve the problem for one request key. Consider the vertex of the path, after which the error occurred. Suppose that correct search at this vertex goes to the left child but we go to the right. This means that request key lies in key range of the left subtree and we go to the right subtree. Therefore further search of request key goes to the vertex of the right subtree with minimum key. Similar, if correct search goes to the right child but we go to the left, then further search goes to the vertex with maximum key in left subtree. Count maximum and minimum keys for each subtree of the all tree. This is done by the depth-first search. If we know minimum and maximum keys for all subtrees, there is easy to count answer for given request key. Execute search of the request key and accumulate values of minimum or maximum keys of subtrees where we go with one error. Now solve the problem for all request keys. Note that the answer for request key depends of only final vertex of the correct search in the tree. Therefore count answer for all leafs of the tree by one depth-first search. For all request keys we need to find final vertex of the search very fast. Put all keys of all vertices of the tree in ordered array. Note that keys of inner vertices and keys of leafs are alternated in this array. So, for each request key find nearest left and right keys in this array using binary search. One of this keys belongs to the leaf. Answer for this leaf would be answer for given request key. Thus, solution of the problem requires two depth-first searches and $k$ binary searches in array. So, running time is $O(n+k\log n)$, where $n$ is a number of vertices in the tree and $k$ is a number of request keys.
|
[
"binary search",
"dfs and similar",
"probabilities",
"sortings",
"trees"
] | 2,200
| null |
86
|
A
|
Reflection
|
For each positive integer $n$ consider the integer $ψ(n)$ which is obtained from $n$ by replacing every digit $a$ in the decimal notation of $n$ with the digit $(9 - a)$. We say that $ψ(n)$ is the reflection of $n$. For example, reflection of $192$ equals $807$. Note that leading zeros (if any) should be omitted. So reflection of $9$ equals $0$, reflection of $91$ equals $8$.
Let us call the weight of the number the product of the number and its reflection. Thus, the weight of the number $10$ is equal to $10·89 = 890$.
Your task is to find the maximum weight of the numbers in the given range $[l, r]$ (boundaries are included).
|
First note that if the interval contains a number with $a$ digits and a number with $b$ digits (where $a$ > $b$) then there is no need to consider the number with $b$ digits (as the weight of $10^{k}$ is greater then the weights of the numbers less than $10^{k}$). If we consider only numbers with fixed number of digits $(s + 1)$, then the sum of $a$ and its reflection is constant. Thus, as product grows as multipliers with fixed sum get closer, the picture is the following: the weight grows from $10^{s}$ to $5 \cdot 10^{s} - 1$, then it stays the same for $5 \cdot 10^{s}$ and then it goes down, and reaches its minimum (zero) value at $10^{s + 1} - 1$. This is the proof, and the solution is: the maximum weight is reached at either $l$, $r$ or $5 \cdot 10^{s}$ (we may check all the $s$ such that $5 \cdot 10^{s}$ belongs to the interval, for example).
|
[
"math"
] | 1,600
| null |
86
|
B
|
Tetris revisited
|
Physicist Woll likes to play one relaxing game in between his search of the theory of everything.
Game interface consists of a rectangular $n × m$ playing field and a dashboard. Initially some cells of the playing field are filled while others are empty. Dashboard contains images of all various connected (we mean connectivity by side) figures of 2, 3, 4 and 5 cells, with all their rotations and reflections. Player can copy any figure from the dashboard and place it anywhere at the still empty cells of the playing field. Of course any figure can be used as many times as needed.
Woll's aim is to fill the whole field in such a way that there are no empty cells left, and also... just have some fun.
Every initially empty cell should be filled with exactly one cell of some figure. Every figure should be entirely inside the board.
In the picture black cells stand for initially filled cells of the field, and one-colour regions represent the figures.
|
It's easy to see that the field may be filled with such figures if and only if there is no isolated cell. There are many different ways to do that, we will show some of them. 1. Domino filling. We construct greedy matching on the cells of our field combining them in domino-like figures (rectangles 1 $ \times $ 2). Passing through the array that represents our field (from left to right, from top to bottom) we combine the still free horizontal pairs of connected cells into the horizontal dominoes. Then we do the same thing with the still free vertical pairs. Naturally, some cells may be still free. But such cells should be adjoined with some of the dominoes (if they were not isolated). We may attach each of these cells to any of the adjoint dominoes. All resulting figures will contain no more than 5 cells, because the cells still empty after matching can not be neighbour cells and can not be adjacent to the left side of dominoes (by the virtue of the order of our matching). The last thing that has to be done is the coloring of the figures in accordance with the output format. For example, we may color them like that: color all the cells in the plane in 9 colors (i, j) -> (i % 3) * 3 + j % 3. Then paint each domino in the color of its black cell (according to chess coloring). Each figure will have the color of the domino it grows from. 2. Greedy. We pass through the array representing the field, again in the same order. Figure for any still free cell may be constructed greedily, but we have to be accurate in order to avoid appearance of new isolated cells. So we just add all the cells that do become isolated when we fill the current figure. Acting in such a fashion we will eventually get the covering by the figures of no more than 5 cells (and at least two, of course). It is possible to color the figure immediately after its formation. We only need to check the colors of all already colored adjacent figures and to take any color, different from all of them. It is not hard to see that 10 colors are enough.
|
[
"constructive algorithms",
"graph matchings",
"greedy",
"math"
] | 2,200
| null |
86
|
C
|
Genetic engineering
|
"Multidimensional spaces are completely out of style these days, unlike genetics problems" — thought physicist Woll and changed his subject of study to bioinformatics. Analysing results of sequencing he faced the following problem concerning DNA sequences. We will further think of a DNA sequence as an arbitrary string of uppercase letters "A", "C", "G" and "T" (of course, this is a simplified interpretation).
Let $w$ be a long DNA sequence and $s_{1}, s_{2}, ..., s_{m}$ — collection of short DNA sequences. Let us say that the collection filters $w$ iff $w$ can be covered with the sequences from the collection. Certainly, substrings corresponding to the different positions of the string may intersect or even cover each other. More formally: denote by $|w|$ the length of $w$, let symbols of $w$ be numbered from $1$ to $|w|$. Then for each position $i$ in $w$ there exist pair of indices $l, r$ ($1 ≤ l ≤ i ≤ r ≤ |w|$) such that the substring $w[l ... r]$ equals one of the elements $s_{1}, s_{2}, ..., s_{m}$ of the collection.
Woll wants to calculate the number of DNA sequences of a given length filtered by a given collection, but he doesn't know how to deal with it. Help him! Your task is to find the number of different DNA sequences of length $n$ filtered by the collection ${s_{i}}$.
Answer may appear very large, so output it modulo $1000000009$.
|
Suppose we've built a string $wp$ of length $k < n$ and want to know how many ways there exist to complement $wp$ to the suitable string of length $n$. What parameters do we need to know in order to build it further? First of all, we need to know the index $wp$ is covered up to (we denote it by $ci$ and call it covering index). Also we want to have some information about what the string ends with. Here comes rather standard idea: let's find all the prefixes $ALL_{P}$ of the {$s_{i}$} and add to our state the largest prefix $p_{k}\in A L L_{P}$ such that $wp$ ends with $p_{k}$ (as an alternative, you may consider a vertex in a trie constructed with the collection's strings). Now I'll try to convince you that it's enough to set the things going. First of all, when we add a symbol $c$ to $wp$ we can easily get $p_{k + 1}$ and it will be equal to the largest string in $ALL_{P}$ such that the string $p_{k} + c$ ends with (we can precalculate all the transitions in advance). So the only thing we want to know how to calculate (in order to use dynamic programming approach) is the new covering index. But we notice that it can be changed only by some string from the collection that $w_{p} + c$ ends with. Now we observe that it is sufficient to check only the largest from all such strings (denote it $fs$), and that it necessarily contains in $p_{k + 1}$ (so it also can we easily precalculated for all strings in $ALL_{P}$). We observe further that the new covering index depends only on the length of $fs$: it either equals the old one if $fs$ doesn't cover the symbol $ci + 1$, or equals to ($k + 1$) if the $fs$ covers that symbol. After calculating all the quantities d[k][k - cov.index][max. prefix] the required number of strings equals the sum of d[n][0][mp] for all $mp$.
|
[
"dp",
"string suffix structures",
"trees"
] | 2,500
| null |
86
|
D
|
Powerful array
|
An array of positive integers $a_{1}, a_{2}, ..., a_{n}$ is given. Let us consider its arbitrary subarray $a_{l}, a_{l + 1}..., a_{r}$, where $1 ≤ l ≤ r ≤ n$. For every positive integer $s$ denote by $K_{s}$ the number of occurrences of $s$ into the subarray. We call the power of the subarray the sum of products $K_{s}·K_{s}·s$ for every positive integer $s$. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite.
You should calculate the power of $t$ given subarrays.
|
Let's solve the problem offline in O(n sqrt(t)) time and O(n) memory. For the simplicity of the reasoning let t = n. Assume we know the answer to the problem for some interval and want to find it to another one. Let us move the left end of the first one towards the left end of the second, similarly dealing with the right ends. By moving the end by one and for every value in the array maintaining the number of its appearances in the current interval, we will be able to calculate the answer and maintain the numbers of appearances at the same time in O(1). From now on we call the procedure of movement by 1 a step. Going through the queries in such a fashion, evidently, will cost us O(n^2) steps. Let p = sqrt(n). Divide the array into p equal parts Q_1, ..., Q_p. Now consider the queries of the form (Q_i, Q_j) for all i and j (there will be approx. n such queries). Clearly, there doesn't exist an order in which we can go through the queries in o(n sqrt(n)) time as the transition from any interval to the other one is done in no less than sqrt(n) steps. Nevertheless, there exists a traversal order that guarantees O(n sqrt(n)) steps in the worst case. Let's sort the query intervals according to the following rule: first come the intervals with the left ends in Q_1, then the intervals with the left ends in Q_2, and so on. And if the left ends of the two queries belong to the same part, then the interval with the more left right end is assumed to be smaller. In order to prove the stated asymptotic behavior we will follow the steps of the left and the right ends independently. We note that the left ends that belong to the same Q_i make <= n / p steps, and transition to Q_{i+1} costs no more than 2 * n / p steps. Therefore the left ends make <= n/p * n + 2*n steps (the second summand is O(n), and it's negligible). The right ends in the common group move only to the right, and this proves <= n * p steps (during the whole process) estimate. We will estimate the transition to the next Q_i at no more than n steps, so overall we get <= 2 * n * p steps. Thus, the total number of steps is no more than (n / p * n + 2 * n * p). Now we choose p = sqrt(n) which proves the statement. Solution: let us sort the queries by this rule, then make transitions from a query to the next one according to the obtained order. Note 1. There is nothing special (except for nonadditivity) with the function in the statement. Note 2. In the case of distinct n and t we can similarly prove the nice estimate 2 * n * sqrt(t), mostly nice because of its exactness (if you follow the proof carefully, you will easily construct the maximal test).
|
[
"data structures",
"implementation",
"math",
"two pointers"
] | 2,200
| null |
86
|
E
|
Long sequence
|
A sequence $a_{0}, a_{1}, ...$ is called a recurrent binary sequence, if each term $a_{i}$ $(i = 0, 1, ...)$ is equal to 0 or 1 and there exist coefficients $c_{1},c_{2},\dots,c_{k}\in\{0,1\}$ such that
\[
a_{n} = c_{1}·a_{n - 1} + c_{2}·a_{n - 2} + ... + c_{k}·a_{n - k} (mod 2),
\]
for all $n ≥ k$. Assume that not all of $c_{i}$ are zeros.Note that such a sequence can be uniquely recovered from any $k$-tuple ${a_{s}, a_{s + 1}, ..., a_{s + k - 1}}$ and so it is periodic. Moreover, if a $k$-tuple contains only zeros, then the sequence contains only zeros, so this case is not very interesting. Otherwise the minimal period of the sequence is not greater than $2^{k} - 1$, as $k$-tuple determines next element, and there are $2^{k} - 1$ non-zero $k$-tuples. Let us call a sequence long if its minimal period is exactly $2^{k} - 1$. Your task is to find a long sequence for a given $k$, if there is any.
|
Firstly let's note that there are only 49 different possible inputs. So any solution that works finite time at all tests (even if does not pass timelimit) is enough, because we can memorize all the answers. It is not necessary, of course, but may help with slow solutions. Then, let's answer a more particular question. Assume that $c_{1}, c_{2}, ..., c_{k}$ and $a_{0}, a_{1}, ..., a_{k - 1}$ are already given and we need to check whether the sequence ${a_{i}}$ generated by them is long or not. We know that if it is periodic, then it is possible to find any non-zero k-tuple among k-tuples $a_{s}, a_{s + 1}, ..., a_{s + k - 1}$. So initial k-tuple has no real matter if only it is not zero. Thus the property of sequence "to be long" depends only on coefficients $c_{i}$, and we may choose any convenient $a_{0}, a_{1}, ..., a_{k - 1}$. We will now think that $a_{0}, a_{1}, ..., a_{k - 2}$ are zeros and $a_{k - 1} = 1$. Consider the transition matrix $A$ of our sequence: for $i < k$ the $i$-th row of $A$ is equal to $(0, 0, ... 0, 1, 0, ..., 0)$ with 1 at $(i + 1)$-th position and last row of $A$ is equal to $(c_{k}, c_{k - 1}, ..., c_{2}, c_{1})$. Denote by $x_{s}$ vector $(a_{s}, a_{s + 1}, ..., a_{s + k - 1})^{T}$. Then for any integer $s$ we have: $A \cdot x_{s} = x_{s + 1}$. Last is just a reformulation of the recurrent formula: $a_{n} = c_{1} * a_{n - 1} + c_{2} * a_{n - 2} + ... + c_{k} * a_{n - k}.$ Then by obvious induction we have: $A^{p} \cdot x_{s} = x_{s + p}$ for any $p \ge 0$. Hence $p$ is a period iff for any vector $x$ that appears in our sequence: $A^{p} \cdot x = x$. If the sequence is not long then it is not self-evident still that $A^{p}$ is an identity matrix, because $x$ does not take all possible values. But we have chosen $x_{0} = (0, 0, ..., 0, 1)$ before, so it is obvious that vectors $x_{0}, x_{1}, x_{2}, ..., x_{k - 1}$ form a basis. Hence if $A^{p} \cdot x_{i} = x_{i}$ for any $i$ then $A^{p}$ is the identity matrix. So we just need to do the following: 1) Construct the matrix $A$ from the coefficients $c_{i}$. 2) Check that $A^{2k - 1}$ is the identity matrix. (If not, then $2^{k} - 1$ is not a period.) If $2^{k} - 1$ is a period, then we have to check that it is minimal. Minimal period divides any period so we only need to check the divisors of $2^{k} - 1$. 3) Generate all maximal divisors of $2^{k} - 1$ and check that they are not periods (using $A$ again). (By maximal divisor of n we mean divisors of the type n/q where q is a prime number.) Last thing we need to notice that such a sequence always exists. Moreover, amount of appropriate sets of $c_{i}$ is pretty large. One may prove that there are $\textstyle{\frac{\varphi(2^{k}-1)}{k}}$ such sets (because they correspond to the coefficients of the irreducible factors of the cyclotomic polynomial over $\mathbb{F}_{2}$). So we can just take them at random and check.
|
[
"brute force",
"math",
"matrices"
] | 2,700
| null |
87
|
A
|
Trains
|
Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.
When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every $a$ minutes, but a train goes to Masha's direction every $b$ minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample).
We know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously.
Help Vasya count to which girlfriend he will go more often.
|
This problem can be approached from two sides - from a programmer's perspective and a mathematician's one. We consider both approaches. First, let's write some general propositions. Let's put on a straight line all the moments of time when the trains arrive. We will refer the interval between two successive points to the girl, to who the train that matches the right end of the segment is going. Also note that the entire picture is periodic with the period equal to lcm(a, b). Vasya will obviously more often visit the girl, whose total length of the segments is larger. The programming approach is about modeling the process. If we need to compare the lengths of two sets of intervals, then let's count them. We can do it using two pointers. Let's see what train comes next, add time before the arrival of the train to one of the answers, move the pointer and the current time. We should stop either when two last trains arrive simultaneously or when arrive a+b trains. The solution has asymptotic $O(a + b)$, that fits the time limit. Don't forget that lcm(a,b) ~ 10^12, i.e., we need the 64-bit data type. The mathematical approach provides us with a more elegant and shorter solution, however, it takes more thinking. It seems obvious that Vasya will more often go to the girl, to who trains go more often. This fact is almost true. Let's try to prove it. Let's divide a and b by their gcd - from this, obviously, nothing will change. To make it clearer, let $a \le b$. Let's calculate the total length of segments corresponding to the second girl. For this, we need to take a few facts into consideration. 1) All of them do not exceed a 2) All a segments are different (due to coprimeness of a and b). 3) They all are at least 1. But such a set of intervals is unique - it's set of numbers {1, 2, \dots , a} and its length equals $\textstyle\sum_{i=1}^{a}i={\frac{a\cdot(a+1)}{2}}\leq{\frac{a\,b}{2}}$. Besides, the equality is fulfilled when the following condition is met: $b - a = 1$. Hence the following is true. The answer is Equal, when $|a - b| = 1$, otherwise Vasya goes more often to the girl to which the trains go more often. The key is not to forget to divide a and b by their gcd.
|
[
"implementation",
"math"
] | 1,500
| null |
87
|
B
|
Vasya and Types
|
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type $X$ — that will result in new type $X * $. That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of $X$, which is a pointer, you can add an ampersand — that will result in a type $&X$, to which refers $X$. That is called a dereference operation.
The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof.
- The operator "typedef $A$ $B$" defines a new data type $B$, which is equivalent to $A$. $A$ can have asterisks and ampersands, and $B$ cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
- The operator "typeof $A$" returns type of $A$, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype*$ = $&errtype$ = $errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words $&T * $ is always equal to $T$.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but \textbf{not} &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
|
In this task, it was necessary to do exactly what is written in the problem's statement, for practically any complexity. You are suggested to do the following. For each data type we shall store two values - its name and the number of asterisks when it is brought to void. Then the typeof request is processed by consecutively looking at each element of an array of definitions, in which we find the desired name of the type and the number of asterisks in it. The type errtype is convenient to store as void, to which we added $- inf$ asterisks. Thus, fulfilling a typedef request, we find the number of asterisks in the type A, add to it a number of asterisks and subtract the number of ampersands. Do not forget to replace any negative number of asterisks by $- inf$, and create a new definition of type B, removing the old one.
|
[
"implementation",
"strings"
] | 1,800
| null |
87
|
C
|
Interesting Game
|
Two best friends Serozha and Gena play a game.
Initially there is one pile consisting of $n$ stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of $a_{1} > a_{2} > ... > a_{k} > 0$ stones. The piles should meet the condition $a_{1} - a_{2} = a_{2} - a_{3} = ... = a_{k - 1} - a_{k} = 1$. Naturally, the number of piles $k$ should be no less than two.
The friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way?
|
In this task you should analyze the game. However, due to the fact that with every move the game is divided into several independent ones, the analysis can be performed using the Grundy's function (you can read about it here, or here). Now all we have to do is to construct edges for each position. We can build the edges separately for each vertex by solving $k=O({\sqrt{n}})$ simple linear equations for each number of piles after splitting. We can construct all the divisions in advance, simply taking one by one the smallest pile and the number or piles and terminating when the sum exceeds $n$. The second way is better because it works for the $O(m + n)$, where m stands for the number of edges, and the first one works for $O(n{\sqrt{n}})$, which is larger. We should evaluate m in the maximal test. The edges are no more than $k n=O(n{\sqrt{(n)}})$. However, in practice they are much less - about 520 thousand. Which is why there's enough time to build the edges within the time limit of $O(nk)$. You can try to find a Grundy's function by the definition if we xor all the required values for each position. But this may not work: it has too many long partitions (solutions with lazy countings or other ideas was working, though). Let's learn how to quickly count a Grundy's xor function for a long partition. Let's use a standard method for counting functions on the interval - $xor[l, r] = xor[0, r]\^xor[0, l - 1]$. In the course of the algorithm we will keep a xor on a prefix of $xor[i]$ up to $i$. Then the xor on the interval can also be calculated as O(1). The solution was strictly successful due to the number of edges, which is not very large.
|
[
"dp",
"games",
"math"
] | 2,000
| null |
87
|
D
|
Beautiful Road
|
A long time ago in some country in Asia were civil wars.
Each of $n$ cities wanted to seize power. That's why sometimes one city gathered an army and sent it to campaign against another city.
Road making was difficult, so the country had few roads, exactly $n - 1$. Also you could reach any city from any other city going on those roads.
Even during the war the Oriental people remain spiritually rich and appreciate the beauty of nature. And to keep the memory of this great crusade for the centuries to come, they planted one beautiful tree by the road on which the army spent most time. The Oriental people love nature, that's why if there were several such roads, then one tree was planted by each of them.
Recently, when the records of the war were found, it became clear that each city attacked each other one exactly once. There were exactly $n(n - 1)$ attacks in total. Everyone has been wondering what road after those wars became the most beautiful, that is, by which road they planted the largest number of beautiful trees.
|
In this task we should count for each edge the number of ways on which it is maximal. Since for one edge alone it does not seem possible to find the answer faster than in the linear time, the solution will compute answer for all the edges at once. We shall solve the problem first for the two extreme cases, then, combining these two we will obtain a complete solution. The first case is when the weights of all edges are identical. In this case we can solve the problem via DFS. For each edge, we just need to count the number of paths that this edge lies on it. This number is the product of the number of vertexes on different sides of the edge. If we count the number of vertexes on one side from it, while knowing the total number of vertexes in the tree, it is easy to find the number of vertexes on the other side of it, and hence the required number of ways on which it lies. The second case - when the weights of all edges are distinct. Sort the edges in the order of the weight's increasing. Initially we take a graph with no edges. We add an edge in the order of increasing of weight. For each edge we join the connected components it connects. Then the answer for each new added edge is the product of the size of components that it has connected. Now we must combine these two cases. We will add the edges in the ascending order, but not one by one, but in the groups of the equal weight. We should understand what the answer is for each of the added edges. After adding our edges some number of connected components was formed - for each edge, we calculate the same product of the number of vertexes on different sides inside his newly formed connected component. To find this number of edges on the different sides, we should realize that it is only enough to know the sizes of the old connected components and connections between them - how they were arranged is not important to us. We use a DSU: adding an edge to our forest, we combine the old connected components by these edges. Note that prior to the merging of the components we must calculate an answer for our edges - and it is possible to make via a DFS on our compressed forest as in the first case, only instead of the number of vertexes on different sides of the edge we take the sum of the sizes of the connected components on different sides of the edge. How to do it neatly: It's good idea to dynamically create compressed graph at each step: it will have O(E') vertexes and edges, where E' - the number of added edges of the source tree. Do not create unnecessary vertexes in the new created compressed column: after all, the DFS works for O(V + E), rather than O(E), so the unused connected components we do not include in the circuit. We should use the 64-bit data type. To store the response of the order of $(10^{5})^{2}$ it will fit more than the 32-bit one. We should not merge the adjacency lists explicitly when connecting components. It is too long. You can do everything instead of arrays on vectors / maps / heap, so the total time of nulling of the marks for an array of DFS occupied O(V). Or, instead of nulling of the array overlays we keep instead of a Boolean flag the iteration number. In general, it is better not to null extra arrays. After all, algorithm can make V iterations. Be careful, solutions with map works at TL's maximum, so it should be written very carefully; you should better use the vectors + list of involved nodes. The author's solution with the map fits in the TL with only half a second to spare. While using a vector has a four-time stock of time to spare.
|
[
"dfs and similar",
"dp",
"dsu",
"graphs",
"implementation",
"sortings",
"trees"
] | 2,300
| null |
87
|
E
|
Mogohu-Rea Idol
|
A long time ago somewhere in the depths of America existed a powerful tribe governed by the great leader Pinnie-the-Wooh. Once the tribe conquered three Maya cities. Pinnie-the-Wooh grew concerned: there had to be some control over the conquered territories. That's why he appealed to the priests of the supreme god Mogohu-Rea for help.
The priests conveyed the god's will to him: to control these three cities he should put an idol to Mogohu-Rea — that will create a religious field over the cities. However, the idol is so powerful that it can easily drive the people around it mad unless it is balanced by exactly three sacrifice altars, placed one in each city. To balance the idol the altars should be placed so that the center of mass of the system of these three points coincided with the idol. When counting the center of mass consider that all the altars have the same mass.
Now Pinnie-the-Wooh is thinking where to put the idol. He has a list of hills, that are suitable to put an idol there. Help him to identify on which of them you can put an idol without risking to fry off the brains of the cities' population with the religious field.
Each city has a shape of a convex polygon such that no three vertexes lie on a straight line. The cities can intersect. Each altar should be attached to the city through a special ceremony, besides, it must be situated on the city's territory (possibly at the border). Thus, there may be several altars on a city's territory, but exactly one of them will be attached to the city. The altars, the idol and the hills are points on the plane, some of them may coincide.
The hills are taken into consideration independently from each other, the altars' location for different hills may also be different.
|
In this task we had to verify that the point is the centroid of the triangle formed by points of the given three polygons. Lets reformulate the problem. We should verify the existence of three points A, B, C, such that A belongs to the first polygon, B - to the second one, C - to the third one, and ${\overrightarrow{O A}}+{\overrightarrow{O B}}+{\overrightarrow{O C}}=3{\overrightarrow{O Q}}$. Logically, you should understand what set of points determines this ${\overrightarrow{O A}}+{\overrightarrow{O B}}+{\overrightarrow{O C}}$, you should understand how to build it and test a point on whether it belongs to the set or not. This set is called Minkowski sum. We will need only one of its properties: the sum of two convex polygons is a convex polygon whose sides coincide as vectors, with the sides of the original polygons. We will prove this later. How do we use it now? The first thing that this property gives us is an algorithm to test for belonging. Once the sum is built you can test whether or not a point belongs to the sum using a standard algorithm of testing a point being inside of a convex polygon in logarithmic time. Also the constructing algorithm is immediately obtained. We just need to add the coordinates of the lowest (the leftmost of them) points of all three polygons. As a result, we get a point, which is the lower left for the sum polygon. The sides are now represented as a sorted by the polar angles list of parties of the original polygons (instead of sorting we may merge sorted arrays). Proof. We shall prove the correctness of the algorithm for two polygons, for three polygons the proof is just the same. Let the first polygon be represented by A and the second one - by B. Denote the sum as M. We will prove that M is a convex set. Choose some $X,Y:X\neq Y,X,\ell\in M$. By definition, $X=P+Q,Y=E+F:P,E\in A,$ Q, $F\in B$(here and below the point is identified with its radius vector). Let's take some point $G\in[A B]$. We shall prove that $G\in M$. As G lies on the [AB], $\begin{array}{c}{{\exists\lambda\in\left[0,1\right]:G=X*\lambda+Y*\left(1-\lambda\right)=\left(P+P\right)*\lambda+\left(E+F\right)*\left(1-\lambda\right)=0}}\\ {{\left(P*\lambda+E*\left(1-\lambda\right)+\left(Q*\lambda+F*\left(1-\lambda\right)\right)}}\end{array}$. Note that the first bracket is obviously some point lying on the segment [PE]. That means the point lying inside the polygon A, since A is convex. Similarly, the second bracket is inside B. Hence, their sum, i.e., G, lies in the Minkowski sum. This means that the Minkowski sum is a convex set. Let us consider some side XY of the first polygon. Let's rotate the plane so that the side XY was horizontal and that the polygon lied above the XY line. Consider the lowest horizontal line intersecting B. Let it cross B along the segment of PR, where point P does not lie further to the right of the R (it is clear that PR can turn out to be a degenerate segment from one vertex or the segment between two consquent verteces). Let's call PR the lowest segment of the polygon. Then we construct in the similar way the lowest segment UV of polygon M. Let's prove that${\vec{U}}={\vec{X}}+{\vec{P}}$ - if not, let $\vec{U}=\vec{x}+\vec{p}$ . It is clear that x and p are the lowest points of the polygons A and B - otherwise one of them can be moved to a small vector d, which lies in the lower half-plane, so that the point remained within its polygon. In this case U will move the same way to d, which contradicts the fact that U is one of the lowest points of the polygon. Thus, x and p are the lowest points of their polygons. Similarly, x and p are the leftmost points on the lowest segments of their polygons - otherwise we shift x or p to vector d that is directed to the left. It is also a contradiction - the U point stops to be the leftmost lower point. Hence, U = X + P. Similarly, V = Y + Q. Hence, ${\overrightarrow{U V}}={\overrightarrow{X Y}}+{\overrightarrow{P Q}}$. Thus, the sequence of sides M as vectors in the, for instance, counterclockwise order, is nothing other than the union of sides of $A$ and $B$ as vectors in the counterclockwise order, that immediately proves the correctness of the algorithm.
|
[
"geometry"
] | 2,600
| null |
88
|
A
|
Chord
|
Vasya studies music.
He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note after the H similar and we will identify them with each other. The distance between the notes along the musical scale is measured in tones: between two consecutive notes there's exactly one semitone, that is, 0.5 tone. The distance is taken from the lowest tone to the uppest one, that is, the distance between C and E is 4 semitones and between E and C is 8 semitones
Vasya also knows what a chord is. A chord is an unordered set of no less than three notes. However, for now Vasya only works with triads, that is with the chords that consist of exactly three notes. He can already distinguish between two types of triads — major and minor.
Let's define a major triad. Let the triad consist of notes $X$, $Y$ and $Z$. If we can order the notes so as the distance along the musical scale between $X$ and $Y$ equals 4 semitones and the distance between $Y$ and $Z$ is 3 semitones, then the triad is major. The distance between $X$ and $Z$, accordingly, equals 7 semitones.
A minor triad is different in that the distance between $X$ and $Y$ should be 3 semitones and between $Y$ and $Z$ — 4 semitones.
For example, the triad "C E G" is major: between C and E are 4 semitones, and between E and G are 3 semitones. And the triplet "C# B F" is minor, because if we order the notes as "B C# F", than between B and C# will be 3 semitones, and between C# and F — 4 semitones.
Help Vasya classify the triad the teacher has given to him.
|
First we need to understand a simple fact - the notes are actually residues modulo 12. It means the minor chord has the form {x, x +3, x +7} (mod 12), and the major one - {x, x +4, x +7}. It is convenient to read the notes as strings, after that it is better to immediately replace them by a corresponding number from 0 to 11, that is, by their number. To perform the analysis, we needed to analyze consecutively the 6 possible orders in which the notes may follow one another in the chord. For each of the 6 orders we should check whether the chord is major or minor and if so, then immediately print the result. There's no chord that would be major and minor at the same time - this is checked by the consecutive analysis of the six possible comparison systems.
|
[
"brute force",
"implementation"
] | 1,200
| null |
88
|
B
|
Keyboard
|
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has $n$ rows of keys containing $m$ keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed $x$. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than $x$. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
|
Here we simply consecutively check for each letter of the alphabet in its two variants, uppercase and lowercase, whether it can be typed with one hand or not. And if we can't type it with one hand, we check whether it can be typed with two hands or can't be typed at all however how many hands one would use :-) To verify let's consider several cases. If the letter is lowercase, then we should simply check whether this letter is present on the keyboard, and if not, we do not type it. If the letter is uppercase, then we must check for each key with the corresponding letter if there is a Shift nearby, simply checking all the key pairs on the keyboard one by one. If there's no such letter or even a single Shift, then we do not type the letter as well. If such pair was found, but the distance between the two keys is too long, then we need another hand to type the letter. Let's sum (for all the text letters) the number of hands needed to type the text and terminate the problem with -1 if some letters just wouldn't be typed. The complexity is $|T| + 52 * (n \cdot m)^{2}$, which is quite enough.
|
[
"implementation"
] | 1,500
| null |
89
|
A
|
Robbery
|
It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has $n$ cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from $1$ to $n$ from the left to the right.
Unfortunately, Joe didn't switch the last security system off. On the plus side, he knows the way it works.
Every minute the security system calculates the total amount of diamonds for each two adjacent cells (for the cells between whose numbers difference equals $1$). As a result of this check we get an $n - 1$ sums. If at least one of the sums differs from the corresponding sum received during the previous check, then the security system is triggered.
Joe can move the diamonds from one cell to another between the security system's checks. He manages to move them no more than $m$ times between two checks. One of the three following operations is regarded as moving a diamond: moving a diamond from any cell to any other one, moving a diamond from any cell to Joe's pocket, moving a diamond from Joe's pocket to any cell. Initially Joe's pocket is empty, and it can carry an unlimited amount of diamonds. It is considered that before all Joe's actions the system performs at least one check.
In the morning the bank employees will come, which is why Joe has to leave the bank before that moment. Joe has only $k$ minutes left before morning, and on each of these $k$ minutes he can perform no more than $m$ operations. All that remains in Joe's pocket, is considered his loot.
Calculate the largest amount of diamonds Joe can carry with him. Don't forget that the security system shouldn't be triggered (even after Joe leaves the bank) and Joe should leave before morning.
|
Determine a form of all arrangements of diamonds that set of all sums of pairs adjacent cells is invariably. If you remove from the first cell exactly $c$ diamonds, you should add exactly $c$ diamonds into the second cell, remove $c$ diamonds from the third cell and so on. In other words, all valid arrangements can be produced by adding $c$ diamonds into every even cell and removing $c$ diamonds from every odd cell, where $c$ is some integer. $c$ lies in range from $-m i n\lbrace a[i],i\mathrm{~is~even}\rbrace$ to $min \{ a[i], i \text{ is odd} \}$ because otherwise number of diamonds in some cell will be less than zero. There is no more valid arrangements. Now consider a number of all diamonds in cells as a function of $c$. If $n$ is even, the sum always is constant. So there is impossible of theft diamonds and answer is $0$. For odd $n$ for every $c$ there is $c$ extra diamonds. So, Joe can theft no more than $min \{ a[i], i \text{ is odd} \}$ diamonds. It is easy for undarstanding that for increasing (or decreasing) $c$ by some constant $x$ Joe should do $x(n + 1) / 2$ moves, but he cannot done it by lass count of moves. In one minute Joe can change $c$ no more than on $[m / ((n + 1) / 2)]$. Common number of diamonds thet Joe can theft for all time is $k[m / ((n + 1) / 2)]$, but you should take into account a limits for changing of $c$. At the end common solution is following: If $n$ is even, answer is 0, otherwise answer is $m i n(m i n\{a[i],i\;\mathrm{is\;odd}\},k[m/((n+1)/2)])$. Be careful fith overflow of 32bit integers. Here you should use an 64bit integers.
|
[
"greedy"
] | 1,800
| null |
89
|
B
|
Widget Library
|
Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other.
A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type.
Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets — they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change.
We shall assume that the widget $a$ is packed in the widget $b$ if there exists a chain of widgets $a = c_{1}, c_{2}, ..., c_{k} = b$, $k ≥ 2$, for which $c_{i}$ is packed directly to $c_{i + 1}$ for any $1 ≤ i < k$. In Vasya's library the situation when the widget $a$ is packed in the widget $a$ (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error.
Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal $0$.
The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox — vertically. The parameter spacing sets the distance between adjacent widgets, and border — a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to $0 × 0$, regardless of the options border and spacing.
The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data.
For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript.
|
Here you can build some miltigraph in which nodes are widgets and edges are relationship of pack()-method. This graph is acyclic. Next, you should do topological sort of nodes. Sizes of widgets should be calculated in the obtained order. At the last, you should sort all nodes by thier names and output an answer. About implementation. Parsing of instructions is very easy if you swap charachers '.', ',', '(', ')' by spaces. Now you can just split instructions into strings using spaces as separators. Multigraph can be saved into matrix. Cell M[i][j] contains integer number that means number of edges from node i to node j. Topological sort can be done by any stupid method. For example, you can choose $k$ times node that has no outgoing edges to unselected nodes, where $k$ is numder of nodes. Every check can be done in $O(k^{2})$. You should recalculate sizes of widgets using 64-bit integets (a tip was is statement). In a test like 100 Widget w(100,100) HBox box box.pack(w) box.set_border(100) HBox a a.pack(box) a.pack(box) HBox b b.pack(a) b.pack(a) HBox c c.pack(b) c.pack(b) ... width of widgets grows exponentially. In jurys' tests maximum length of a side of widgets was 103079215104000. You can get that length by packing 4 widgets everu time instead of 2 widgets.
|
[
"dp",
"expression parsing",
"graphs",
"implementation"
] | 2,300
| null |
89
|
C
|
Chip Play
|
Let's consider the following game. We have a rectangular field $n × m$ in size. Some squares of the field contain chips.
Each chip has an arrow painted on it. Thus, each chip on the field points in one of the following directions: up, down, left or right.
The player may choose a chip and make a move with it.
The move is the following sequence of actions. The chosen chip is marked as the current one. After that the player checks whether there are more chips in the same row (or in the same column) with the current one that are pointed by the arrow on the current chip. If there is at least one chip then the closest of them is marked as the new current chip and the former current chip is removed from the field. After that the check is repeated. This process can be repeated several times. If a new chip is not found, then the current chip is removed from the field and the player's move ends.
By the end of a move the player receives several points equal to the number of the deleted chips.
By the given initial chip arrangement determine the maximum number of points that a player can receive during one move. Also determine the number of such moves.
|
This problem can be solved by simulation. You can just iterate over all chips and for every of them calculate number of points. But srupid simulate can give $O(k^{3})$ time solution, where $k$ is total number of chips. It doesn't fit into time limits. For example, try test like 1 5000 RRRR...[2500 times]LLLL...[2500 times] You can simulate process in $O(k^{2}\log k)$ time by using some data structures like std::set, but it doesn't fit into limits too. Similating in $O(k^{2})$ time is given by following data structure. For every chip you can save links to chips that is placed up, doun, left and right from the considered chip. Net of links can be built in O($nm$). Now, when you simulate process, you can remove chips this way: Chip->L->R = Chip->R Chip->R->L = Chip->L Chip->U->D = Chip->D Chip->D->U = Chip->U So, jump from some chip to the next chip in a move can be done in $O(1)$. Now you can simulate every move in $O(k)$. Remove operation is reversible because every removed chip stores links to all of its neighbours. Therefore you can save links to all removed chips in current move and after restore net of links using following operetions for all removed chips in reversed order Chip->L->R = Chip Chip->R->L = Chip Chip->U->D = Chip Chip->D->U = Chip Also you can just build net of links anew for every move.
|
[
"brute force",
"data structures",
"implementation"
] | 2,300
| null |
89
|
D
|
Space mines
|
Once upon a time in the galaxy of far, far away...
Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star.
When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon — space mines. Let's describe a space mine's build.
Each space mine is shaped like a ball (we'll call it the mine body) of a certain radius $r$ with the center in the point $O$. Several spikes protrude from the center. Each spike can be represented as a segment, connecting the center of the mine with some point $P$, such that $r<|O P|\leq{\frac{3}{2}}r$ (transporting long-spiked mines is problematic), where $|OP|$ is the length of the segment connecting $O$ and $P$. It is convenient to describe the point $P$ by a vector $p$ such that $P = O + p$.
The Death Star is shaped like a ball with the radius of $R$ ($R$ exceeds any mine's radius). It moves at a constant speed along the $v$ vector at the speed equal to $|v|$. At the moment the rebels noticed the Star of Death, it was located in the point $A$.
The rebels located $n$ space mines along the Death Star's way. You may regard the mines as being idle. The Death Star does not know about the mines' existence and cannot notice them, which is why it doesn't change the direction of its movement. As soon as the Star of Death touched the mine (its body or one of the spikes), the mine bursts and destroys the Star of Death. A touching is the situation when there is a point in space which belongs both to the mine and to the Death Star. It is considered that Death Star will not be destroyed if it can move infinitely long time without touching the mines.
Help the rebels determine whether they will succeed in destroying the Death Star using space mines or not. If they will succeed, determine the moment of time when it will happen (starting from the moment the Death Star was noticed).
|
Initially lets pump all mines on radius of Death Star and squeeze Death Star into point. Now you should determine an intersection of a ray with obtained figures. Mine's body with radius $r$ is pumped into ball with radius $r + R$. Every mine's spike is pumped into union of two balls with radius $R$ and cylinder. One of these balls lies inside of pumped mine's body, therefore you can don't consider it. Let length of spike is $r_{0}$. Then cylinder will have heigth $r_{0}$ and radius $R$. A distance between center of one base of the cylinder and edge of another one equals $\sqrt{r_{0}^{2}+R^{2}}$. Following unequation proves that this distance always less than radius of pumped mine's body and cylinder lies inside of the pumped mine's body: $r_{0}^{2}+R^{2}\le\textstyle{\frac{9}{4}}r^{2}+R^{2}<r^{2}+{\textstyle{\frac{5}{4}}}r R+R^{2}<r^{2}+2r R+R^{2}=(r+R)^{2}.$ So, you can don't consider the cylinders too. For every spike you should store only ball of radius $R$ with center in a peak of the spike. Now we have set of balls, we are needed to determine a time in that some point collides with every of those balls. Lets write an equation: $|A + vt - O| = R$, where $A$ is start position of point, $v$ is vector of its velocity, $O$ is center of ball, $R$ is its radius. Lets rewrite equation in scalar variables: $(A_{x} + v_{x}t - O_{x})^{2} + (A_{y} + v_{y}t - O_{y})^{2} + (A_{z} + v_{z}t - O_{z})^{2} = R^{2}.$ When you expand brackets, you receive some quadratic equation from variable $t$: $At^{2} + Bt + C = 0$. You should solve it and choose minimal root (minimal root is time of the first collision of point with the ball, maximal one is time of the second collision). Check than root more than 0. Now you should determine all times and choose minimum of them. If there are no collisions, answer is -1. All checking should be done in integer 64bit numbers for absolutely precision.
|
[
"geometry"
] | 2,500
| null |
89
|
E
|
Fire and Ice
|
The Fire Lord attacked the Frost Kingdom. He has already got to the Ice Fortress, where the Snow Queen dwells. He arranged his army on a segment $n$ in length not far from the city walls. And only the frost magician Solomon can save the Frost Kingdom.
The $n$-long segment is located at a distance equal exactly to $1$ from the castle walls. It can be imaginarily divided into unit segments. On some of the unit segments fire demons are located — no more than one demon per position. Each demon is characterised by his strength - by some positive integer. We can regard the fire demons being idle.
Initially Solomon is positioned on the fortress wall. He can perform the following actions several times in a row:
- "L" — Solomon shifts one unit to the left. This movement cannot be performed on the castle wall.
- "R" — Solomon shifts one unit to the left. This movement cannot be performed if there's no ice block to the right.
- "A" — If there's nothing to the right of Solomon, then Solomon creates an ice block that immediately freezes to the block that Solomon is currently standing on. If there already is an ice block, then Solomon destroys it. At that the ice blocks to the right of the destroyed one can remain but they are left unsupported. Those ice blocks fall down.
Solomon spends exactly a second on each of these actions.
As the result of Solomon's actions, ice blocks' segments fall down. When an ice block falls on a fire demon, the block evaporates and the demon's strength is reduced by $1$. When the demons' strength is equal to $0$, the fire demon vanishes. The picture below shows how it happens. The ice block that falls on the position with no demon, breaks into lots of tiny pieces and vanishes without hurting anybody.
Help Solomon destroy all the Fire Lord's army in minimum time.
|
Solomon can just create some segments of ice cubes and cut its. Consider a segment with rightmost begin. You can assume that it ends in position of the last demon (you always can cut end of a segment that ends on last demon and add it to current segment). For cutting the last segment you should build "ice bridge" to it. When you are building this bridge, you should create and cut all others segments. Now iterate over all start positions of the last segment. For every of them you should decrease powers of demons that is covered by this segment and calculate minimal number of moves for destroy all demons (do not forgen about the last segment!). You can see that for every fallen ice cube you need exactly 3 operations --- go left, create cube, go right. For cutting a segment you need exactly 2 operations --- create cube and destroy one. Therefore all demons should be covered by minimal number of segments that no cube falls on an empty position. It can be done by greedy algorithm. Total number of operations for every start position of the last segment can be calculated in $O(n)$. Total number of checks is $O(n)$, so we have an $O(n^{2}) solution$. After all, answer can be built very easy.
|
[
"greedy"
] | 2,900
| null |
90
|
A
|
Cableway
|
A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.
A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.
The number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly $30$ minutes for a cablecar to get to the top.
All students are divided into three groups: $r$ of them like to ascend only in the red cablecars, $g$ of them prefer only the green ones and $b$ of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like,
The first cablecar to arrive (at the moment of time $0$) is painted red. Determine the least time it will take all students to ascend to the mountain top.
|
In this problem you can simulate the process. You can consider all minutes and in dependence by a color of a current cablecar decrease size of corresponding group of students $G$ by $min(|G|, 2)$, where $|G|$ is size of the group. After that you should determine the first minute $t$ in that all three groups of students will be empty. So $t + 30$ is an answer. This solution works in $O(r + g + b)$. Also there is $O(1)$ solution. It is following formula: $ans = max(3[(R + 1) / 2] + 27, 3[(G + 1) / 2] + 28, 3[(B + 1) / 2] + 29)$ where $[x]$ is rounding down.
|
[
"greedy",
"math"
] | 1,000
| null |
90
|
B
|
African Crossword
|
An African crossword is a rectangular table $n × m$ in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.
When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.
You are suggested to solve an African crossword and print the word encrypted there.
|
It this problem you should write exactly that is written in statement. For every letter you should see a row and a column of the letter. If equal letter was found, current letter sould not be output. You can combine scanning rows and columns and output an answer, for example, this way: FOR(a,1,n) FOR(b,1,m) { bool should_out=true; FOR(c,1,n) if (c!=a) if (T[a][b]==T[c][b]) should_out=false; FOR(c,1,m) if (c!=b) if (T[a][b]==T[a][c]) should_out=false; if (should_out) printf("%c", T[a][b]); } This solution works in $O(mn(n + m))$. Also here an $O(nm)$-solution exitsts. In every row and column you can calculate a number of every letter of an alphabet. After that check for output can be done in $O(1)$. You just should check that numbers of entries of considered letter into corresponding row and column equal exactly 1.
|
[
"implementation",
"strings"
] | 1,100
| null |
91
|
A
|
Newspaper Headline
|
A newspaper is published in Walrusland. Its heading is $s_{1}$, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word $s_{2}$. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.
For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions $1$ and $5$, we get a word "bcac".
Which least number of newspaper headings $s_{1}$ will Fangy need to glue them, erase several letters and get word $s_{2}$?
|
In this problem letters from $s1$ should be taken greedily: take the left letter from the right of the last used letter, if there is no necessary letter from the right of the right used letter the the search should be started from the beginning of string $s1$ and the answer should be increased by one. But the brute solution get $TL$ and have complexity $O(Ans * |s1|)$. This solution can be optimized using the following way. For every position in $s1$ let's precalculate positions of the closest letters from the right of it from the alphabet. It can be done by moving from the right to the left ins $s1$ and remembering the last position of every type of symbol. This solution have complexity $O(|s1| * K + |s2|)$, where $K$ is a size of alphabet.
|
[
"greedy",
"strings"
] | 1,500
| null |
91
|
B
|
Queue
|
There are $n$ walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the $1$-st walrus stands at the end of the queue and the $n$-th walrus stands at the beginning of the queue. The $i$-th walrus has the age equal to $a_{i}$.
The $i$-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such $j$ ($i < j$), that $a_{i} > a_{j}$. The \underline{displeasure} of the $i$-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the $i$-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.
The airport manager asked you to count for each of $n$ walruses in the queue his displeasure.
|
There were a lot of different solutions but I will tell you the author solution. Let's precalculate $[i, n]$. It can be done with the time equal to $O(n)$ moving from the right to the left. Define $[i, n]$ as $Min_{i}$. Obviously, that $Min_{i} < = Min_{i + 1}$. Now for every position $i$ using binary search let's find j ($j > i$), that $Min_{j} < a_{i}$ and $Min_{j + 1} > = a{i}$. For such $j$ there are no walruses who have age younger then walrus $i$. It's obviously because $Min_{j}$ is the minimum on $[j, n]$. If there is no such $j$ then print $- 1$ else print $j - i - 1$.
|
[
"binary search",
"data structures"
] | 1,500
| null |
91
|
C
|
Ski Base
|
A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains $n$ ski junctions, numbered from $1$ to $n$. Initially the junctions aren't connected in any way.
In the constructing process $m$ bidirectional ski roads will be built. The roads are built one after another: first the road number $1$ will be built, then the road number $2$, and so on. The $i$-th road connects the junctions with numbers $a_{i}$ and $b_{i}$.
\underline{Track} is the route with the following properties:
- The route is closed, that is, it begins and ends in one and the same junction.
- The route contains at least one road.
- The route doesn't go on one road more than once, however it can visit any junction any number of times.
Let's consider the \underline{ski base} as a non-empty set of roads that can be divided into one or more tracks so that exactly one track went along each road of the chosen set. Besides, each track can consist only of roads from the chosen set. Ski base doesn't have to be connected.
Two ski bases are considered different if they consist of different road sets.
After building each new road the Walrusland government wants to know the number of variants of choosing a ski base based on some subset of the already built roads. The government asks you to help them solve the given problem.
|
We will count the number of ski bases including the base consisted of empty subset of edges (before printing just subtract one). In the beginning the number of bases is equal to $1$. If we connect vertexes in the same connected components then the result should be multiplied by $2$ else do nothing. You should use DJS data structure to know information about connected components where vertexes are and to unite them. Why is it correct? To prove it we will use the matrix of incidence $I$, rows in it will be edges and columns will be vertexes. Let's define $xor$ of two rows. $Xor$ of two rows $a$ and $b$ will be row $c$ such that $c_{i} = a_{i}$ xor $b_{i}$. Notice if $xor$ of some subset of rows is equal to a zero row then this subset form the ski base. It's correct because, the degree of contiguity of every vertex is even, so we can form an Euler cycle in every connected component. The answer is $2^{}(m - rank(I))$. Why it is correct? Let's write the number of edge from the right of each row which suit this row. While finding the matrix rank using gauss method with $xor$ operation, we will $xor$ the subsets from the right of the strings. In the end the subsets of edges written from the right of the zero rows will form the basis of the linear space. Thats why we can take any subset of vectors from basis and make up a new ski base. The number of these subsets is equal to $2^{k}$ = $2^{}(m - rank(I))$, where k is the number of zero rows. The last thing we should notice that the adding row is liner depended if and only if there is exist a way between the vertexes $a$ and $b$ ($a$ and $b$ are the ends of the adding edge).
|
[
"combinatorics",
"dsu",
"graphs"
] | 2,300
| null |
91
|
D
|
Grocer's Problem
|
Yesterday was a fair in a supermarket's grocery section. There were $n$ jars with spices on the fair. Before the event the jars were numbered from $1$ to $n$ from the left to the right. After the event the jars were moved and the grocer had to sort them by the increasing of the numbers.
The grocer has a special machine at his disposal. The machine can take any $5$ or less jars and rearrange them in the way the grocer wants. Note that the jars \textbf{do not have to} stand consecutively. For example, from the permutation $2$, $6$, $5$, $4$, $3$, $1$ one can get permutation $1$, $2$, $3$, $4$, $5$, $6$, if pick the jars on the positions $1$, $2$, $3$, $5$ and $6$.
Which minimum number of such operations is needed to arrange all the jars in the order of their numbers' increasing?
|
Let's find all cycles in substitution: $1$ $2$ $3$ $4$ $5$ ... $a_{1}$ $a_{2}$ $a_{3}$ $a_{4}$ $a_{5}$ ... For example, in sequence $a = {2, 1, 4, 5, 3}$ exist two cycles with length $2$ and $3$ on positions $1$ $2$ and $3$ $4$ $5$ respectively. If the length of the cycle is more than $5$, then we can take $5$ consecutive elements and make a new order in such way that $4$ elements will take their places where they should be in sorted array. In common: if we take $p$ elements in a cycle of length more than $p$, the we can make a new order in such way that $p - 1$ elements will take their places where they should be in sorted array. If the cycle length is $p$ we can sort all the elements taking $p$ elements from it. Next in the analysis I will define length of a cycle as a real length of a cycle - 1 (now I can say that if we take $p$ consecutive elements then $p - 1$ will take the right places). We also can take some elements in one and some elements in other cycles. We can make up division numbers from $2$ to $5$ into a sum to see how we can use them: $5$, $4$, $3$, $2$, $2 + 3$, $2 + 2$. We can take, for example, three elements in one cycle and two in other, their sizes were reduced by 2 and 1. The task now is to get all cycle lengths equal to zero. Let's to suppose that an optimal solution have four operations which decrease the same cycle length by one. We will work with operations of $5$ elements and which are not process the same cycle except one, because it's more stronger condition. Such operation can be shown as a table where rows are operations, columns are cycles and cells of table are the values on which cycles will be reduced. a b c d e 1 2 1 2 1 2 1 2 Replace operations this way: a b c d e 4 2 1 1 2 2 The number of operations was not increased, but now we can see that if there is an optimal solution where one cycle reduced by one four times then there is an optimal solution where no cycles reduced by one four times. Look at some other replacements: a b c 2 1 2 1 Replace by: a b c 4 1 1 and a b c d 2 1 1 2 1 2 Replace by: a b c d 4 1 2 2 Now we can see that there is an optimal solution where no operation reducing one cycle in ways:$1 + 1 + 1 + 1$, $2 + 2$, $1 + 1 + 2$. That's why we can reduce any cycle by $4$ while it's size is $> = 4$. Let's use zhe same method to prove that cycles of size $3$ reduced by $3$ in some optimal solution. a b c 2 1 1 2 Replace by: a b c d 3 1 2 and a b c d 1 2 1 2 1 2 Replace by: a b c d 3 2 1 1 2 Now we have cycles only with size $1$ or $2$. Let's brute the number of operations to process like ${2, 2} - > {0, 1}$ (one cycle will be reduced from $2$ to $1$ and the other will be reduced from $2$ to $0$). Fix some such number and make these operations. Now we should process the maximum available operations like ${2, 1} - > {0, 0}$. After it we will have no cycles or some cycles of size $1$ or some cycles of size $2$. In the second case we should do the maximum of available operations like ${1, 1} - > {0, 0}$ and if one cycle lasts we should do ${1} - > {0}$. In the third case we should to do operations like ${2} - > {0}$. Using such way we can find the optimal set of operations. We shouldn't divide cycle into a parts because it makes the number of operation bigger or the same. Stress test shows the uniting cycles will not improve the answer.
|
[
"constructive algorithms",
"graphs",
"greedy"
] | 2,600
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.