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
1
A
Theatre Square
Theatre Square in the capital city of Berland has a rectangular shape with the size $n × m$ meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size $a × a$. What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
The constraint that edges of each flagstone much be parralel to edges of the square allows to analyze X and Y axes separately, that is, how many segments of length 'a' are needed to cover segment of length 'm' and 'n' -- and take product of these two quantities. Answer = ceil(m/a) * ceil(n/a), where ceil(x) is the least integer which is above or equal to x. Using integers only, it is usually written as ((m+a-1)/a)*((n+a-1)/a). Note that answer may be as large as 10^18, which does not fit in 32-bit integer. Most difficulties, if any, contestants had with data types and operator priority, which are highly dependant on language used, so they are not covered here.
[ "math" ]
1,000
null
1
B
Spreadsheet
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc. The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example. Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
Let each letter representation of column number be associated with integer in radix-26, where 'A' = 0, 'B' = 1 ... 'Z'=25. Then, when converting letter representation to decimal representation, we take associated integer and add one plus quantity of valid all letter representations which are shorter than letter representation being converted. When converting from decimal representation to letter representation, we have to decide how many letters do we need. Easiest way to do this is to subtract one from number, then quantity of letter representation having length 1, then 2, then 3, and so on, until next subtraction would have produced negative result. At that point, the reduced number is the one which must be written using defined association with fixed number of digits, with leading zeroes (i.e. 'A's) as needed. Note that there is other ways to do the same which produce more compact code, but they are more error-prone as well.
[ "implementation", "math" ]
1,600
null
1
C
Ancient Berland Circus
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different. In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a special pillar, and the rope strung between the pillars marked the arena edges. Recently the scientists from Berland have discovered the remains of the ancient circus arena. They found only three pillars, the others were destroyed by the time. You are given the coordinates of these three pillars. Find out what is the smallest area that the arena could have.
The points can be vertices of regular N-polygon, if, and only if, for each pair, difference of their polar angles (as viewed from center of polygon) is a multiple of 2*pi/N. All points should lie on the circle with same center as the polygon. We can locate the center of polygon/circle [but we may avoid this, as a chord (like, say, (x1,y1)-(x2,y2)) is seen at twice greater angle from center, than it is seen from other point of a cricle (x3,y3)]. There are many ways to locate center of circle, the way I used is to build midpoint perpendiculares to segments (x1,y1)-(x2,y2) and (x2,y2)-(x3,y3) in form y = a*x + b and find their intersection. Formula y = a*x + b has drawback that it cannot be used if line is parallel to y, possible workaround is to rotate all points by random angle (using formulae x' = x*cos(a) - y*sin(a), y' = y*cos(a) + x*sin(a) ) until no segments are horizontal (and hence no perperdiculares are vertical). After the coordinates of the center are known, we use fancy function atan2, which returns angle in right quadrant: a[i] = atan2(y[i]-ycenter, x[i]-xcenter) Area of regular polygon increases with increasing N, so it is possible just to iterate through all possible values on N in ascending order, and exit from cycle as first satisfying N is found. Using sin(x) is makes it easy: sin(x) = 0 when x is mutiple of pi. So, for points to belong to regular, N-polygon, sin( N * (a[i]-a[j]) /2 )=0 because of finite precision arithmetic, fabs( sin( N * (a[i]-a[j]) /2 ) ) < eps
[ "geometry", "math" ]
2,100
null
2
A
Winner
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to $m$) at the end of the game, than wins the one of them who scored at least $m$ points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.
To solve the problem we just need accurately follow all rules described in the problem statement. Let's describe in more details required sequence of actions. First of all, we need to find the maximum score m at the end of the game. This can be done by emulating. After all rounds played just iterate over players and choose one with the maximum score. Second, we need to figure out the set of players who have maximum score at the end of the game. We can do this in the same way as calculating maximum score. Just iterate over players after all rounds played and store all players with score equal to m. And the last, we need to find a winner. To do this we will emulate the game one more time looking for player from the winner list with score not less m after some round. This task demonstrates that sometimes it is easier to code everything stated in the problem statement, than thinking and optimizing.
[ "hashing", "implementation" ]
1,500
null
2
B
The least round way
There is a square matrix $n × n$, consisting of non-negative integer numbers. You should find such a way on it that - starts in the upper left cell of the matrix; - each following cell is to the right or down from the current cell; - the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
First of all, let's consider a case when there is at least one zero number in the square. In this case we can easily create a way with only one trailing zero in resulting multiplication - just output way over this zero number. The only case when this is not optimal way is when a way exists with no trailing zeroes at all. So, we can replace all 0's with 10's and solve the problem in general case. If there is an answer with no trailing zeroes - we will choose this one, otherwise we will output way over zero number. So, we can consider that all numbers in the square are positive. Let's understand what the number of zeroes in the resulting multiplication is. If we go along a way and count number of 2's and 5's in numbers factorization then the number of trailing zeros will be min(number of 2's, number of 5's). This allows us to solve the problem independently for 2's and 5's. The final answer will be just a minimum over these two solutions. Now, the last thing left is to solve the problem for 2's and 5's. New problem interpretation is the following: there is a square with numbers inside. We are to find a way with the minimal sum of the number over the way. This is classical dynamic programming problem. Let's consider that A[r,c] is the number in cell (r,c) and D[r,c] is the answer for this cell. Then D[r,c] = min(D[r-1,c],D[r,c-1]) + A[r][c]
[ "dp", "math" ]
2,000
null
2
C
Commentator problem
The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to choose the best point of observation, that is to say the point from where all the three stadiums can be observed. As all the sport competitions are of the same importance, the stadiums should be observed at the same angle. If the number of points meeting the conditions is more than one, the point with the maximum angle of observation is prefered. Would you, please, help the famous Berland commentator G. Berniev to find the best point of observation. It should be noted, that the stadiums do not hide each other, the commentator can easily see one stadium through the other.
Let's take two stadiums and find out a set of points from which the stadiums are observed at the same angle. Not very hard mathematical calculation shows that this is a line if stadiums have the same radius and this is a circle if they have different radiuses. Let's define S(i,j) as a set of points from which the stadiums i and j are observed at the same angle. Given that centers of stadiums are not on the same line, the intersection of S(1,2) with S(1,3) contains no more than two points. If we know these no more that 2 points we can double-check that they satisfy the criteria and chose the point with the maximum angle of observation.
[ "geometry" ]
2,600
null
5
A
Chat Servers Outgoing Traffic
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: - Include a person to the chat ('Add' command). - Remove a person from the chat ('Remove' command). - Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands. Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends $l$ bytes to each participant of the chat, where $l$ is the length of the message. As Polycarp has no time, he is asking for your help in solving this problem.
Both are implementation problems. The only difficult, many participants faced with - to read data correctly. It is recommended to use gets(s) or getline(cin, s) in C++, readLine() method of BufferedReader class in Java.
[ "implementation" ]
1,000
null
5
B
Center Alignment
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product. You are to implement the alignment in the shortest possible time. Good luck!
Both are implementation problems. The only difficult, many participants faced with - to read data correctly. It is recommended to use gets(s) or getline(cin, s) in C++, readLine() method of BufferedReader class in Java.
[ "implementation", "strings" ]
1,200
null
5
C
Longest Regular Bracket Sequence
This is yet another problem dealing with regular bracket sequences. We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.
First of all, for each closing bracket in our string let's define 2 values: d[j] = position of corresponding open bracket, or -1 if closing bracket doesn't belong to any regular bracket sequence. c[j] = position of earliest opening bracket, such that substring s(c[j], j) (both boundaries are inclusive) is a regular bracket sequence. Let's consider c[j] to be -1 if closing bracket doesn't belong to any regular bracket sequence. It can be seen, that c[j] defines the beginning position of the longest regular bracket sequence, which will end in position j. So, having c[j] answer for the problem can be easily calculated. Both d[j] and c[j] can be found with following algorithm, which uses stack. Iterate through the characters of the string. If current character is opening bracket, put its position into the stack. If current character is closing bracket, there are 2 subcases: Stack is empty - this means that current closing bracket doesn't have corresponding open one. Hence, both d[j] and c[j] are equal to -1. Stack is not empty - we will have position of the corresponding open bracket on the top of the stack - let's put it to d[j] and remove this position from the stack. Now it is obvious, that c[j] is equal at least to d[j]. But probably, there is a better value for c[j]. To find this out, we just need to look at the position d[j] - 1. If there is a closing bracket at this position, and c[d[j] - 1] is not -1, than we have 2 regular bracket sequences s(c[d[j] - 1], d[j] - 1) and s(d[j], j), which can be concatenated into one larger regular bracket sequence. So we put c[j] to be c[d[j] - 1] for this case.
[ "constructive algorithms", "data structures", "dp", "greedy", "sortings", "strings" ]
1,900
null
5
D
Follow Traffic Rules
Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of $a$ km/h$^{2}$, and has maximum speed of $v$ km/h. The road has the length of $l$ km, and the speed sign, limiting the speed to $w$ km/h, is placed $d$ km ($1 ≤ d < l$) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed.
This problem can be solved by careful case handling. Let's construct O(1) solution for it. First of all, let's define 2 functions: $dist(speed, time)$ - calculates the distance will be covered in specified time, if car's current speed is speed. This function will not take car's speed limit into account. Also it assumes, that car is always driven with maximum acceleration $a$. It is obvious that required distance is equal to $speed * time + (a * time^2) / 2$. $travelTime(distance, speed)$ - calculates the time, required to travel specified distance, if car have starting speed equal to speed. This function will also take care about car's speed limit. We will have the following quadratic equation for time $t$: $a\ast(t^{2})/2+s p e e d*t-d i s t a n c e=0$. This equation will have exactly 2 different roots. Using Viete's formulas it can be concluded, that one root of the equation is non-positive and other is non-negative. Let's define the larger root of the equation as $tAll$. It will be the answer, if there is no car's speed limit. To take the limit into account let's find the time, required to gain car's max speed. $tMax = (v - speed) / a$. If $tMax \ge tAll$, function should just returns $tAll$ as a result. Otherwise result is $tMax$ hours to achieve car's maximal speed plus $(distance - dist(speed, tMax)) / v$ hours to cover remaining distance. Having these functions, solution will be the following: If $v \le w$, answer is $travelTime(l, 0)$. Calculate $tw = w / a$ - time, required to gain speed $w$. Consider $dw = dist(0, tw)$. If $dw \ge d$, we will pass the point there sign is placed before we gain speed $w$. Answer for this case is $travelTime(l, 0)$ as well. Otherwise, we will gain speed $w$ before the sign. Let's consider segment of the road $[dw, d]$. We need to find out the best strategy to drive it. It is obvious, that we definitely should have speed $w$ at the both ends of this segment. Also we know, that acceleration is equal to deceleration. Taking these facts into account we can see, that the speed in the optimal solution will be symmetrical with respect to the middle of the segment $[dw, d]$. Hence answer for this case will be $tw + 2 * travelTime(0.5 * (d - dw), w) + travelTime(l - d, w)$.
[ "implementation", "math" ]
2,100
null
5
E
Bindian Signalizing
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by $n$ hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night. In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other. An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Let's reduce the problem from the circle to the straight line. Perform the following actions to do it: Find the hill with the maximal height (if it is not unique, choose any). Rotate all the sequence in such a way that hill with maximal height goes first. For convenience, add one more hill with maximum height to the end of the sequence. (It will represent the first hill, which goes after the last in the circle order). Now we have almost the same problem on the straight line. One exception is that now first hill is doubled. General idea of the solution: Consider there is a pair of hills, such that these hills are visible from each other. Let's define hill with lower height (if heights are equal - with lower position) as responsible for adding this pair to the answer. From this point of view, hill x will adds to the answer 3 kinds of hills as his pair: First hill to the left of the x, which is strictly higher than x. (Let's define its position as l[x]) First hill to the right of the x, which is strictly higher than x. (Let's call this hill y and define it's position as r[x]). All hills that are as high as x and are located between x and y. (Let's define this count as c[x]). Arrays r[x] and c[x] can be calculated by the following piece of code: c[n] = 0; for(int i = n - 1; i >= 0; --i) { r[i] = i + 1; while (r[i] < n && height[i] > height[r[i]]) r[i] = r[r[i]]; if (r[i] < n && height[i] == height[r[i]]) { c[i] = c[r[i]] + 1; r[i] = r[r[i]]; } } I am not going to prove here, that it works for the O(N) time, but believe it does :) Pay attention, that r[x] is undefined for hills with maximum height and this algorithm will find r[x] = n for such hills. Array l[x] can be found in a similar way. Having l[x], r[x] and c[x], it's not so difficult to calculate the answer. We should just notice, that: Each hill will add c[x] pairs to the answer. Each hill, lower than maximal, will also add 2 pairs (x, l[x]) and (x, r[x]) to the answer. The only corner case here is l[x] = 0 and r[x] = n, because (x, 0) and (x, n) is the same pair of hills in the original problem, where hills are circled.
[ "data structures" ]
2,400
null
6
A
Triangle
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same. The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
For each of the possible combinations of three sticks , we can make a triangle if sum of the lengths of the smaller two is greater than the length of the third and we can make a segment in case of equality.
[ "brute force", "geometry" ]
900
#include <iostream> using namespace std; bool tr(int a,int b,int c) { return ((a+b>c)&&(a+c>b)&&(b+c>a)); } bool seg(int a,int b,int c) { return ((a==b+c)||(b==a+c)||(c==a+b)); } int main() { bool normal=false; bool deg=false; int a,b,c,d; cin>>a>>b>>c>>d; normal=normal||(tr(a,b,c)); normal=normal||(tr(a,b,d)); normal=normal||(tr(a,c,d)); normal=normal||(tr(b,c,d)); deg=deg||(seg(a,b,c)); deg=deg||(seg(a,b,d)); deg=deg||(seg(a,c,d)); deg=deg||(seg(b,c,d)); if(normal) cout<<"TRIANGLE"<<endl; else if(deg) cout<<"SEGMENT"<<endl; else cout<<"IMPOSSIBLE"<<endl; return 0; }
6
B
President's Office
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length. The office-room plan can be viewed as a matrix with $n$ rows and $m$ columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.
For each cell of president's desk , we check all its neighbors and add their colors to a set. easy as pie!
[ "implementation" ]
1,100
#include <iostream> #include <string> #include <set> using namespace std; set<char> adj; int main() { int n,m; char c; cin>>n>>m>>c; string room[n]; for(int i=0;i<n;i++) cin>>room[i]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(room[i][j]==c) { if(i!=0&&room[i-1][j]!=c) adj.insert(room[i-1][j]); if(i!=n-1&&room[i+1][j]!=c) adj.insert(room[i+1][j]); if(j!=0&&room[i][j-1]!=c) adj.insert(room[i][j-1]); if(j!=m-1&&room[i][j+1]!=c) adj.insert(room[i][j+1]); } } } int x=0; if(adj.find('.')!=adj.end()) x--; cout<<adj.size()+x<<endl; return 0; }
6
C
Alice, Bob and Chocolate
Alice and Bob like games. And now they are ready to start a new game. They have placed $n$ chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman. How many bars each of the players will consume?
This one can be solved easily by simulation. see the code.
[ "greedy", "two pointers" ]
1,200
#include <iostream> #include <deque> #include <algorithm> using namespace std; struct eater{ int ate; int wait; void init() { ate=wait=0; } }; int main() { eater alice,bob; bob.init(); alice.init(); int n; cin>>n; deque<int> chocs; for(int i=0;i<n;i++) { int t; cin>>t; chocs.push_back(t); } while(chocs.size()>0) { if(alice.wait!=0) alice.wait--; if(bob.wait!=0) bob.wait--; if(alice.wait==0) { alice.wait=chocs[0]; alice.ate++; chocs.pop_front(); } if(bob.wait==0) { if(chocs.size()==0) break; else { bob.wait=chocs[chocs.size()-1]; bob.ate++; chocs.pop_back(); } } } cout<<alice.ate<<" "<<bob.ate<<endl; return 0; }
6
E
Exposition
There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than $k$ millimeters. The library has $n$ volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is $h_{i}$. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.
I solved this one in O(nlgn) time using a segment-tree and keeping track of minimum and maximum element in each segment. Adding a number is O(lgn) because we need to update minimum and maximum for the log2n segments containing that number. For each start point we query the tree to find the maximal endpoint. This is again O(lgn) and is done O(n) times so we have a total complexity of O(nlgn) fitting perfectly in the time limit.
[ "binary search", "data structures", "dsu", "trees", "two pointers" ]
1,900
null
8
D
Two Friends
Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it. Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path — a continuous curve, going through the shop, and having the cinema and the house as its ends. The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than $t_{1}$, and the distance covered by Bob should not differ from the shortest one by more than $t_{2}$. Find the maximum distance that Alan and Bob will cover together, discussing the film.
The main observation for this problem is the following: If Alan and/or Bob is at some point X and moves following some curve and travels distance d, then the point at which they finish can be ANY point on or inside the circle with center X and radius d. In other words: If you start at some point X and go to some point Y, you can do this on as long curve as we want(only not shorter then the distance(X, Y). Now, for convenience, lets say that T1 is the longest allowed path for Alan and T2 is the longest allowed path for Bob. These values are easily calculated: T1 = distance(cinema, shop) + distance(shop, home) + t1 T2 = distance(cinema, home) + t2Now, there are two cases. The first and trivial case is when distance(cinema, shop) + distance(shop, home) <= T2. In this case, it is OK for Bob to go to the shop with Alan. If they go to the shop together there is no need for them to ever split. So they go together all the way from the cinema to the shop and then from the shop to their home. In this case the solution is min(T1, T2) Why? (Hint: here the observation in the beginning is important).The second case is when Bob cannot go to the shop with Alan. We'll solve this case with binary search on the distance that they could cover together before splitting. Let's assume that the go to some point P together covering some distance x. After they split Bob goes home in straight line and Alan first goes to the shop in straight line and then goes home again in straight line. This circumstance forces three condition for the point P. Point P must be inside a circle with center 'cinema' and radius x. This follows directly from the main observation. x + distance(P, home) <= T2 - Bob must be able to go home in time. This condition means that P must be inside a circle with center home and radius max(0, T2 - x). x + distance(P, shop) + distance(shop, home) <= T1 - Alan must be able to go home in time. This condition means that P must be inside circle with center shop and radius max(0, T1 - x - distance(shop, home). Now we have three circles and if they intersect, then it's possible to choose point P in such a way that Alan and Bob will the together the first x meters of their journey.Now, the problem is to check if three circles intersect. I come up with easy solution for this problem. I haven't proven it correct, but it seem to work. I don't know if there is some standard algorithm for this problem. My idea is the following. Let the 3 circles be C1, C2 and C3. If C1 and C2 intersect they do it in one or two point. Now we check is some of these points is inside C3. If there is such point, then the 3 circles intersect, but if there is no such point, it doesn't necessarily mean thath the 3 circles doesn't intersect. We should try all permutations of the 3 circles. That is we first check C1 and C2 and the intersected points with C3, then C1 and C3 and the intersected points with C2, and so on.
[ "binary search", "geometry" ]
2,600
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <cstring> #include <cmath> #include <ctime> #include <complex> using namespace std; const double eps = 1e-10; const int DIM = 2; typedef complex<double> point; typedef pair<point, double> circle; double T1, T2; point cinema, shop, home; inline double dist(const point& a, const point& b) { return abs(a - b); } void readPoint(point& p) { double x, y; cin >> x >> y; p = point(x, y); } inline bool isIn(const circle& a, const circle& b) { double A = dist(a.first, b.first) + a.second; double B = b.second; return A < B + eps; } inline bool isInPoint(const point& p, const circle& c) { return dist(p, c.first) < c.second + eps; } inline bool doesIntersect(const circle& a, const circle& b) { return dist(a.first, b.first) < a.second + b.second + eps; } point getNewCoords(point e1prime, point e2prime, point P, point A) { double c1 = A.real() - P.real(); double c2 = A.imag() - P.imag(); double x = c1 * e1prime.real() + c2 * e2prime.real(); double y = c1 * e1prime.imag() + c2 * e2prime.imag(); return point(x, y); } point getOldCoors(point e1prime, point e2prime, point P, point A) { double a1 = A.real(); double a2 = A.imag(); double x = a1 * e1prime.real() + a2 * e1prime.imag(); double y = a1 * e2prime.real() + a2 * e2prime.imag(); x += P.real(); y += P.imag(); return point(x, y); } vector<point> getIntersectedPoints(const circle& C1, const circle& C2) { point P = C1.first; point e1prime = C2.first - C1.first; e1prime = e1prime / abs(e1prime); point e2prime = point(e1prime.imag(), -e1prime.real()); point A = getNewCoords(e1prime, e2prime, P, C1.first); point B = getNewCoords(e1prime, e2prime, P, C2.first); double R1 = C1.second * C1.second; double R2 = C2.second * C2.second; double b = B.real(); double x = (b * b + R1 - R2) / (2.0 * b); double Y = R1 - x * x; if (Y < 0.0) Y = 0.0; vector<point> ret; if (Y < eps) { ret.push_back(point(x, Y)); } else { ret.push_back(point(x, sqrt(Y))); ret.push_back(point(x, -sqrt(Y))); } for (int i = 0; i < int(ret.size()); ++i) { ret[i] = getOldCoors(e1prime, e2prime, P, ret[i]); } return ret; } bool my_comp(const circle& c1, const circle& c2) { if (c1.first.real() < c2.first.real()) return true; if (c1.first.real() > c2.first.real()) return false; if (c1.first.imag() < c2.first.imag()) return true; if (c1.first.imag() > c2.first.imag()) return false; if (c1.second < c2.second) return true; return false; } bool intersect3Circles(vector<circle>& circles) { sort(circles.begin(), circles.end(), my_comp); do { if (!doesIntersect(circles[0], circles[1])) { return false; } if (isIn(circles[0], circles[1])) { if (doesIntersect(circles[0], circles[2])) { return true; } else { return false; } } } while (next_permutation(circles.begin(), circles.end(), my_comp)); sort(circles.begin(), circles.end(), my_comp); do { vector<point> pts = getIntersectedPoints(circles[0], circles[1]); bool ok = false; for (int i = 0; i < int(pts.size()); ++i) { if (isInPoint(pts[i], circles[2])) { ok = true; break; } } if (ok) return true; } while(next_permutation(circles.begin(), circles.end(), my_comp)); return false; } bool check(double Q) { vector<circle> circles(3); circles[0] = circle(cinema, Q); circles[1] = circle(shop, max(0.0, T1 - dist(shop, home) - Q)); circles[2] = circle(home, max(0.0, T2 - Q)); return intersect3Circles(circles); } int main() { cout.setf(ios::fixed); cout.precision(9); double t1, t2; cin >> t1 >> t2; readPoint(cinema); readPoint(home); readPoint(shop); T2 = t2 + dist(cinema, home); T1 = t1 + dist(cinema, shop) + dist(shop, home); if (dist(cinema, shop) + dist(shop, home) < T2 + eps) { cout << min(T1, T2) << endl; return 0; } double L = 0.0; double R = min(T1, T2); check(1.000253); for (int step = 1; step <= 40; ++step) { double Q = (L + R) / 2.0; if (check(Q)) { L = Q; } else { R = Q; } } cout << (L + R) / 2.0 << endl; return 0; }
8
E
Beads
One Martian boy called Zorg wants to present a string of beads to his friend from the Earth — Masha. He knows that Masha likes two colours: blue and red, — and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if one unfastens it, one might notice that all the strings of beads in the shop are of the same length. Because of the peculiarities of the Martian eyesight, if Zorg sees one blue-and-red string of beads first, and then the other with red beads instead of blue ones, and blue — instead of red, he regards these two strings of beads as identical. In other words, Zorg regards as identical not only those strings of beads that can be derived from each other by the string turnover, but as well those that can be derived from each other by a mutual replacement of colours and/or by the string turnover. It is known that all Martians are very orderly, and if a Martian sees some amount of objects, he tries to put them in good order. Zorg thinks that a red bead is smaller than a blue one. Let's put 0 for a red bead, and 1 — for a blue one. From two strings the Martian puts earlier the string with a red bead in the $i$-th position, providing that the second string has a blue bead in the $i$-th position, and the first two beads $i - 1$ are identical. At first Zorg unfastens all the strings of beads, and puts them into small heaps so, that in each heap strings are identical, in his opinion. Then he sorts out the heaps and chooses the minimum string in each heap, in his opinion. He gives the unnecassary strings back to the shop assistant and says he doesn't need them any more. Then Zorg sorts out the remaining strings of beads and buys the string with index $k$. All these manupulations will take Zorg a lot of time, that's why he asks you to help and find the string of beads for Masha.
This is quite an interesting problem for me. We must find the k-th lexicographically smallest number from a subset of the numbers from 0 to 2^N(It is easier to increase K with one and consider the all zeroes and all ones case, too). The numbers which we want to count are those which are smaller or equal to their inverted number(flip zeroes and ones), their reversed number(read the bits of the number from right to left) and their reversed and inverted number.Let's call a prefix the first half of the numbers, i.e. when only the first N/2 bits are set. Since N <= 50, there are at most 2 ^ 25 such numbers. Also we will only consider numbers with 0 at the first bit. If it is 1, then the inverse number will be smaller, so there are at most 2^24 prefixes. Now if we have some prefix, using dynamic programming we will see in how many ways can we finish it to a real number. The state of the dp is: (int pos, bool less, bool lessInv) and dp[pos][less][lessInv] is the number of ways to finish the number if we have to choose the pos-th bit now. less shows if so far we are less then or equal to the reversed number and lessInv shows if so far we are less then or equal to the inverted and reversed number. Using the dp we could easily find the k-th number.There is one final note. The DP here is run for every possible prefix and the prefixes could be up to 2^24. Every time we clear the DP table before running it. This makes the solution slow even for the 5 seconds time limit. There is one more observation which makes the solution run in time. We iterate the prefixes in order, that is in each step newprefix = oldprefix + 1. In this case only the last few bits of the prefix are changed. The other part of the prefix remains the same and there is no need to clear the whole DP table, only the parts that changed due to changing the last few bits. This is left for exercise.
[ "dp", "graphs" ]
2,600
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <cstring> #include <cmath> #include <ctime> using namespace std; const int MAXN = 50; typedef long long ll; int n, nPrefix; ll rem; int s[MAXN]; ll dp[MAXN + 1][2][2]; ll f(int pos, int less, int lessRev) { if (dp[pos][less][lessRev] != -1) return dp[pos][less][lessRev]; if (pos >= n) { if (less && lessRev) { dp[pos][less][lessRev] = 1; return 1; } else { dp[pos][less][lessRev] = 0; return 0; } } ll ret = 0; for (int i = 0; i <= 1; ++i) { int nextLess = less; int nextLessRev = lessRev; if (i > s[n - 1 - pos]) { nextLess = 1; } else if (i < s[n - 1 - pos]) { nextLess = 0; } if (1 - i > s[n - 1 - pos]) { nextLessRev = 1; } if (1 - i < s[n - 1 - pos]) { nextLessRev = 0; } ret += f(pos + 1, nextLess, nextLessRev); } dp[pos][less][lessRev] = ret; return ret; } int main() { cin >> n >> rem; ++rem; nPrefix = n / 2 + n % 2; bool found = false; int prefix; memset(dp, -1, sizeof dp); memset(s, 0, sizeof s); for (prefix = 0; prefix < (1 << nPrefix); ++prefix) { if (prefix > 0) { int i = nPrefix - 1; while (i >= 0) { if (s[i] == 0) { s[i] = 1; break; } s[i] = 0; --i; } for (int j = n - nPrefix; j <= n - 1 - i; ++j) { dp[j][0][0] = -1; dp[j][0][1] = -1; dp[j][1][0] = -1; dp[j][1][1] = -1; } } int firstPos = nPrefix; int less = 1; int lessRev = 1; if (n % 2 == 1 && s[nPrefix - 1] == 1) lessRev = 0; ll temp = f(firstPos, less, lessRev); if (temp < rem) { rem -= temp; } else { found = true; break; } } if (!found) { cout << "-1" << endl; return 0; } int less = 1, lessRev = 1; if (n % 2 == 1 && s[nPrefix - 1] == 1) lessRev = 0; for (int pos = nPrefix; pos < n; ++pos) { int nextLess = less; int nextLessRev = lessRev; if (0 < s[n - 1 - pos]) nextLess = 0; if (1 > s[n - 1 - pos]) nextLessRev = 1; ll temp = f(pos + 1, nextLess, nextLessRev); if (temp >= rem) { s[pos] = 0; less = nextLess; lessRev = nextLessRev; continue; } rem -= temp; s[pos] = 1; if (1 > s[n - 1 - pos]) less = 1; if (0 < s[n - 1 - pos]) lessRev = 0; } for (int i = 0; i < n; ++i) { cout << s[i]; } cout << endl; return 0; }
9
A
Die Roll
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place. But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams. Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania. It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
If the maximum of Yakko's and Wakko's points is a, then Dot will win, if she has not less than a points. So the probability of her win is (6 - (a-1)) / 6. Since there are only 6 values for a, you can simply hardcode the answers.
[ "math", "probabilities" ]
800
null
9
B
Running Student
And again a misfortune fell on Poor Student. He is being late for an exam. Having rushed to a bus stop that is in point $(0, 0)$, he got on a minibus and they drove along a straight line, parallel to axis $OX$, in the direction of increasing $x$. Poor Student knows the following: - during one run the minibus makes $n$ stops, the $i$-th stop is in point $(x_{i}, 0)$ - coordinates of all the stops are different - the minibus drives at a constant speed, equal to $v_{b}$ - it can be assumed the passengers get on and off the minibus at a bus stop momentarily - Student can get off the minibus only at a bus stop - Student will have to get off the minibus at a terminal stop, if he does not get off earlier - the University, where the exam will be held, is in point $(x_{u}, y_{u})$ - Student can run from a bus stop to the University at a constant speed $v_{s}$ as long as needed - a distance between two points can be calculated according to the following formula: $\sqrt{(x_{2}-x_{1})^{2}+(y_{2}-y_{1})^{2}}$ - Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.
It is simple to calculate the time $ti$ that the Student will need, if he gets off the bus at the i-th stop: $ti = bi + si$, where $bi = xi / vb$ is the time he will drive on the bus, and $s_{i}=\sqrt{(x_{i}-x_{u})^{2}+y_{u}^{2}}/v_{s}$ is the time he will need to get from the i-th stop to the University. We need to choose indices with minimal possible $ti$, and among them - the index with minimal possible $si$, that is, with maximal $bi$, that is (since the coordinates of bus stops are already ordered) with maximal i.Note that due to precision issues, you should be careful when you compare $ti$: the condition $ti$ = $tj$ should be written in the form $|ti - tj| < \epsilon $ for some small $ \epsilon $.
[ "brute force", "geometry", "implementation" ]
1,200
null
9
C
Hexadecimal's Numbers
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of $n$ different natural numbers from 1 to $n$ to obtain total control over her energy. But his plan failed. The reason for this was very simple: Hexadecimal didn't perceive any information, apart from numbers written in binary format. This means that if a number in a decimal representation contained characters apart from 0 and 1, it was not stored in the memory. Now Megabyte wants to know, how many numbers were loaded successfully.
Brute force solution, when you try each number from 1 to n, will not fit into the time limit.Note, however, that all good numbers have at most 10 digits, and each of the digits is 0 or 1. That is, there are at most $210$ binary strings to check. Each of these strings is a number from 1 to $210 - 1$ in binary representation. So the algorithm is the following: for each number from 1 to $210 - 1$ write its binary representation, read it as if it was decimal representation and compare the result to n.
[ "brute force", "implementation", "math" ]
1,200
null
9
D
How many trees?
In one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong — the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure — and then terrible Game Cubes fall down on the city, bringing death to those modules, who cannot win the game... For sure, as guard Bob appeared in Mainframe many modules stopped fearing Game Cubes. Because Bob (as he is alive yet) has never been defeated by User, and he always meddles with Game Cubes, because he is programmed to this. However, unpleasant situations can happen, when a Game Cube falls down on Lost Angles. Because there lives a nasty virus — Hexadecimal, who is... mmm... very strange. And she likes to play very much. So, willy-nilly, Bob has to play with her first, and then with User. This time Hexadecimal invented the following entertainment: Bob has to leap over binary search trees with $n$ nodes. We should remind you that a binary search tree is a binary tree, each node has a distinct key, for each node the following is true: the left sub-tree of a node contains only nodes with keys less than the node's key, the right sub-tree of a node contains only nodes with keys greater than the node's key. All the keys are different positive integer numbers from $1$ to $n$. Each node of such a tree can have up to two children, or have no children at all (in the case when a node is a leaf). In Hexadecimal's game all the trees are different, but the height of each is not lower than $h$. In this problem «height» stands for the maximum amount of nodes on the way from the root to the remotest leaf, the root node and the leaf itself included. When Bob leaps over a tree, it disappears. Bob gets the access to a Cube, when there are no trees left. He knows how many trees he will have to leap over in the worst case. And you?
Denote by $tnh$ the number of binary search trees on n nodes with height equal to h. We will derive a recurrent formula for $tnh$. For the base case note that $t00 = 1$ (empty tree), and $ti0 = t0i = 0$ if i>0.Now take any binary search tree on n nodes with height equal to h. Let m be the number written at its root, $1 \le m \le n$. The left subtree is a binary search tree on m-1 nodes, and the right subtree is a binary search tree on n-m nodes. The maximal of their heights must be equal to h-1. Consider 2 subcases:1. The height of the left subtree is equal to h-1. There are $tm - 1, h - 1$ such trees. The right subtree can have any height from 0 to h-1, so there are $\textstyle\sum_{i=0}^{h-1}t_{n-m,i}$ such trees. Since we can choose left and right subtrees independently, we have $\begin{array}{c}{{\displaystyle F_{m-1,h-1}\displaystyle\sum_{n=0}^{h-1}\,t_{n-m,i}}}\end{array}$ variants in this case.2. The height of the left subtree is less than h-1. There are $\textstyle\sum_{i=0}^{h-2}t_{m-1,i}$ such trees, and the right subtree must have height exactly h-1, which gives us totally $\begin{array}{c}{{\displaystyle F_{n-m,h-1}\sum_{n=1}^{h-2}\bigg(n_{m-1,i}}}\end{array}$ variants.So the recurrent formula is the following: $t_{n h}=\sum_{m=1}^{n}\left(t_{m-1,h-1}\sum_{i=0}^{h-1}t_{n-m,i}+t_{n-m,h-1}\sum_{i=0}^{h-2}t_{m-1,i}\right)$.All the values $tnh$ can be calculated by dynamic programming. The answer, then, is $\textstyle\sum_{i=h}^{n}t_{n i}$.
[ "combinatorics", "divide and conquer", "dp" ]
1,900
null
9
E
Interestring graph and Apples
Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{n}, y_{n})$, where $x_{i} ≤ y_{i}$, is lexicographically smaller than the set $(u_{1}, v_{1}), (u_{2}, v_{2}), ..., (u_{n}, v_{n})$, where $u_{i} ≤ v_{i}$, provided that the sequence of integers $x_{1}, y_{1}, x_{2}, y_{2}, ..., x_{n}, y_{n}$ is lexicographically smaller than the sequence $u_{1}, v_{1}, u_{2}, v_{2}, ..., u_{n}, v_{n}$. If you do not cope, Hexadecimal will eat you. ...eat you alive.
Interesting graph and Apples The funny ring consists of n vertices and n edges. If there is another edge except for these n, then the vertices it connects belong to more than one cycle. So, an interesting graph is just a funny ring. A graph is a funny ring if and only if the following conditions hold:A1. The degree of each vertex equals 2.A2. The graph is connected. Now let's figure out when a graph is not yet a funny ring, but can be transformed into a funny ring by adding edges. There are obvious necessary conditions:B1. m < n.B2. There are no cycles.B3. The degree of each vertex is not more than 2. Let's add edges so that these conditions were preserved, and the sequence of edges was lexicographically minimal. So, we add an edge (i,j) such that:1. The degrees of i and j are less than 2. (Otherwise we would break B3).2. i and j belong to different connected components. (Otherwise we would break B2).3. The pair (i,j) is lexicographically minimal. Let's see what we have when we can't add edges anymore. Since there are no cycles, each connected component is a tree, and therefore has at least one vertex with degree less than 2. If there are two connected components, then they could be connected by an edge without breaking B1-B3. So the graph is connected, has no cycles, and the degree of each vertex is not more than 2. This means that the obtained graph is just a walk and we can connect its end points to obtain a funny ring. To summarize, the algorithm is the following: 1. Check if A1-A2 hold. If yes, output "YES" and 0. 2. Check if B1-B3 hold. If no, output "NO". 3. Output "YES" and n-m. 4. Add edges as described. When the edge (i,j) is added, output "i j". 5. Find the only vertices i and j with degree less than 2 (they can be equal if n=1). Output "i j".
[ "dfs and similar", "dsu", "graphs" ]
2,300
null
13
A
Numbers
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18. Now he wonders what is an average value of sum of digits of the number $A$ written in all bases from $2$ to $A - 1$. Note that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10.
It is sufficient to iterate over all bases from 2 to A-2 and find the sum of digits in them. Then one should find the greatest common divisor of found sum and A-2 (which is equal to number of bases in which we found the sums). The numerator of the answer is equal to founded sum divided by this GCD and the denominator is equal to A-2 divided by this GCD.The complexity is O(A).
[ "implementation", "math" ]
1,000
null
13
B
Letter A
Little Petya learns how to write. The teacher gave pupils the task to write the letter $A$ on the sheet of paper. It is required to check whether Petya really had written the letter $A$. You are given three segments on the plane. They form the letter $A$ if the following conditions hold: - Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments. - The angle between the first and the second segments is greater than $0$ and do not exceed $90$ degrees. - The third segment divides each of the first two segments in proportion not less than $1 / 4$ (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than $1 / 4$).
This problem appeared to be quite unpleasant to code, but all what one need to do is to check whether all three statements are true. It is recommended to perform all computations using integer arithmetics and to use scalar and vector product instead of computing cosines of angles or angles itself.
[ "geometry", "implementation" ]
2,000
null
13
C
Sequence
Little Petya likes to play very much. And most of all he likes to play the following game: He is given a sequence of $N$ integer numbers. At each step it is allowed to increase the value of any number by $1$ or to decrease it by $1$. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help. The sequence $a$ is called non-decreasing if $a_{1} ≤ a_{2} ≤ ... ≤ a_{N}$ holds, where $N$ is the length of the sequence.
Note, that there exists a non-decreasing sequence, which can be obtained from the given sequence using minimal number of moves and in which all elements are equal to some element from the initial sequence (i.e. which consists only from the numbers from the initial sequence).Suppose {ai} is the initial sequence, {bi} is the same sequence, but in which all elements are distinct and they are sorted from smallest to greatest. Let f(i,j) be the minimal number of moves required to obtain the sequence in which the first i elements are non-decreasing and i-th element is at most bj. In that case the answer to the problem will be equals to f(n,k), where n is the length of {ai} and k is the length of {bi}. We will compute f(i,j) using the following recurrences:f(1,1)=|a1-b1|f(1,j)=min{|a1-bj|,f(1,j-1)}, j>1f(i,1)=|ai-b1|+f(i-1,1), i>1f(i,j)=min{f(i,j-1),f(i-1,j)+|ai-bj|}, i>1, j>1The complexity is O(N2). To avoid memory limit one should note that to compute f(i,*) you only need to know f(i-1,*) and the part of i-th row which is already computed.
[ "dp", "sortings" ]
2,200
null
13
D
Triangles
Little Petya likes to draw. He drew $N$ red and $M$ blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.
We will solve the problem using the following algorithm:Fix some red point.Find the number of triangles with vertices in the red points which don't contain any blue points inside and which have the fixed red point as one of the vertices.Remove the fixed red point and go back to statement 1, if there remain any red point.The first and third statements are obvious, so the main part of the solution is statement 2.Suppose the red point A is fixed (in the first statement). Also suppose we have all other points which are still not removed (blue and red together) sorted by angle around the point A. We will iterate over all red points B, which will be the second vertice of triangle. Now, we need to find the number of triangles with vertices in red points which have points A and B as two vertices and which don't contain any blue point inside.To solve this problem we will iterate over all unremoved points C in the increasing order of angle ABC starting from the point after the point B (in the same order). To avoid double counting we will stop when the angle between vectors AB and AC become greater than 180 degrees or when we reach the point which was already considered. Then we will perform such actions:If C is red then we will check whether there are blue points inside triangle ABC and if not - we will increase the answer by 1. Note, that to perform this check we don't need to iterate over all blue points. It is sufficient to maintain such point D from the ones which we have already seen for which the angle ABD is the smallest possible. If D doesn't lies inside the triangle ABC, then there is no blue point which lies inside it.If C is blue, then we will compare the angle ABC with ABD and if ABC is smaller, we will replace old D with C.Note, that after choosing new B we consider that there is no point D and there will be no blue points inside triangles ABC until we reach the first blue point.The complexity is O(N2(N+M)).
[ "dp", "geometry" ]
2,600
null
13
E
Holes
Little Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules: There are $N$ holes located in a single row and numbered from left to right with numbers from 1 to $N$. Each hole has it's own power (hole number $i$ has the power $a_{i}$). If you throw a ball into hole $i$ it will immediately jump to hole $i + a_{i}$, then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the $M$ moves the player can perform one of two actions: - Set the power of the hole $a$ to value $b$. - Throw a ball into the hole $a$ and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.
Let's divide all row into blocks of length K=sqrt(N) of consecutive holes. If N is not a complete square, then we will take K=sqrt(N) rounded down. For each hole we will maintain not only it's power (let's call it power[i]), but also the number of the first hole which belongs to other block and which can be reached from the current one with sequence of jumps (let's call it next[i]). Also, for each hole we will maintain the number of jumps required to reach the hole next[i] from the current one (let's call it count[i]). We will consider that there is a fictious hole, which lies after the hole N and it belongs to it's own block.To answer the query of the first type (when the ball is thrown) we will jump from the hole i to hole next[i] and so on, until we reach the fictious hole. Each time we will add count[i] to the answer. We will jump not more than N/K times.To maintain the query of the seqond type (when the power of hole i is changed) we will change power[i], next[i] and count[i]. Then for each hole which belongs to the same block as i and has smaller number than i we will update next[i] and power[i] in decreasing order of number of the hole. We will perform not more than K updates.The complexity is O(Nsqrt(N)).
[ "data structures", "dsu" ]
2,700
null
14
A
Letter
A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with $n$ rows and $m$ columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.
To find the smallest rectangle containing the picture, iterate through the pairs (i,j) such that the j-th symbol in i-th line is '*'; find the minimum and maximum values of i and j from these pairs. The rectangle to output is $[imin, imax] \times [jmin, jmax]$.
[ "implementation" ]
800
null
14
B
Young Photographer
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position $x_{0}$ of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals $n$. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position $a_{1}$ to position $b_{1}$, the second — from $a_{2}$ to $b_{2}$ What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.
First we find the intersection of all segments. To do this, denote by m the rightmost of left ends of the segments and denote by M the leftmost of right ends of the segments. The intersection of the segments is [m,M] (or empty set if m>M). Now determine the nearest point from this segment. If $x0 < m$, it's $m$, and the answer is $m - x0$. If $x0 > M$, it's $M$, and the answer is $x0 - M$. If $x_{0}\in[m,M]$, it's $x0$, and the answer is 0. If m>M, then the answer is -1.
[ "implementation" ]
1,000
null
14
C
Four Segments
Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the program detects if the four given segments form a rectangle of a positive area and with sides parallel to coordinate axes. As Alex does badly at school and can't write this program by himself, he asks you to help him.
There must be many ways to solve this problem. The following one seems quite easy to code.First count the number of distinct points among segments' ends. If it's not equal to 4, the segments can't form a rectangle and we output "NO". Then calculate the minimum and maximum coordinates of the 4 points: $xmin$, $xmax$, $ymin$, $ymax$. If $xmin = xmax$ or $ymin = ymax$, then even if the segments form a rectangle, it has zero area, so we also output "NO" in this case.Now if the segments indeed form a rectangle, we know the coordinates of its vertices - $(xmin, ymin)$, $(xmin, ymax)$, $(xmax, ymin)$ and $(xmax, ymax)$. We just check that every side of this rectangle appears in the input. If it is the case, we output "YES", otherwise we output "NO".
[ "brute force", "constructive algorithms", "geometry", "implementation", "math" ]
1,700
null
14
D
Two Paths
As you know, Bob's brother lives in Flatland. In Flatland there are $n$ cities, connected by $n - 1$ two-way roads. The cities are numbered from 1 to $n$. You can get from one city to another moving along the roads. The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities). It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.
Take any pair of non-intersecting paths. Since Flatland is connected, there must be a third path, connecting these two. Remove a road from the third path. Then Flatland is divided into two components - one containing the first path, and the other containing the second path. This observation suggests us the algorithm: iterate over the roads; for each road remove it, find the longest path in both connected components and multiply the lengths of these paths. The longest path in a tree can be found by depth first search from each leaf.
[ "dfs and similar", "dp", "graphs", "shortest paths", "trees", "two pointers" ]
1,900
null
14
E
Camels
Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with $t$ humps, representing them as polylines in the plane. Each polyline consists of $n$ vertices with coordinates $(x_{1}, y_{1})$, $(x_{2}, y_{2})$, ..., $(x_{n}, y_{n})$. The first vertex has a coordinate $x_{1} = 1$, the second — $x_{2} = 2$, etc. Coordinates $y_{i}$ might be any, but should satisfy the following conditions: - there should be $t$ humps precisely, i.e. such indexes $j$ ($2 ≤ j ≤ n - 1$), so that $y_{j - 1} < y_{j} > y_{j + 1}$, - there should be precisely $t - 1$ such indexes $j$ ($2 ≤ j ≤ n - 1$), so that $y_{j - 1} > y_{j} < y_{j + 1}$, - no segment of a polyline should be parallel to the $Ox$-axis, - all $y_{i}$ are integers between 1 and 4. For a series of his drawings of camels with $t$ humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with $t$ humps for a given number $n$.
Let us call an index j such that $yj - 1 > yj < yj + 1$ a cavity. Also, we'll call humps and cavities by the common word break. Then there must be exactly $T = 2t - 1$ breaks, and the first one must be a hump.Denote by $fnth$ the number of ways in which a camel with $t$ breaks, ending at the point (n,h), can be extended to the end (the vertical $xN = N$) so that the total number of breaks was equal to T. Note that:1. $fNTh = 1$, if h=1,2,3,4. (We have already finished the camel and it has T breaks)2. $fNth = 0$, if $0 \le t < T, h = 1, 2, 3, 4$. (We have already finished the camel, but it has less than T breaks)3. $fn, T + 1, h = 0$, if $1 \le n \le N$, $h = 1, 2, 3, 4$. (The camel has already more than T breaks). Now we find the recurrent formula for $fnth$. Suppose that $t$ is even. Then the last break was a cavity, and we are moving up currently. We can continue moving up, then the number of breaks stays the same, and we move to one of the points $(n + 1, h + 1), (n + 1, h + 2), ..., (n + 1, 4)$. Or we can move down, then the number of breaks increases by 1, and we move to one of the points $(n + 1, h - 1), (n + 1, h - 2), ..., (n + 1, 1)$. This gives us the formula$f_{n t h}=\sum_{H=h+1}^{4}f_{n+1,t,H}+\sum_{H=1}^{h-1}f_{n+1,t+1,H}$.If $t$ is odd, then the last break was a hump, and similar reasoning leads to the formula$f_{n t h}=\sum_{H=h+1}^{4}f_{n+1,t+1,H}+\sum_{H=1}^{h-1}f_{n+1,t,H}$.We can calculate $fnth$ by dynamic programming. Consider now the point $(2, h)$ on a camel. There are h-1 ways to get to this point (starting from points $(1, 1), ..., (1, h - 1)$), and $f2, 0, h$ ways to extend the camel to the end. So the answer to the problem is $\textstyle\sum_{h=1}^{4}(h-1)f_{2,0,h}$.
[ "dp" ]
1,900
null
17
A
Noldbach problem
Nick is interested in prime numbers. Once he read about \underline{Goldbach problem}. It states that every even integer greater than $2$ can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it \underline{Noldbach problem}. Since Nick is interested only in prime numbers, Noldbach problem states that at least $k$ prime numbers from $2$ to $n$ inclusively can be expressed as the sum of three integer numbers: two neighboring prime numbers and $1$. For example, 19 = 7 + 11 + 1, or 13 = 5 + 7 + 1. Two prime numbers are called neighboring if there are no other prime numbers between them. You are to help Nick, and find out if he is right or wrong.
To solve this problem you were to find prime numbers in range $[2..N]$. The constraints were pretty small, so you could do that in any way - using the Sieve of Eratosthenes or simply looping over all possible divisors of a number.Take every pair of neighboring prime numbers and check if their sum increased by $1$ is a prime number too. Count the number of these pairs, compare it to $K$ and output the result.
[ "brute force", "math", "number theory" ]
1,000
null
17
B
Hierarchy
Nick's company employed $n$ people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are $m$ applications written in the following form: \underline{«employee $a_{i}$ is ready to become a supervisor of employee $b_{i}$ at extra cost $c_{i}$»}. The qualification $q_{j}$ of each employee is known, and for each application the following is true: $q_{ai} > q_{bi}$. Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.
Note that if employee, except one, has exactly one supervisor, then our hierarchy will be tree-like for sure.For each employee consider all applications in which he appears as a subordinate. If for more than one employee there are no such applications at all, it's obvious that $- 1$ is the answer. In other case, for each employee find such an application with minimal cost and add these costs to get the answer.Alternatively, you could use Kruskal's algorithm finding a minimum spanning tree for a graph. But you should be careful so that you don't assign the second supervisor to some employee.And yes, the employees' qualifications weren't actually needed to solve this problem :)
[ "dfs and similar", "dsu", "greedy", "shortest paths" ]
1,500
null
17
C
Balance
Nick likes strings very much, he likes to rotate them, sort them, rearrange characters within a string... Once he wrote a random string of characters a, b, c on a piece of paper and began to perform the following operations: - to take two adjacent characters and replace the second character with the first one, - to take two adjacent characters and replace the first character with the second one To understand these actions better, let's take a look at a string «abc». All of the following strings can be obtained by performing one of the described operations on «abc»: «bbc», «abb», «acc». Let's denote the \underline{frequency of a character} for each of the characters a, b and c as the number of occurrences of this character in the string. For example, for string «abc»: |$a$| = 1, |$b$| = 1, |$c$| = 1, and for string «bbc»: |$a$| = 0, |$b$| = 2, |$c$| = 1. While performing the described operations, Nick sometimes got \underline{balanced strings}. Let's say that a string is balanced, if the frequencies of each character differ by at most 1. That is $ - 1 ≤ |a| - |b| ≤ 1$, $ - 1 ≤ |a| - |c| ≤ 1$ и $ - 1 ≤ |b| - |c| ≤ 1$. Would you help Nick find the number of different balanced strings that can be obtained by performing the operations described above, perhaps multiple times, on the given string $s$. This number should be calculated modulo $51123987$.
Consider the input string $A$ of length $n$. Let's perform some operations from the problem statement on this string; suppose we obtained some string $B$. Let compression of string $X$ be a string $X'$ obtained from $X$ by replacing all consecutive equal letters with one such letter. For example, if $S = "aabcccbbaa"$, then its compression $S' = "abcba"$.Now, consider compressions of strings $A$ and $B$ - $A'$ and $B'$. It can be proven that if $B$ can be obtained from some string $A$ using some number of operations from the problem statement, then $B'$ is a subsequence of $A'$, and vice versa - if for any strings $A$ and $B$ of equal length $B'$ is a subsequence of $A'$, then string $B$ can be obtained from string $A$ using some number of operations.Intuitively you can understand it in this manner: suppose we use some letter $a$ from position $i$ of $A$ in order to put letter $a$ at positions $j..k$ of $B$ (again, using problem statement operations). Then we can't use letters at positions $1..i - 1$ of string $A$ in order to influence positions $k + 1..n$ of string $B$ in any way; also, we can't use letters at positions $i + 1..n$ of string $A$ in order to influence positions $1..j - 1$ of string $B$.Now we have some basis for our solution, which will use dynamic programming. We'll form string $B$ letter by letter, considering the fact that $B'$ should still be a subsequence of $A'$ (that is, we'll search for $B'$ in $A'$ while forming $B$). For this matter we'll keep some position $i$ in string $A'$ denoting where we stopped searching $B'$ in $A'$ at the moment, and three variables $kA$, $kB$, $kC$, denoting the frequences of characters $a$, $b$, $c$ respectively in string $B$. Here are the transitions of our DP:1) The next character of string $B$ is $a$. Then we may go from the state $(i, kA, kB, kC)$ to the state $(nexti, 'a', kA + 1, kB, kC)$.2) The next character of string $B$ is $b$. Then we may go from the state $(i, kA, kB, kC)$ to the state $(nexti, 'b', kA, kB + 1, kC)$.3) The next character of string $B$ is $c$. Then we may go from the state $(i, kA, kB, kC)$ to the state $(nexti, 'c', kA, kB, kC + 1)$.Where $nexti, x$ is equal to minimal $j$ such that $j \ge i$ and $A'j = x$ (that is, the nearest occurrence of character $x$ in $A'$, starting from position $i$). Clearly, if in some case $nexti, x$ is undefined, then the corresponding transition is impossible.Having calculated $f(i, kA, kB, kC)$, it's easy to find the answer: $\textstyle\sum_{i=1\ldots1A^{\prime}!}f(i,k A,k B,k C)$ for all triples $kA$, $kB$, $kC$ for which the balance condition is fulfilled.Such a solution exceeds time and memory limits. Note that if string $B$ is going to be balanced, then $kA, kB, kC \le (n + 2) / 3$, so the number of states can be reduced up to 27 times. But it's also possible to decrease memory usage much storing matrix $f$ by layers, where each layer is given by some value of $kA$ (or $kB$ or $kC$). It's possible since the value of $kA$ is increased either by $0$ or by $1$ in each transition.The overall complexity is $O(N4)$ with a quite small constant.
[ "dp" ]
2,500
null
17
D
Notepad
Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base $b$ caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length $n$ without leading zeros in this number system. Each page in Nick's notepad has enough space for $c$ numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number $0$ as he has unpleasant memories about zero divide. Would you help Nick find out how many numbers will be written on the last page.
The answer to the problem is $bn - 1 * (b - 1)$ mod $c$. The main thing you should be able to do in this problem - count the value of $AB$ mod $C$ for some long numbers $A$ and $B$ and a short number $C$. Simple exponentiation by squaring exceeds time limit since to converse of $B$ to binary you need about $O(|B|2)$ operations, where $|B|$ is the number of digits in decimal representation of number $B$.The first thing to do is to transform $A$ to $A$ mod $C$. It isn't difficult to understand that this transformation doesn't change the answer.Let's represent $C$ as $C = p1k1p2k2...pmkm$, where $pi$ are different prime numbers.Calculate $ti = AB$ mod $piki$ for all $i$ in the following way. There are two possible cases:1) $A$ is not divisible by $pi$: then $A$ and $pi$ are coprime, and you can use Euler's theorem: $AB' = AB$ (mod $C$), where $B' = B$ mod $ \phi (C)$ and $ \phi (C)$ is Euler's totient function;2) $A$ is divisible by $pi$: then if $B \ge ki$ then $ti = AB$ mod $piki = 0$, and if $B < ki$ then you can calculate $ti$ in any way since B is very small.Since all $piki$ are pairwise coprime you may use chinese remainder theorem to obtain the answer.You can also use Euler's theorem directly. Note that if for some $B1, B2 \ge 29$ you know that $|B1 - B2|$ mod $ \phi (C) = 0$, then all $ti$ for them will be the same ($29$ is the maximal possible value of $ki$). Using that you may reduce $B$ so that it becomes relatively small and obtain the answer using exponentiation by squaring.There is another solution used by many contestants. Represent $B$ as $B = d0 + 10d1 + 102d2 + ... + 10mdm$, where $0 \le di \le 9$ (in fact $di$ is the $i$-th digit of $B$ counting from the last). Since $ax + y = ax \cdot ay$, you know that $AB = Ad0 \cdot A10d1 \cdot ... \cdot A10mdm$. The values of $ui = A10i$ can be obtained by successive exponentiation (that is, $ui = ui - 110$); if you have $A10i$, it's easy to get $A10idi = uidi$. The answer is the product above (modulo $C$, of course).
[ "number theory" ]
2,400
null
17
E
Palisection
In an English class Nick had nothing to do at all, and remembered about wonderful strings called \underline{palindromes}. We should remind you that a string is called a palindrome if it can be read the same way both from left to right and from right to left. Here are examples of such strings: «eye», «pop», «level», «aba», «deed», «racecar», «rotor», «madam». Nick started to look carefully for all palindromes in the text that they were reading in the class. For each occurrence of each palindrome in the text he wrote a pair — the position of the beginning and the position of the ending of this occurrence in the text. Nick called each occurrence of each palindrome he found in the text \underline{subpalindrome}. When he found all the subpalindromes, he decided to find out how many different pairs among these subpalindromes cross. Two subpalindromes cross if they cover common positions in the text. No palindrome can cross itself. Let's look at the actions, performed by Nick, by the example of text «babb». At first he wrote out all subpalindromes: \begin{center} • «b» — $1..1$ \end{center} \begin{center} • «bab» — $1..3$ \end{center} \begin{center} • «a» — $2..2$ \end{center} \begin{center} • «b» — $3..3$ \end{center} \begin{center} • «bb» — $3..4$ \end{center} \begin{center} • «b» — $4..4$ \end{center} Then Nick counted the amount of different pairs among these subpalindromes that cross. These pairs were six: \begin{center} 1. $1..1$ cross with $1..3$ \end{center} \begin{center} 2. $1..3$ cross with $2..2$ \end{center} \begin{center} 3. $1..3$ cross with $3..3$ \end{center} \begin{center} 4. $1..3$ cross with $3..4$ \end{center} \begin{center} 5. $3..3$ cross with $3..4$ \end{center} \begin{center} 6. $3..4$ cross with $4..4$ \end{center} Since it's very exhausting to perform all the described actions manually, Nick asked you to help him and write a program that can find out the amount of different subpalindrome pairs that cross. Two subpalindrome pairs are regarded as different if one of the pairs contains a subpalindrome that the other does not.
The first thing to do is to find all subpalindromes in the given string. For this you may use a beautiful algorithm described for example here. In short, this algorithm find the maximal length of a subpalindrome with its center either at position $i$ of the string or between positions $i$ and $i + 1$ for each possible placement of the center.For example, suppose that the maximal subpalindrome length with center at position $i$ is $5$; it means that there are three subpalindromes with center at $i$, with lengths $1$ ($i..i$), $3$ ($i - 1..i + 1$) and $5$ ($i - 2..i + 2$). In general, all starting and finishing positions of subpalindromes with a fixed center lie on some interval of positions, which is pretty easy to find.Let's find for each position $i$ the value of $starti$, which is equal to the number of subpalindromes starting at position $i$. All these values can be found in linear time. Let's create an auxiliary array $ai$. If after processing a position in the string some new pack of subpalindromes was found and they start at positions $i..j$, then increase the value of $ai$ by $1$, and decrease the value of $aj + 1$ by $1$. Now $s t a r t_{i}=\sum_{k=1\ldots i}a_{i}$. Proving this fact is left as an exercise to the reader :)In a similar way it's possible to calculate $finishi$, which is equal to the number of subpalindromes finishing at position $i$.Since it's easy to count the total number of subpalindromes, let's find the number of non-intersecting pairs of subpalindromes and subtract this number from the total number of pairs to obtain the answer. Note that if two subpalindromes don't intersect then one of them lies strictly to the left of the other one in the string. Then, the number of non-intersecting pairs of subpalindromes is equal to: $\textstyle\sum_{i=1\ldots n}(s t a r t_{i}\cdot\sum_{i=1,i-1}f i n i s h_{j})$This can be calculated in linear time if the value of $\sum_{j=1..i-1}f i n i s h_{j}$ is recalculated by addition of $finishi$ before moving from position $i$ to position $i + 1$.The overall complexity of the algorithm is $O(N)$.
[ "strings" ]
2,900
null
19
A
World Football Cup
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: - the final tournament features $n$ teams ($n$ is always even) - the first $n / 2$ teams (according to the standings) come through to the knockout stage - the standings are made on the following principle: for a victory a team gets 3 points, for a draw — 1 point, for a defeat — 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place — in decreasing order of the difference between scored and missed goals; in the third place — in the decreasing order of scored goals - it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.
I think is' just a problem about writing code quickly and correctly.Just follow the statement. if you use c++ STL will make you life easier
[ "implementation" ]
1,400
null
19
B
Checkout Assistant
Bob came to a cash & carry store, put $n$ items into his trolley, and went to the checkout counter to pay. Each item is described by its price $c_{i}$ and time $t_{i}$ in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. To steal one item Bob needs exactly 1 second. What is the minimum amount of money that Bob will have to pay to the checkout assistant? Remember, please, that it is Bob, who determines the order of items for the checkout assistant.
First,for every i increase ti by 1..then you will see that statement require sum of t of the items bigger or equal to n..and their sum of c should be minimal..so it's just a 0-1 knapsack problem.
[ "dp" ]
1,900
null
19
C
Deletion of Repeats
Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length $x$ is such a substring of length $2x$, that its first half coincides character by character with its second half. Bob started deleting all the repeats from the string. He does it as follows: while it's possible, Bob takes the shortest repeat, if it is not unique, he takes the leftmost one, and deletes its left half and everything that is to the left of this repeat. You're given the string seen by Bob. Find out, what it will look like after Bob deletes all the repeats in the way described above.
First let's generate all repeats.In a repeat,the first number and the middle number must be the same, so we just look at all pair of postion which have same number..Thank to the statement..There are at most O(10N) such pair..And use suffix array to check if each pair can build a repeat...Then just sort all the interval and go through then to get the answer...http://en.wikipedia.org/wiki/Suffix_arraymaybe you think suffix array is hard to code..you can use hash and binary search to do the same..
[ "greedy", "hashing", "string suffix structures" ]
2,200
#include <vector> #include <algorithm> #include <utility> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <set> #include <map> #include <cstring> #include <time.h> #define rep(i,n) for(int i=0;i<n;i++) #define pb push_back #define Debug(x) cout<<#x<<"="<<x<<endl; #define For(i,l,r) for(int i=l;i<=r;i++) #define tr(e,x) for(typeof(x.begin()) e=x.begin();e!=x.end();e++) #define printTime cout<<"Time:"<<pre-clock()<<endl;pre=clock(); const int inf=~0U>>1,maxn=100000+10,Log=20,seed=133331; using namespace std; typedef vector<int> VI; typedef long long ll; const ll F=354871524; map<int,VI> Map; int n,A[maxn]; ll P[Log]; ll Hash[maxn][Log]; void DoIt() { P[0]=seed;rep(i,Log-1)P[i+1]=P[i]*P[i]; rep(j,Log)rep(i,n) if(i+(1<<j)<=n) { ll&tmp=Hash[i][j]; if(!j)tmp=A[i]^F; else tmp=(Hash[i][j-1])*P[j-1]+Hash[i+(1<<(j-1))][j-1]; } } int Lcp(int a,int b) { if(a>b)swap(a,b);int ret=0; for(int i=Log-1;i>=0;i--) { if(b+(1<<i)>n)continue; if(Hash[a][i]==Hash[b][i]) a+=(1<<i),b+=(1<<i),ret+=(1<<i); } return ret; } bool Check(int a,int b) { int s=b-a; return Lcp(a,b)>=s; } struct Seg { int l,r,s; Seg(int _l,int _r):l(_l),r(_r),s(r-l){} bool operator<(const Seg&o)const { if(s!=o.s)return s<o.s; return l<o.l; } }; int main() { //freopen("in","r",stdin); cin>>n; rep(i,n)scanf("%d",A+i),Map[A[i]].pb(i); DoIt(); vector<Seg> S; for(map<int,VI>::iterator it=Map.begin();it!=Map.end();it++) { VI&tmp=it->second; For(i,0,tmp.size()-1) For(j,i+1,tmp.size()-1) if(Check(tmp[i],tmp[j])) S.pb(Seg(tmp[i],tmp[j]-1)); } sort(S.begin(),S.end()); int now=0; rep(i,S.size()) { Seg&tmp=S[i]; if(tmp.l>=now)now=tmp.r+1; } cout<<n-now<<endl; For(i,now,n-1)cout<<A[i]<<" "; }
19
D
Points
Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point $(0, 0)$ is located in the bottom-left corner, $Ox$ axis is directed right, $Oy$ axis is directed up. Pete gives Bob requests of three types: - add x y — on the sheet of paper Bob marks a point with coordinates $(x, y)$. For each request of this type it's guaranteed that point $(x, y)$ is not yet marked on Bob's sheet at the time of the request. - remove x y — on the sheet of paper Bob erases the previously marked point with coordinates $(x, y)$. For each request of this type it's guaranteed that point $(x, y)$ is already marked on Bob's sheet at the time of the request. - find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point $(x, y)$. Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete. Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to $2·10^{5}$, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please!
First of all,do the discretization.Then the biggest value of x is n,so we can build a Segment Tree to Ask the question "what is the first place from postion x and its value is bigger than y"..if we find such postion we just find the smallest Y-value bigger than y in such postion--it can be done using set's operation upper_bound...http://en.wikipedia.org/wiki/Segment_tree so the algorithm is clear..For every possible value of x use a set to store all y value in it..And every time the action is "find" or "remove" just change this set and update the Segment Tree..otherwise use Segment Tree to find the answer..
[ "data structures" ]
2,800
#include <vector> #include <algorithm> #include <utility> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <set> #include <map> #include <cstring> #include <time.h> #define rep(i,n) for(int i=0;i<n;i++) #define pb push_back #define Debug(x) cout<<#x<<"="<<x<<endl; #define For(i,l,r) for(int i=l;i<=r;i++) #define tr(e,x) for(typeof(x.begin()) e=x.begin();e!=x.end();e++) #define printTime cout<<"Time:"<<pre-clock()<<endl;pre=clock(); const int inf=~0U>>1,maxn=200000+10; using namespace std; int n,m; struct Index { int A[maxn],n; int size(){return n;} void clear(){n=0;} void add(int x){A[n++]=x;} void doit() { sort(A,A+n);n=unique(A,A+n)-A; } int operator[](int v){return lower_bound(A,A+n,v)-A;} }IX; char cmd[100]; struct Action { int type,x,y; void readin() { scanf("%s%d%d",cmd,&x,&y); IX.add(x); if(cmd[0]=='a')type=0; if(cmd[0]=='r')type=1; if(cmd[0]=='f')type=2; } }A[maxn]; set<int> S[maxn]; int M(int i){return *(--S[i].end());} int Max[maxn*4]; #define Tree int t,int l,int r #define Left t*2,l,l+r>>1 #define Right t*2+1,l+r>>1,r #define root 1,0,m void Update(int t) { Max[t]=max(Max[t*2],Max[t*2+1]); } void Change(Tree,int p) { if(p<l||p>=r)return; if(l+1==r){Max[t]=M(l);return;} Change(Left,p);Change(Right,p); Update(t); } int Query(Tree,int a,int c) { if(a>=r||Max[t]<=c)return -1; if(l+1==r)return l; int tmp=Query(Left,a,c);if(tmp>=0)return tmp; tmp=Query(Right,a,c);if(tmp>=0)return tmp; return -1; } void init() { cin>>n; rep(i,n)A[i].readin(); IX.doit(); } void Solve() { m=IX.size();memset(Max,-1,sizeof Max); rep(i,m)S[i].insert(-1); rep(i,n) { int x=A[i].x,y=A[i].y;x=IX[x]; switch(A[i].type) { case 0:S[x].insert(y);Change(root,x);break; case 1:S[x].erase(S[x].find(y));Change(root,x);break; case 2:int tmp=Query(root,x+1,y); if(tmp==-1)printf("-1 "); else { set<int>::iterator it=S[tmp].upper_bound(y); printf("%d %d ",IX.A[tmp],*it); } } } } int main() { //freopen("in","r",stdin); init(); Solve(); }
19
E
Fairy
Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper $n$ points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess.
It's a interesting problem.If you for every edge, try to remove it and check if it is a bipartite graph..I think it will get TLE..so let's analysis the property of bipartite graph..http://en.wikipedia.org/wiki/Bipartite_graphAfter reading it...we know.. It should never contain a cycle of odd length... and it can be 2-colored.. so first build a spanning forest for the graph.. and do the 2-color on it(Tree can be 2-colored). for convenience. Let TreeEdge={all edge in forest} NotTreeEdge={All edge}/TreeEdge ErrorEdge={all edge that two endpoint have the same color..} NotErorEdge=NotTreeEdge/ErroEdge.. First,consider a edge form NotTreeEdge,remove it can't change any node's color..so.. if |ErrorEdge|=0 of course we can remove all NotTreeEdge if =1 we just can remove the ErrorEdge if >1 we can't remove any from NotTreeEdge Now,Let consider a Edge e from TreeEdge.. Let Path(Edge e)=the path in forest between e's two endpoints.. if there is a Edge e' from ErrorEdge that Path(e') didn't go through e..it will destroy the bipartite graph.. if there is a Edge e' from ErrorEdge that Path(e') go through e and there is a Edge e'' from NotErrorEdge that Path(e'') go through e..it will also destroy the bipartite graph.. so now we need to know for every edge,how many such path go through it..it require a data structure... one way is to use heavy-light decomposition then we can update every path in O(LogN^2)... another way is to use Link-Cut Tree..It can do the same in O(LogN)....if you didn't see Link-Cut tree before,you can read thishttp://www.cs.cmu.edu/~sleator/papers/dynamic-trees.pdfor my code..use heavy-light decomposition
[ "dfs and similar", "divide and conquer", "dsu" ]
2,900
#include <vector> #include <algorithm> #include <utility> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <set> #include <map> #include <cstring> #include <time.h> #define rep(i,n) for(int i=0;i<n;i++) #define pb push_back #define Debug(x) cout<<#x<<"="<<x<<endl; #define For(i,l,r) for(int i=l;i<=r;i++) #define tr(e,x) for(vector<int>::iterator e=x.begin();e!=x.end();e++) #define printTime cout<<"Time:"<<pre-clock()<<endl;pre=clock(); const int inf=~0U>>1,maxn=10000; using namespace std; typedef pair<int,int> pi; vector<int> E[maxn]; map<pi,int> Map; vector<pi> Es; set<pi> InTree; int mnt=0,n,m; struct TA { vector<int> A; int s; void Add(int l,int d) { l-=s; for(l++;l<=A.size();l+=l&-l) A[l-1]+=d; } void Add(int l,int r,int d) { Add(l,d);Add(r+1,-d); } int Sum(int l) { l-=s;int ret=0; for(l++;l;l-=l&-l)ret+=A[l-1]; return ret; } void Build(int l,int r) { s=l;int n=r-l+1;A=vector<int>(n); } }T[2][maxn]; void AddEdge(int s,int t) { E[s].pb(t);E[t].pb(s); Map[pi(s,t)]=Map[pi(t,s)]=mnt++; Es.pb(pi(s,t)); } int D[maxn],F[maxn]; bool c[maxn]; int Q[maxn],h,t,Size[maxn],own[maxn]; bool Vis[maxn]={}; void BFS(int vs) { h=t=0; for(F[vs]=-1,Vis[vs]=true,Q[t++]=vs,D[vs]=0;h<t;h++) { int x=Q[h];c[x]=D[x]%2; tr(e,E[x])if(!Vis[*e]) { Q[t++]=*e;F[*e]=x; D[*e]=D[x]+1;Vis[*e]=true; InTree.insert(pi(x,*e)); InTree.insert(pi(*e,x)); } } for(int i=h-1;i>=0;i--) { int x=Q[i];Size[x]=1; tr(e,E[x])if(F[*e]==x)Size[x]+=Size[*e]; } for(int i=0;i<h;i++) { int a=Q[i];if(own[a]>=0)continue; int x=a,next; for(;;x=next) { next=-1;own[x]=a; tr(e,E[x])if(F[*e]==x) if(next==-1||Size[*e]>Size[next]) next=*e; if(next==-1)break; } rep(j,2)T[j][a].Build(D[a],D[x]); } } void MarkThePath(int u,int v,int t) { for(;;) { if(D[u]<D[v])swap(u,v); if(own[u]==own[v]) { T[t][own[u]].Add(D[v]+1,D[u],1); return; } if(D[own[u]]<D[own[v]])swap(u,v); T[t][own[u]].Add(D[own[u]],D[u],1); u=F[own[u]]; } } int GetTheValue(int u,int v,int t) { if(D[u]<D[v])swap(u,v); return T[t][own[u]].Sum(D[u]); } bool IsTreeEdge(int u,int v) { if(D[u]<D[v])swap(u,v); return D[u]==D[v]+1; } void init() { scanf("%d%d",&n,&m);int s,t; rep(i,m) { scanf("%d%d",&s,&t);--s;--t; AddEdge(s,t); } } vector<pi> Ans; void Solve() { //Built It memset(own,-1,sizeof own); rep(i,n)if(!Vis[i])BFS(i); vector<pi> TreeEdge,NotErrorEdge,ErrorEdge; //For All Tree Not On Tree rep(i,Es.size()) { pi e=Es[i]; if(InTree.find(e)!=InTree.end()) { TreeEdge.pb(e); } else { if(c[e.first]==c[e.second]) ErrorEdge.pb(e); else NotErrorEdge.pb(e); } } if(ErrorEdge.size()==0) Ans=NotErrorEdge; if(ErrorEdge.size()==1) Ans=ErrorEdge; //Mark The Path For ErorrEdge rep(i,ErrorEdge.size()) { pi e=ErrorEdge[i]; MarkThePath(e.first,e.second,0); } //Mark The Path For NotErorrEdge rep(i,NotErrorEdge.size()) { pi e=NotErrorEdge[i]; MarkThePath(e.first,e.second,1); } // For All Tree Edge int a[2]; rep(i,TreeEdge.size()) { pi e=TreeEdge[i]; rep(j,2)a[j]=GetTheValue(e.first,e.second,j); if(a[0]<ErrorEdge.size()||(a[0]&&a[1]))continue; Ans.pb(e); } vector<int> Print; rep(i,Ans.size())Print.pb(Map[Ans[i]]+1); sort(Print.begin(),Print.end()); cout<<Print.size()<<endl; rep(i,Print.size())cout<<Print[i]<<" ";cout<<endl; } int main() { //freopen("in","r",stdin); init(); Solve(); }
22
A
Second Order Statistics
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.
In this problem one should find a minimal element from all elements, that are strictly greater, then the minimal one or report that it doesn't exist. Of course, there can be a lot of different solutions, but one of the simplest - to sort the given sequence and print the first element, that's not equal to the previous. If all elements are equal, then the required element doesn't exist.
[ "brute force" ]
800
null
22
B
Bargaining Table
Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room $n × m$ meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that its sides are parallel to the office walls. Bob doesn't want to change or rearrange anything, that's why all the squares that will be occupied by the table should be initially free. Bob wants the new table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the maximum possible perimeter of a bargaining table for his office.
In this problem one should find the maximal perimeter of a rectangle that contains no '1'. Define these rectangles "correct". To solve a problem you are to check each possible rectangle for correctness and calculate its perimeter. The easiest way to check all rectangles is using 6 nested cycles. Using 4 of them you fix the coordinates while other 2 will look for '1'. So the complexity is O((n*m)3). It seems slow, but those, who wrote such a solution, says that it hasn't any problems with TL.One may interest in much faster solution. Using simple DP solution one can get a solution with an O((n*m)2) complexity. It's clear, that rectangle with coordinates (x1, y1, x2, y2) is correct if and only if rectangles (x1, y1, x2-1, y2) and (x1, y1, x2, y2-1) are correct, and board[x2][y2] = '0'. So each of rectangles can be checked in O(1) and totally there will be O((n*m)2) operations.
[ "brute force", "dp" ]
1,500
null
22
C
System Administrator
Bob got a job as a system administrator in X corporation. His first task was to connect $n$ servers with the help of $m$ two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index $v$ fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
In this problem you are to construct a connected graph, which contains n vertexes and m edges, and if we delete vertex with number v, our graph stops being connected or to report that such a graph doesn't exist. Moreover, each pair of vertexes can have no more than one edge connecting them. Obviously, a connected graph doesn't exist if the number of edges is less than n-1. It's easy to notice, that the maximal possible number of edges reaches when there is a vertex connected to v and doesn't connected to any other vertex, those can form up to complete graph. So the maximal number of edges is (n-1)*(n-2)/2+1. If m is in that range then required graph always exists. Then you should place one vertex on the one side of v (let it be 1), and other vertexes - on the other side. First, you should connect all this vertexes to v and then connect them between each other (except 1).
[ "graphs" ]
1,700
null
22
D
Segments
You are given $n$ segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?
In this problem one should place minimal number of points on the line such that any given segment touches at least one of these points. Let's call the coordinate of ending of any segment as event. There will be events of two types: beginning of a segment and its ending. Let's sort this events by coordinates. In the case of equality of some events consider that the event of the beginning will be less than the event of ending. Look at our events from left to right: if there is a beginning event, then push the number of this segment to the special queue. Once we take an ending of some segment, place the point here and clear the special queue (because each of segment in this queue will touch this point).
[ "greedy", "sortings" ]
1,900
null
22
E
Scheme
To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third member, and so on; i.e. a person with index $i$ got a person with index $f_{i}$, to whom he has to call, if he learns the news. With time BolgenOS community members understood that their scheme doesn't work sometimes — there were cases when some members didn't learn the news at all. Now they want to supplement the scheme: they \underline{add} into the scheme some instructions of type $(x_{i}, y_{i})$, which mean that person $x_{i}$ has to call person $y_{i}$ as well. What is the minimum amount of instructions that they need to add so, that at the end everyone learns the news, no matter who is the first to learn it?
Given an oriented graph, find the minimal number of edges one should add to this graph to make it strongly connected. Looking at statement we can get the fact that each vertex has exactly one outcoming edge. It means that starting at some point we'll get stuck in some cycle. So each connected (not strongly) component is a set of simple paths, ending in some cycle or just a simple cycle. First consider vertexes, which has no incoming edges. When passing through some vertex we'll paint it until the current vertex will be already painted. Then we call the starting vertex as "beginning" and the finishing one as "ending" of a component.After that consider other vertexes - they belong to cycles. Beginning and ending of a cycle - is any vertexes (possible coinciding) belonging to it. So we got a number of components which we have to connect. Let's connect them cyclically: the edge will pass from the ending of i-th component to the beginning of ((i+1)%k)-th, where k is the number of such components. The answer will be k. There is an exception: if we have only one component which is a simple cycle, the answer will be equal to 0.So we'll consider each edge exactly once and the total complexity will be O(n).
[ "dfs and similar", "graphs", "trees" ]
2,300
null
23
A
You're Given a String...
You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
Iterate over all substrings, starting with the longest ones, and for each one count the number of appearances. The complexity is $O(L4)$ with a small multiplicative constant.
[ "brute force", "greedy" ]
1,200
null
23
B
Party
$n$ people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly $2, 3, ..., n - 1$ friends among those who stayed by the moment of their leaving, did the same. What is the maximum amount of people that could stay at the party in the end?
It's clear that at least one person (the one with the least number of friends) will have to leave. We claim that at least two persons will leave. Indeed, suppose that only one person left, and he had $d$ friends. Then all other people had more than $d$ friends before he left, and after that they had less than $d + 1$ friends, i.e. not more than $d$. So, his leaving influenced the number of friends for every other person, which means that he was friends with everyone: $d = N - 1$. But he has fewer friends than everyone - a contradiction.So, the answer is not more than $N - 2$. We'll prove that it's possible for $N - 2$ people to stay (of course, if $N > 1$). The graph of friendship will be the following: take a complete graph on $N$ vertices and delete one edge. Then the degrees of two vertices equal $N - 2$, and other degrees equal $N - 1$. After the first two vertices are removed, we have a complete graph on $N - 2$ vertices, and all degrees equal $N - 3$, which means that no one else will leave.
[ "constructive algorithms", "graphs", "math" ]
1,600
null
23
C
Oranges and Apples
In $2N - 1$ boxes there are apples and oranges. Your task is to choose $N$ boxes so, that they will contain not less than half of all the apples and not less than half of all the oranges.
Sort the boxes in increasing number of oranges. Count the total number of apples in boxes with odd and even numbers. If the boxes with odd numbers contain at least half of all apples, choose them (there are exactly $N$ boxes with odd numbers). If the boxes with even numbers contain at least half of all apples, take them and the last box (which contains the largest number of oranges). It's easy to see that in both cases the conditions of the task are fulfilled.
[ "constructive algorithms", "sortings" ]
2,500
null
23
D
Tetragon
You're given the centers of three equal sides of a strictly convex tetragon. Your task is to restore the initial tetragon.
Let ABCD be the quadrangle that we're looking for, and K, L, and M be the middle points of equal sides AB, BC and CD, correspondingly. Let M' be the point symmetric to M with respect to L. Triangles BLM' and CLM are equal by two sides and angle, so BM' = CM = BL = BK, i. e. B is the circumcenter of the triangle KLM'. Knowing B, we can reconstruct the whole quadrangle, using the symmetries with respect to the points K, L, and M, and then check whether it satisfies all conditions.Note that we don't know which of the given points is L, so we need to check all 3 cases.
[ "geometry", "math" ]
2,600
null
23
E
Tree
Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree.
Lemma. In one of optimal solutions there are no simple paths of length 3.Proof. We can remove the middle edge from such a path. The connected component will split into two components of sizes $a$ and $b$, where $a \ge 2, b \ge 2$, and therefore $ab \ge a + b$.We'll root the tree and calculate recursively the numbers $hv$ = the solution of the problem for the subtree with the root $v$, and $fv$ = the product of $hu$ for all children of $v$. If $v$ is a leaf, then $hv = fv = 1$.We show how to calculate $hv$, given the solution for all subtrees of $v$. Consider the connected component of $v$ in an optimal solution. It follows from the lemma that the component has one of the following types:1. The single vertex $v$.2. The vertex $v$ and several children of $v$.3. The vertex $v$, one child of $v$ - $w$, and several children of $w$.In the first case the result of the game is $fv$.In the second case it equals $ \Pi fi \cdot \Pi hj \cdot k = \Pi (fi / hi) \cdot fv \cdot k$, where $i$ iterates over children belonging to the connected component, $j$ iterates over the rest children, and $k$ is the size of the component. Since we want to maximize the result, we're interested in children with the largest value of $fi / hi$. Therefore, the largest possible result in this case equals the maximum value of $ \Pi i \le s (fi / hi) \cdot fv \cdot (s + 1)$, where it's supposed that the children are sorted in descending order of $fi / hi$.In the third case we can use a similar reasoning for every child $w$. The best result will be the maximum of the expression $fv \cdot (fw / hw) \cdot \Pi i \le s (fi / hi) \cdot (s + 2)$ as $w$ iterates over children of $v$, and $s$ iterates from 1 to the number of children of $w$; note that the children of $w$ have already been sorted in the previous step.Therefore, the number of operations necessary to calculate $fv$ is proportional to the total number of children and grandchildren of $v$, which is less than $n$. The complexity of the algorithm, then, is $O(n2)$ (ignoring operations with long numbers).
[ "dp" ]
2,500
null
24
A
Ring road
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all $n$ cities of Berland were connected by $n$ two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all $n$ roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
This is pretty simple task - we have cycle and must direct all edges on it in one of 2 directions. We need to calculate cost of both orientation and print smallest of them.There is a small trick - we can calculate cost of only one orientation and then cost of the other will be sum of costs of all edges minus cost of first orientation.
[ "graphs" ]
1,400
null
24
B
F1 Champions
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places. You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.
Also very simple - we need literary do what we asked. We put all data in a map where for each pilot we have number of points and array of 50 elements - number of times pilot finished at corresponding place. Then we just need to find maximum in this array according to 2 given criteria.
[ "implementation" ]
1,500
null
24
C
Sequence of points
You are given the following points with integer coordinates on the plane: $M_{0}, A_{0}, A_{1}, ..., A_{n - 1}$, where $n$ is odd number. Now we define the following infinite sequence of points $M_{i}$: $M_{i}$ is symmetric to $M_{i - 1}$ according ${\cal A}_{\{i-1\}}\,\mathrm{\mod}\,\,n$ (for every natural number $i$). Here point $B$ is symmetric to $A$ according $M$, if $M$ is the center of the line segment $AB$. Given index $j$ find the point $M_{j}$.
Reflection over 2 points is just a parallel shift for a doubled vector between them. So $M2n$ = $M0$ because sequence of reflections may be replaced with sequence of shifts with doubled vectors $A0A2$, $A2A4$, ..., $An - 2A0$ - and their sum is 0. So we can replace j with $j' = jmod2N$. Now we can just perform j' reflections. Suppose we need to find M' (x', y') - reflection of M(x, y) witch center at A($x0$, $y0$). Then $x' = 2x0 - x$, $y' = 2y0 - y$.
[ "geometry", "implementation", "math" ]
1,800
null
24
D
Broken robot
You received as a gift a very clever robot walking on a rectangular board. Unfortunately, you understood that it is broken and behaves rather strangely (randomly). The board consists of $N$ rows and $M$ columns of cells. The robot is initially at some cell on the $i$-th row and the $j$-th column. Then at every step the robot could go to some another cell. The aim is to go to the bottommost ($N$-th) row. The robot can stay at it's current cell, move to the left, move to the right, or move to the cell below the current. If the robot is in the leftmost column it cannot move to the left, and if it is in the rightmost column it cannot move to the right. At every step all possible moves are equally probable. Return the expected number of step to reach the bottommost row.
If robot is at last row then answer is 0. Suppose that for every cell of the next row we now expected number of steps to reach last row - $zi$. Let $xi$ be expected value of steps to reach the last row from current row. Then we have following system of equations:$x1 = 1 + x1 / 3 + x2 / 3 + z1 / 3$$xi = 1 + xi / 4 + xi - 1 / 4 + xi + 1 / 4 + zi / 4$ for i from 2 to M - 1$xM = 1 + xM / 3 + xM - 1 / 3 + zM / 3$This is tridiagonal system, it can be solved using tridiagonal matrix algorithm in linear time.So we just have to solve this for each row starting from N - 1 and ending at i and then take x[j].For M = 1 the answer is 2(N - i) because expected number of steps to go down is 2 - on each turn we either go down or stay
[ "dp", "math", "probabilities" ]
2,400
null
24
E
Berland collider
Recently the construction of Berland collider has been completed. Collider can be represented as a long narrow tunnel that contains $n$ particles. We associate with collider 1-dimensional coordinate system, going from left to right. For each particle we know its coordinate and velocity at the moment of start of the collider. The velocities of the particles don't change after the launch of the collider. Berland scientists think that the big bang will happen at the first collision of particles, whose velocities differs in directions. Help them to determine how much time elapses after the launch of the collider before the big bang happens.
At first we need to exclude answer -1. Answer is -1 if and only if first part of particles moves left and second part moves right (any of this parts may be empty)Let's use binary search. Maximal answer is 1e9. Suppose we need to unserstand - whether answer is more then t or less then t. Let's itirate particles from left to right and maintain maximal coordinate that particle moving right would achive. Then of we will meet particle moving left that will move to the left of that coordinate in time t that we have 2 particles that will collide before time t. Otherwise we won't have such pair of particles.
[ "binary search" ]
2,300
null
25
A
IQ test
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given $n$ numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given $n$ numbers finds one that is different in evenness.
We can store two values, $count_{odd}$ and $count_{even}$, as the number of odd or even elements in the series. We can also store $last_{odd}$ and $last_{even}$ as the index of the last odd/even item encountered. If only one odd number appears --- output $last_{odd}$; otherwise only one even number appears, so output $last_{even}$.
[ "brute force" ]
1,300
null
25
B
Phone numbers
Phone number in Berland is a sequence of $n$ digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.
There are many ways of separating the string into clusters of 2 or 3 characters. One easy way is to output 2 characters at a time, until you have only 2 or 3 characters remaining.
[ "implementation" ]
1,100
null
25
C
Roads in Berland
There are $n$ cities numbered from 1 to $n$ in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build $k$ new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
If you are familiar with the Floyd-Warshall algorithm, then this solution may be easier to see.Initially, we are given a matrix $D$, where $D[i][j]$ is the distance of shortest path between city $i$ and city $j$. Suppose we build a new road between $a$ and $b$ with length shorter than $D[a][b]$. How do we update the rest of the graph accordingly?Define a new matrix $D'$, whose entries $D'[i][j]$ are the minimum path distance between $i$ and $j$ while taking into account the new road $ab$. There are three possibilities for each $i, j$:$D'[i][j]$ remains unchanged by the new road. In this case $D'[i][j] = D[i][j]$$D'[i][j]$ is shorter if we use the new road $ab$. This means that the new path $i, v_{1}, v_{2}, ..., v_{n}, j$ must include the road $a, b$. If we connect the vertices $i, a, b, j$ together in a path, then our new distance will be $D[i][a] + length(ab) + D[b][j]$.Lastly, we may have to use the road $ba$. (Note that this may not be the same as road $ab$.) In this case, we have $D'[i][j] = D[i][b] + length(ab) + D[a][j]$.Thus, for each new road that we build, we must update each path $i, j$ within the graph. Then we must sum shortest distances between cities. Updating the matrix and summing the total distance are both $O(N^{2})$, so about $300^{2}$ operations. Lastly, there are at most $300$ roads, so in total there are about $300^{3}$ operations.One thing to note is that the sum of all shortest distances between cities may be larger than an int; thus, we need to use a long when calculating the sum.
[ "graphs", "shortest paths" ]
1,900
null
25
D
Roads not only in Berland
Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are $n$ cities in Berland and neighboring countries in total and exactly $n - 1$ two-way roads. Because of the recent financial crisis, the Berland Government is strongly pressed for money, so to build a new road it has to close some of the existing ones. Every day it is possible to close one existing road and immediately build a new one. Your task is to determine how many days would be needed to rebuild roads so that from each city it became possible to reach all the others, and to draw a plan of closure of old roads and building of new ones.
Before we start this problem, it is helpful to know about the union find data structure. The main idea is this: given some elements $x_{1}, x_{2}, x_{3}, ..., x_{n}$ that are partitioned in some way, we want to be able to do the following:merge any two sets together quicklyfind the parent set of any $x_{i}$This is a general data structure that sometimes appears in programming competitions. There are a lot of ways to implement it; one good example is written by Bruce Merry (aka BMerry) here.Back to the problem: Every day we are allowed to build exactly 1 road, and close exactly 1 road. Thus, we can break the problem into two parts:How do we connect the parts of the graph that are disconnected?How do we remove roads in a way that does not disconnect parts of the graph? Let $build$ be the list all roads that need to be built, and let $close$ be the list of nodes that need to be closed. We can show that in fact, these lists are of the same size. This is because the connected graph with $n$ nodes is a tree if and only if it has $n - 1$ edges. Thus, if we remove more roads than than we build, then the graph is disconnected. Also, if we build more roads than we remove, then we have some unnecessary roads (the graph is no longer a tree).Now consider the format of the input data:$a_{1}, b_{1}$$a_{2}, b_{2}$...$a_{None}, b_{None}$We can show that edge $(a_{i}, b_{i})$ is unnecessary if and only if the nodes $a_{i}, b_{i}$ have already been connected by edges $(a_{1}, b_{1}), (a_{2}, b_{2}), ..., (a_{None}, b_{None})$. In other words, if the vertices $a_{i}, b_{i}$ are in the same connected component before we, add $(a_{i}, b_{i})$ then we do not need to add $(a_{i}, b_{i})$. We can use union-find to help us solve this problem:<code>for( i from 1 to n-1 ){ if( find($a_{i}$)=find($b_{i}$) ) close.add$(a_{i}, b_{i})$; else merge($a_{i}, b_{i}$);}</code>In other words, we treat each connected component as a set. Union find allows us to find the connected component for each node. If the two connected components are the same, then our new edge is unnecessary. If they are different, then we can merge them together (with union find). This allows us to find the edges that we can remove.In order to find the edges that we need to add to the graph, we can also use union-find: whenever we find a component that is disconnected from component 1, then we just add an edge between them.<code>for( i from 2 to n ) if( find($v_{i}$)!=find($v_{1}$) ) { then merge$(v_{1}, v_{i})$; build.add$(v_{1}, v_{i})$; }</code>We just need to store the lists of roads that are unnecessary, and the roads that need to be built.
[ "dsu", "graphs", "trees" ]
1,900
null
25
E
Test
Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring $s_{1}$, the second enters an infinite loop if the input data contains the substring $s_{2}$, and the third requires too much memory if the input data contains the substring $s_{3}$. Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions?
The way I solved this problem is with a hash function. Hash functions can fail on certain cases, so in fact, my solution is not 'correct'. However, it passed all the test cases =PLet the input strings be $s_{0}, s_{1}, s_{2}$. We can build the shortest solution by permuting the strings and then trying to 'attach' them to each other. I.e., we need to find the longest overlapping segments at the end of string $a$ and the beginning of string $b$. The obvious brute force solution won't run in time. However, we can use a hash function to help us calculate the result in $O(n)$ time, where $n$ is $min(len(a), len(b))$. The hash function that I used was the polynomial $hash(x_{0}, x_{1}, ..., x_{n}) = x_{0} + ax_{1} + a^{2}x_{2} + ... + a^{n}x_{n}$. This polynomial is a good hash function in this problem because it has the following useful property:Given $hash(x_{i}, ..., x_{j})$, we can calculate the following values in $O(1)$ time:$hash(x_{None}, x_{i}, ..., x_{j}) = x_{None} + a \times hash(x_{i}, ..., x_{j})$$hash(x_{i}, ..., x_{j}, x_{None}) = hash(x_{i}, ..., x_{j}) + a^{None} \times x_{None}$In other words, if we know the hash for some subsequence, we can calculate the hash for the subsequence and the previous element, or the subsequence and the next element. Given two strings $a, b$, we can calculate the hash functions starting from the end of $a$ and starting from the beginning of $b$. If they are equal for length $n$, then that means that (maybe) $a$ and $b$ overlap by $n$ characters.Thus, we can try every permutation of $s_{0}, s_{1}, s_{2}$, and try appending the strings to each other. There is one last case: if $s_{i}$ is a substring of $s_{j}$ for some $i \neq j$, then we can just ignore $s_{i}$. We can use hash functions to check that one string is contained within another one.
[ "hashing", "strings" ]
2,200
null
26
A
Almost Prime
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and $n$, inclusive.
This is a straightforward implementation problem: factor every number from 1 to n into product of primes and count the number of distinct prime divisors.
[ "number theory" ]
900
null
26
B
Regular Bracket Sequence
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?
Read the string from left to right and calculate the balance of brackets at each step (i.e., the difference between the number of "(" and ")" characters written out). We need to keep this balance non-negative. Hence, every time when the balance equals 0 and we read the ")" character, we must omit it and not write it out. The answer to the problem is twice the number of ")" characters that we wrote out.
[ "greedy" ]
1,400
null
26
C
Parquet
Once Bob decided to lay a parquet floor in his living room. The living room is of size $n × m$ metres. Bob had planks of three types: $a$ planks $1 × 2$ meters, $b$ planks $2 × 1$ meters, and $c$ planks $2 × 2$ meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks.
We'll derive several necessary conditions for the parquet to be possible. If some of them is not fulfilled, the answer is "IMPOSSIBLE".1. m*n must be even, because it equals the total area of the parquet, and the area of each plank is even.2. Suppose m (the number of columns) is odd. Paint the living room in two colors - black and white - in the following way: the first column is black, the second one is white, the third one is black, ..., the last one is black. The number of black squares is $n$ greater than the number of white squares. The planks 1x2 and 2x2 contain an equal number of black and white squares, so we must compensate the difference with 2x1 planks, and their number must be at least n/2. In this case we can parquet the last column with these planks, decrease $b$ by n/2 and decrease $m$ by one.3. If $n$ is odd, then by similar reasoning $a \ge m / 2$.4. Now $m$ and $n$ are even. A similar reasoning shows that the number of 1x2 planks used must be even, and the number of 2x1 planks used must be even. So, if $a$ is odd, we decrease it by 1, and the same with $b$.5. Now we must have $mn \le 2a + 2b + 4c$, because otherwise the total area of planks would not be enough.6. If all the conditions were fulfilled, we can finish the parquet: divide it into 2x2 squares, and use one 2x2 plank, two 1x2 planks, or two 2x1 planks to cover each square.
[ "combinatorics", "constructive algorithms", "greedy", "implementation" ]
2,000
null
26
D
Tickets
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly $n + m$ people will come to buy a ticket. $n$ of them will have only a single 10 euro banknote, and $m$ of them will have only a single 20 euro banknote. Currently Charlie has $k$ 10 euro banknotes, which he can use for change if needed. All $n + m$ people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.
If we picture the graph of the number of 10-euro banknotes, it will be a broken line, starting at the point (0, k) and ending at the point (m+n, n+k-m). Exactly $m$ segments on the line are 'going down', and other $n$ segments are 'going up'. Hence the total number of possible graphs is $C(m + n, m)$ (the binomial coefficient). We need to find out the number of graphs which don't go under the X axis. To do that, we'll calculate the complementary number: the number of graphs which go under the X axis, or, equivalently, intersect the line y=-1. Here we'll use the so-called 'reflection principle'. Consider any graph that intersects the line y=-1, and take the last point of intersection. Reflect the part of the graph from this point to the end with respect to the line y=-1. We'll have a new graph, ending at the point $(m + n, - 2 - n - k + m)$. Conversely, any graph ending at this point will intersect the line y=-1, and we can apply the same operation to it. Hence, the number of graphs we're interested in equals the number of graphs starting at the point $(0, k)$ and ending at the point $(m + n, - 2 - n - k + m)$. Let $a$ and $b$ be the number of segments in such a graph which go up and down, respectively. Then $a + b = m + n$, $a - b + k = - 2 - n - k + m$. It follows that $a = m - k - 1$, and there are $C(m + n, m - k - 1)$ such graphs. So, the probability that the graph will go down the X axis is $C(m + n, m - k - 1) / C(m + n, m) = (m!n!) / ((n + k + 1)!(m - k - 1)!) = (m(m - 1)... (m - k)) / ((n + 1)(n + 2)... (n + k + 1))$. The answer to the problem is $1 - (m(m - 1)... (m - k)) / ((n + 1)(n + 2)... (n + k + 1))$.
[ "combinatorics", "math", "probabilities" ]
2,400
null
26
E
Multithreading
You are given the following concurrent program. There are $N$ processes and the $i$-th process has the following pseudocode: \begin{verbatim} repeat $n_{i}$ times $y_{i}$ := $y$ $y$ := $y_{i} + 1$ end repeat \end{verbatim} Here $y$ is a shared variable. Everything else is local for the process. All actions on a given row are atomic, i.e. when the process starts executing a row it is never interrupted. Beyond that all interleavings are possible, i.e. every process that has yet work to do can be granted the rights to execute its next row. In the beginning $y = 0$. You will be given an integer $W$ and $n_{i}$, for $i = 1, ... , N$. Determine if it is possible that after all processes terminate, $y = W$, and if it is possible output an arbitrary schedule that will produce this final value.
It's clear that we must have $1 \le w \le \Sigma _{i} n_{i}$. If this condition is true, we show how to achieve the desired result in the following cases:1. $N = 1, w = n_{1}$. Obvious.2. $N \ge 2, w \ge 2$. For $w = 2$, the schedule is the following: 1, all loops of processes 3..N, $n_{2} - 1$ loops of the second process, 1, 2, $n_{1} - 1$ loops of the first process, 2. For $w > 2$, we just need to move several loops from the middle of the sequence to the end.3. $N \ge 2, w = 1$, and there exists an index $i$ such that $n_{i} = 1$. Then the schedule is the following: $i$, all loops of other processes, $i$.Now we'll show that in any other case the result $w$ is impossible. The case $N = 1, w \neq n_{1}$ is obvious. We have one more case left: $N \ge 2, w = 1$, and $n_{i} > 1$ for each $i$. Suppose that there exists a schedule which results in $y = 1$. Consider the last writing operation in this schedule; suppose it is executed by the process $i$. Then the corresponding reading operation should have read the value y=0. This means that there were no writing operations before. But this is impossible, since $n_{i} > 1$, and this process executed $n_{i} - 1$ read/write loops.
[ "constructive algorithms" ]
2,400
null
27
A
Next Test
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test. You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.
We will create an array of boolean used[1..3001] ans fill it with "false" values. For each of n given number, we will assign corresponding used value to "true". After that, the index of first element of used with "false" value is the answer to the problem.
[ "implementation", "sortings" ]
1,200
null
27
B
Tournament
The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. $n$ best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. $n·(n - 1) / 2$ games were played during the tournament, and each participant had a match with each other participant. The rules of the game are quite simple — the participant who falls asleep first wins. The secretary made a record of each game in the form «$x_{i}$ $y_{i}$», where $x_{i}$ and $y_{i}$ are the numbers of participants. The first number in each pair is a winner (i.e. $x_{i}$ is a winner and $y_{i}$ is a loser). There is no draws. Recently researches form the «Institute Of Sleep» have found that every person is characterized by a value $p_{j}$ — the speed of falling asleep. The person who has lower speed wins. Every person has its own value $p_{j}$, constant during the life. It is known that all participants of the tournament have distinct speeds of falling asleep. Also it was found that the secretary made records about all the games except one. You are to find the result of the missing game.
To solve this problem first of all we should find such numbers A and B that occur in the input data not (n - 1) times, but (n - 2). We can notice, that winner-loser relation in this problem is transitive. This means that if X wins against Y and Y wins against Z, than X wins against Z. So to find out who is harsher A or B, let's look for such C, that the results of the match A with C and B with C are distinct. If such C exists, than the one, who wins against C should be printed first. If there is no such C, than both results of the match A versus B satisfy problem's statement.
[ "bitmasks", "brute force", "dfs and similar", "greedy" ]
1,300
null
27
C
Unordered Subsequence
The sequence is called \underline{ordered} if it is non-decreasing or non-increasing. For example, sequnces [3, 1, 1, 0] and [1, 2, 3, 100] are ordered, but the sequence [1, 3, 3, 1] is not. You are given a sequence of numbers. You are to find it's shortest subsequence which is not ordered. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements.
First of all, we should notice, that if answer exists, it consist of 3 elements. Here is linear time solution. Let's path with for-loop through the given array and on each iteration let's store current minimul and maximun elements positions. When we are looking at some element, it is enough to check, whereas this element makes unordered subsequence along with min and max elements of the previous part of the array. It is not obvious, but not very difficult to prove. You should try it yourself.
[ "constructive algorithms", "greedy" ]
1,900
null
27
D
Ring Road 2
It is well known that Berland has $n$ cities, which form the Silver ring — cities $i$ and $i + 1$ ($1 ≤ i < n$) are connected by a road, as well as the cities $n$ and $1$. The goverment have decided to build $m$ new roads. The list of the roads to build was prepared. Each road will connect two cities. Each road should be a curve which lies inside or outside the ring. New roads will have no common points with the ring (except the endpoints of the road). Now the designers of the constructing plan wonder if it is possible to build the roads in such a way that no two roads intersect (note that the roads may intersect at their endpoints). If it is possible to do, which roads should be inside the ring, and which should be outside?
Consider all m given roads as segments on numeric axis. Road from town a to town b should correspond to segment [min(a, b), max(a, b)]. For each pair of segments there are three types of positions: both ends of one segment are inside of the other one, both ends of one segment are outside of the other one and only one end of one segment is inside of the other one. In the first two cases positions of corresponding roads(inside circle or outside) are independend. But in the third case this positions must be opposite Let's build the graph. Vertexes will correspond to segments/roads and edge between vertexes i and j will mean that positions of this roads should be opposite. Now we have another problem: for given undirected graph, we must paint all vertexes in 2 colours such that for each edge, corresponding vertexes will have different colours. This problem can be solved using DFS algorithm. First, we will paint all vertexes in -1 colour. Let's begin for-loop through vertexes. If loop finds -1-vertex, assing colour 0 to the vertex and run DFS from it. DFS from vertex V should look through all neighbor vertex. If neighbor has colour -1, than assing to that neighbor colour, opposite to the colour of V and run DFS from it. If neighbor already has non-negative colour, we should check whereas this colour is opposite, because if it is not, answer is "Impossible". Such DFS will either build the correct answer or prove that it is impossible.
[ "2-sat", "dfs and similar", "dsu", "graphs" ]
2,200
null
27
E
Number With The Given Amount Of Divisors
Given the number $n$, find the smallest positive integer which has exactly $n$ divisors. It is guaranteed that for the given $n$ the answer will not exceed $10^{18}$.
Consider the number, that is our answer and factorize it. We will get such product $p_{1}^{None} \cdot p_{2}^{None} \cdot ... \cdot p_{k}^{None}$. Product through each i $a_{i} + 1$ will be the number of divisors. So, if we will take first 10 prime numbers, their product will have 1024 divisors. This means that we need only first 10 primes to build our answer. Let's do it with dynamic programming: d[i][j] - the minimal number with i divisors that can be built with first j prime numbers. To calculate the answer for state (i, j) let's look over all powers of j-th prime number in the answer. If j-th prime number has power k in the answer, than $d[i][j] = d[i / (k + 1)][j - 1] * prime[j]^{k}$. For each power of j-th prime we must select the power, that gives us minimal d[i][j]. You should be extremely careful during the implementation, because all calculations are made on the edge of overflow.
[ "brute force", "dp", "number theory" ]
2,000
null
28
A
Bender Problem
Robot Bender decided to make Fray a birthday present. He drove $n$ nails and numbered them from $1$ to $n$ in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods. Help Bender to solve this difficult task.
Let's look at the first nail. If it is occupied by the fold place, then Bender will put next fold place on the third nail, then on fifth and so on. Else, is the first nail occupied by end, than second, fourth, sixth and so on nail will be occupied by the fold places. Let's see, if we can complete our polyline with the first nail, occupied by rhe fold place. It means we should check, if we have an unused pod with length $dist(nails[n], nails[1]) + dist(nails[1], nails[2])$. Then check the third nail and so on. If we have completed the polyline, then we have an answer. Else repeat previous procedure, but starting from the second nail.
[ "implementation" ]
1,600
null
28
B
pSort
One day $n$ cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from $1$). Also each cell determined it's favourite number. On it's move $i$-th cell can exchange it's value with the value of some other $j$-th cell, if $|i - j| = d_{i}$, where $d_{i}$ is a favourite number of $i$-th cell. Cells make moves in any order, the number of moves is unlimited. The favourite number of each cell will be given to you. You will also be given a permutation of numbers from $1$ to $n$. You are to determine whether the game could move to this state.
Let's consider a graph. Vertexes will correspond to place of the permutation. Places will be connected by an edge if and only if we can swap theirs values. Our problem has a solution when for every i, vertex p[i] can be reached from vertex i.
[ "dfs and similar", "dsu", "graphs" ]
1,600
null
28
C
Bath Queue
There are $n$ students living in the campus. Every morning all students wake up at the same time and go to wash. There are $m$ rooms with wash basins. The $i$-th of these rooms contains $a_{i}$ wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.
This problem is solved by dynamic programming Consider the following dynamics: $d[i][j][k]$. $i$ --- number of not yet processed students, $j$ --- number of not yet processed rooms, $k$ --- maximum queue in the previous rooms. The value we need is in state $d[n][m][0]$. Let's conside some state $(i, j, k)$ and search through all $c$ from 0 to $i$. If $c$ students will go to $j$th room, than a probability of such event consists of factors: $C^{c}_{i}$ --- which students will go to $j$th room. $(1 / j)^{c} \cdot ((j - 1) / j)^{None}$ --- probability, that $c$ students will go to $j$th room,and the rest of them will go to the rooms from first to $j - 1$th. Sum for all $n$ from 0 to $i$ values of $(1 / j)^{c} \cdot ((j - 1) / j)^{None} \cdot C^{c}_{i} \cdot d[i - c][j - 1][mx]$. Do not forget to update maximum queue value and get the accepted.
[ "combinatorics", "dp", "probabilities" ]
2,200
null
28
D
Don't fear, DravDe is kind
A motorcade of $n$ trucks, driving from city «Z» to city «З», has approached a tunnel, known as Tunnel of Horror. Among truck drivers there were rumours about monster DravDe, who hunts for drivers in that tunnel. Some drivers fear to go first, others - to be the last, but let's consider the general case. Each truck is described with four numbers: - $v$ — value of the truck, of its passangers and cargo - $c$ — amount of passanger on the truck, the driver included - $l$ — total amount of people that should go into the tunnel before this truck, so that the driver can overcome his fear («if the monster appears in front of the motorcade, he'll eat them first») - $r$ — total amount of people that should follow this truck, so that the driver can overcome his fear («if the monster appears behind the motorcade, he'll eat them first»). Since the road is narrow, it's impossible to escape DravDe, if he appears from one side. Moreover, the motorcade can't be rearranged. The order of the trucks can't be changed, but it's possible to take any truck out of the motorcade, and leave it near the tunnel for an indefinite period. You, as the head of the motorcade, should remove some of the trucks so, that the rest of the motorcade can move into the tunnel and the total amount of the left trucks' values is maximal.
Let's split all trucks into different classes by the sum of $l_{i} + c_{i} + r_{i}$. Answer sequence consists of trucks from only one class, so let's solve problem for different classes independently. Let's loop through trucks from fixed class in the order, then follow in the motorcade and update values in dynamics $z[k]$ - maximum profit we can get, if last truck has $r_{i} = k$. Truck with number i can update two values: it can update value $z[r_{i}]$ with value $z[r_{i} + c_{i}] + v_{i}$. It means this truck continued some motorcade, started from some previous truck. if $l_{i} = 0$ it can update value $z[r_{i}]$ with $v_{i}$. It means this truck started motorcade. Answer will be in $z[0]$ To restore the trucks included in the answer, we can keep with the maximal sum in z the index of last truck that updated this sum. Also we store the ancestor p for each truck that updated something in z. This ancestor is calculated when we consider i-th truck and doesn't change further: p[i] = -1 if truck i became beginning of the motorcade, otherwise p[i] = last truck that updated $z[r_{i} + c_{i}]$. We start restore of the answer from last truck updated z[0]. After that we restore everything using only p.
[ "binary search", "data structures", "dp", "hashing" ]
2,400
null
28
E
DravDe saves the world
How horrible! The empire of galactic chickens tries to conquer a beautiful city "Z", they have built a huge incubator that produces millions of chicken soldiers a day, and fenced it around. The huge incubator looks like a polygon on the plane $Oxy$ with $n$ vertices. Naturally, DravDe can't keep still, he wants to destroy the chicken empire. For sure, he will start with the incubator. DravDe is strictly outside the incubator's territory in point $A(x_{a}, y_{a})$, and wants to get inside and kill all the chickens working there. But it takes a lot of doing! The problem is that recently DravDe went roller skating and has broken both his legs. He will get to the incubator's territory in his jet airplane LEVAP-41. LEVAP-41 flies at speed $V(x_{v}, y_{v}, z_{v})$. DravDe can get on the plane in point $A$, fly for some time, and then air drop himself. DravDe is very heavy, that's why he falls vertically at speed $F_{down}$, but in each point of his free fall DravDe can open his parachute, and from that moment he starts to fall at the wind speed $U(x_{u}, y_{u}, z_{u})$ until he lands. Unfortunately, DravDe isn't good at mathematics. Would you help poor world's saviour find such an air dropping plan, that allows him to land on the incubator's territory? If the answer is not unique, DravDe wants to find the plan with the minimum time of his flight on the plane. If the answers are still multiple, he wants to find the one with the minimum time of his free fall before opening his parachute
Let's look at geometrical locus where DravDe can land. It can be eigher an angle or a line(half-line). 1. Locus is an angle if and only if projection of vector $v$ and vector $u$ on Oxy plane is not collinear. This angle is easy to calculate. Angular vertex is DravDe starting point and one of half-lines is collinear with place speed vector projection. Second half-line is easy to calculate: $A_{z} + V_{z} \cdot tv + U_{z} \cdot tu = 0$ $A_{x} + V_{x} \cdot tv + U_{x} \cdot tu = B_{x}$ $A_{y} + V_{y} \cdot tv + U_{y} \cdot tu = B_{y}$ where A - starting point, B - landing point. Consider tv equal to 1 and calculate tu from first equation. From second and third calculate point B. This point lies on the second half-line of the angle. 2. If plane speed projection and wind speed projection is collinear, locus is half-line or line, depending on the difference between this two speeds. If the answer exist, than polygon and locus have at least onecommon point. And t1 and t2 is minimal on edge points. So now let's cross all segments with locus, calculate t1 and t2 for each intersection point and select minimal answer.
[ "geometry", "math" ]
2,800
null
29
A
Spit Problem
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. The trajectory of a camel's spit is an arc, i.e. if the camel in position $x$ spits $d$ meters right, he can hit only the camel in position $x + d$, if such a camel exists.
Check whether exist a pair i and j,they satisfy xi+di = xj && xj+dj = xi;
[ "brute force" ]
1,000
null
29
B
Traffic Lights
A car moves from point A to point B at speed $v$ meters per second. The action takes place on the X-axis. At the distance $d$ meters from A there are traffic lights. Starting from time 0, for the first $g$ seconds the green light is on, then for the following $r$ seconds the red light is on, then again the green light is on for the $g$ seconds, and so on. The car can be instantly accelerated from $0$ to $v$ and vice versa, can instantly slow down from the $v$ to $0$. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules?
Pay attention to Just Right or Red. use Div and Mod can solve it easily;
[ "implementation" ]
1,500
null
29
C
Mail Stamps
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately. There are $n$ stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
As we know, there are only two path -- forward and reverse, so we can do DFS from the one-degree nodes (only two nodes).As their index may be very larger, so I used map<int,int> to do hash.
[ "data structures", "dfs and similar", "graphs", "implementation" ]
1,700
null
29
D
Ant on the Tree
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too. An ant stands at the root of some tree. He sees that there are $n$ vertexes in the tree, and they are connected by $n - 1$ edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex. The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
First, Floyd pretreat the path from I to J, and save the path. Then get the answer.The order is a1,a2...ak, K is the number of the leaves, we can assume a0 = ak+1 = 1, the root.then, answer push_back the path[ai][ai+1].if the ans.size() > 2*N-1 , cout -1;else cout the answer.
[ "constructive algorithms", "dfs and similar", "trees" ]
2,000
null
30
A
Accounting
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself. The total income $A$ of his kingdom during $0$-th year is known, as well as the total income $B$ during $n$-th year (these numbers can be negative — it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient $X$ — the coefficient of income growth during one year. This coefficient should satisfy the equation: \[ A·X^{n} = B. \] Surely, the king is not going to do this job by himself, and demands you to find such number $X$. It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient $X$ must be integers. The number $X$ may be zero or negative.
First solution: naive brute Let's brute all possible values of $X$, and check each of them. It's easy to understand, that $X$ will be constrained in the same limits as values $A$ and $B$, that is, from -1000 to 1000 inclusive (obviously, there exists a test for each such $X$, so we can't decrease these limits). When we have some fixed value of $X$, we check it simply by multiplying $A$ by $X$ $n$ times. But, you should be careful with possible integer (and even 64-bit integer :) ) overflow. For example, you should stop multiplying by $X$ if the currect result exceeds 1000 by absolute value already. Second solution: formula It's easy to note, that if solution exists, then it is $n$-th root from $|B| / |A|$ fraction, with changed sign if $A$ and $B$ have different signs and if $n$ is odd (if $n$ is even, then no solution exists). That's why we could just use pow() function (or some analog in your language) to calculate $1 / n$-th power of the fraction, and after that we just have to check - is the result integer number or not. Of course, we have to check it with taking into account precision errors: that is, number is integer if it is within $10^{ - 9}$ (or some another number) from nearest integer. Moreover, in this solution you should be careful with zeroes. The worst case is when $A = 0$, and this case should be checked manually (you should note the difference between $B = 0$ and $B \neq 0$ cases). It should be told that many of the solutions failed on tests with $A = 0$, or $B = 0$, and if these tests were not included in the pretestset, I think, about half of participants would fail to solve this problem :)
[ "brute force", "math" ]
1,400
null
30
B
Codeforces World Finals
The king Copa often has been reported about the Codeforces site, which is rapidly getting more and more popular among the brightest minds of the humanity, who are using it for training and competing. Recently Copa understood that to conquer the world he needs to organize the world Codeforces tournament. He hopes that after it the brightest minds will become his subordinates, and the toughest part of conquering the world will be completed. The final round of the Codeforces World Finals 20YY is scheduled for $DD$.$MM$.$YY$, where $DD$ is the day of the round, $MM$ is the month and $YY$ are the last two digits of the year. Bob is lucky to be the first finalist form Berland. But there is one problem: according to the rules of the competition, all participants must be at least 18 years old at the moment of the finals. Bob was born on $BD$.$BM$.$BY$. This date is recorded in his passport, the copy of which he has already mailed to the organizers. But Bob learned that in different countries the way, in which the dates are written, differs. For example, in the US the month is written first, then the day and finally the year. Bob wonders if it is possible to rearrange the numbers in his date of birth so that he will be at least 18 years old on the day $DD$.$MM$.$YY$. He can always tell that in his motherland dates are written differently. Help him. According to another strange rule, eligible participant must be born in the same century as the date of the finals. If the day of the finals is participant's 18-th birthday, he is allowed to participate. As we are considering only the years from $2001$ to $2099$ for the year of the finals, use the following rule: the year is leap if it's number is divisible by four.
To solve this problem we had to learn how to check the given date XD.XM.XY for correctness (taking into account number of days in each month, leap years, and so on). After implementing this, we had just to iterate over all 6 possible permutations of three given numbers (BD,BM,BY), checking each of them for correctness as a date, and comparing it with the date of Codeforces World Finals DD.MM.YY. The comparison itself could be done, by simply adding 18 to the year number, and comparing the two dates as a triple (year,month,day). The only difficult case is the case of February, 29-th. It's easy to understand that the solution described above works correctly, if we suppose that this unlucky man (having its birthday on February 29-th) celebrates his birthday on March, 1st in 3/4 years. Interesting question - what do people usually do in this situation in the real life? :)
[ "implementation" ]
1,700
null
30
D
King's Problem?
Every true king during his life must conquer the world, hold the Codeforces world finals, win pink panda in the shooting gallery and travel all over his kingdom. King Copa has already done the first three things. Now he just needs to travel all over the kingdom. The kingdom is an infinite plane with Cartesian coordinate system on it. Every city is a point on this plane. There are $n$ cities in the kingdom at points with coordinates $(x_{1}, 0), (x_{2}, 0), ..., (x_{n}, 0)$, and there is one city at point $(x_{n + 1}, y_{n + 1})$. King starts his journey in the city number $k$. Your task is to find such route for the king, which visits all cities (in any order) and has minimum possible length. It is allowed to visit a city twice. The king can end his journey in any city. Between any pair of cities there is a direct road with length equal to the distance between the corresponding points. No two cities may be located at the same point.
In this problem to create a wright solution you need to perform the following chain of inferences (though, if you skip some steps or do them not completely, you can still get an AC solution :) ): Note that after we visit the city numbered $n + 1$, the further answer depends only from the leftmost and the rightmost unvisited cities (and it would be optimal to come to the nearest to $n + 1$-th city of them, and the come to another of them). That's why we know the answer for the case $k = n + 1$, and won't consider this case later.Before we visit the $n + 1$-th city, - this part of the path covers some segment of cities lying in the OX axis. This segment, obviously, contains the point $k$. But we can't iterate over all such possible segments, because there are $O(n^{2})$ of them, so it's still a slow solution.Let's understand the following fact: if before visiting city $n + 1$ we visited some other cities, but neither the leftmost nor the rightmost, then it was surely unprofitable. Really, after we come into the $n + 1$, the answer will depend only on the leftmost and the rightmost of non-visited cities. So, if before the $n + 1$-th city we performed some movements, but didn't change the leftmost and the rightmost cities, then it was completely unnecessary and unprofitable action.We can can get even more: there is no optimal solution, where we should move from the start city $k$ to the $n + 1$-th city directly, without vithout visiting other cities (here I suppose that $k$ is neither the leftmost nor the rightmost city). Btw, this step of reasoning could be skipped - we can believe it's sometimes profitable to come from $k$ to $n + 1$ directly, and it's not difficult to support this case in a solution we'll build later; but in order to describe the problem completely let's prove this fact too. In order to prove this, let's write down two formulas: first for the length of the answer if we come from $k$ to $n + 1$ directly, then come to city $1$, and then to city $n$ (here I suppose that $1$ and $n$ are the leftmost and the rightmost cities, accordingly, and city $1$ is nearer to $n + 1$ than $n$); second formula - for the length of the answer if we come from $k$ to $1$ first, then to $n + 1$, then to $k + 1$, and then to $n$. If we compare these two formulas, then after the cancellation of like terms we can use the triangle's inequality to see that the second formula always gives smaller value (at least, not greater) than the first. So, it's really unprofitable to come from $k$ to $n + 1$ directly.So, to make a right solution, it's enough to iterate over only two types of segments: $[1;i]$ for $i \ge k$, and $[i;n]$ for $i \le k$ (here I suppose for convenience that cities are sorted by their x-coordinate).The last idea is how to process each of these cases accurately. In order to do this we iterate over all possible $i = 1... n$. Let, for example, $i \le k$. Then we have to try the following case: go from $k$ to $n$, then return to $i$, then come to $n + 1$, and then return back to the OX axis if need (if $i > 1$). Also it is required to check another type of cases: try to go from $k$ to $i$, then to $n$, and then come to $n + 1$, and return back to the OX axis if need. Answer for each of these cases can be calculated in $O(1)$. For $i \ge k$ everything is symmetric. So, not taking into account the sorting of the citites in the beginning of the program, we get a $O(n)$-solution.
[ "geometry", "greedy" ]
2,600
null
30
E
Tricky and Clever Password
In his very young years the hero of our story, king Copa, decided that his private data was hidden not enough securely, what is unacceptable for the king. That's why he invented tricky and clever password (later he learned that his password is a palindrome of odd length), and coded all his data using it. Copa is afraid to forget his password, so he decided to write it on a piece of paper. He is aware that it is insecure to keep password in such way, so he decided to cipher it the following way: he cut $x$ characters from the start of his password and from the end of it ($x$ can be $0$, and $2x$ is strictly less than the password length). He obtained 3 \textbf{\underline{parts of the password}}. Let's call it $prefix$, $middle$ and $suffix$ correspondingly, both $prefix$ and $suffix$ having equal length and $middle$ always having odd length. From these parts he made a string $A + prefix + B + middle + C + suffix$, where $A$, $B$ and $C$ are some (possibly empty) strings invented by Copa, and «$ + $» means concatenation. Many years have passed, and just yesterday the king Copa found the piece of paper where his ciphered password was written. The password, as well as the strings $A$, $B$ and $C$, was completely forgotten by Copa, so he asks you to find a password of maximum possible length, which could be invented, ciphered and written by Copa.
Scheme of the author solution The author solution has the following scheme. Let's brute over each possible position $pos$ of the center of the middle part (the part that must be palindrome by problem statement). Then let's take as a $middle$ the maximum palindrome among all centered in the position $pos$. After that we have to take as $prefix$ and $suffix$ such maximum-sized substrings, which satisfy all problem constraints, and don't intersect with medium part. After we do these calculations for each possible position $pos$, the answer to the problem will be just maximum among answers found on each step. Efficient Implementation In fact, the problem consists of two sub-problems: First, it's a search for a maximum-length palindrome, having its center in the given position $pos$. We can calculate these answers in $O(n)$ with Manacher's algorithm, which is described on my site (unfortunately, the article is only in Russian, so you have to use Google Translator or something like this). Alternatively you can calculate this "palindromic array" using binary search and, for example, hashes or suffix array: let's search for maximum palindrome length using binary search, then inside the binary search we have to compare for equivalence two substrings of the given string, which can be done in O(1) using hashes or calculated suffix array. Second, it's a search for maximum length and corresponding positions for $prefix$ and $suffix$ parts, not intersecting the given substring $[l;r]$. Let's look at lengths $sufflen$ of suffix $suffix$ in order of their increase, then for each fixed $sufflen$ obviously it is the best to look only at first occurence of string $prefix = reverse(suffix)$. Thereby, by increasing the length $sufflen$, we can move the corresponding $prefix$ only to the right, not to the left. Designating by $lpos[sufflen]$ the position of first occurence of string $reverse(suffix(sufflen))$ in the given string, we get that these $lpos$ values are non-decreasing. It will be more comfortable to introduce another array $rpos[len] = lpos[len] + len - 1$ - end-position of occurence of this suffix (obviously these values will strictly increase). So, if we knew the values of the array $lpos$ (or, more convenient, of the array $rpos$), then in the main solution (in the place, where after selecting maximum in $pos$ palindrome we have to search for maximum appropriate $prefix$ and $suffix$) we can use binary search over the length $sufflen$. Moreover, we can just precalculate answers to each of query of this form, and after that we'll answer to each query in $O(1)$. The last thing is to learn how to build $lpos$ array - array of positions of first occurences of reversed suffixes. For example, this can be done using hashes or suffix array. If we've calculated the value $lpos[k]$, let's learn how to calculate $lpos[k + 1]$. If the substring $s.substr(lpos[k], k + 1)$ equals to s-th suffix of length $k + 1$, then $lpos[k + 1] = lpos[k]$. In the other case, we try to increase $lpos[k + 1]$ by one, and again do the comparison, and so on. Comparison of any two substrings can be done in $O(1)$ using hashes or suffix array. Of course, total time to build $lpos$ array will be then $O(n)$ - because there won't be more than $n$ increases (and string comparisons) during the whole algorithm. Another approach to building $lpos$ array is to use prefixe-function. For this, let's make a string reverse(s) + # + s, and if in some point of the right half of the string the value of the prefix function equaled to $k$, then let's assign $lpos[k] =$ this position (if, of course, this $lpos[k]$ haven't yet been assigned before - because we have to find only first occurences). Finally, it's rather easy to get $O(n)$ solution of this problem using rather famous approaches: hashes, suffix array, prefix-function and palindromic array. $O(n\log n)$-solution is somewhat easier, - it is based on binary search (for building palindromic array and for answering the queries) and, for example, hashes (for comparison of two substrings). Proof The only non-obvious thing is why after we've fixed the position $pos$ (we remind it's a position of middle of central part of $middle$), - after that we can greedily take the maximum palindrome with center in it. Let's suppose the contrary: suppose it was better not to take the maximum palindrome centered in $pos$, but to take some smaller palindrome centered here. Look what happens when we decrease a length of palindrome by two (by one from each end): we loose two symbols in $middle$, but instead we get more "freedom" for $prefix$ and $suffix$ parts. But for both of them their $freedom$ increased only by one: $prefix$ gained one symbol after the end, and $suffix$ - one symbol before this beginning. So, taking into account the monotonic increase of $rpos$, we see that $prefix$ and $suffix$ could increase only by one, not more. Summarizing this discussion, we can say that after decreasing the $middle$ part we loose two symbols, and gain maximum two symbols. That's why there is no need in decreasing the $middle$ part, we can always select it as the maximum-sized palindrome. Another approach Let's iterate over each suffix length, and after we've fixed some suffix length, we have to find maximum-sized palindrome between the $suffix$ and the found $prefix$ (position of the $prefix$ still has to be found, just like in the previous solution). First idea is to use some greedy (similar to described above): take maximum-sized palindrome with center between $prefix$ and $suffix$, and "cut" it down, in order to fit between the $prefix$ and $suffix$. It's wrong: there are tests, where after cutting the maximum palindrome becomes very small, so after cutting down it's better to choose another palindrome. But we can cope with this using the following approach: let's find the length of $middle$ part using binary search. To do this, we have to answer the following queries: "is there a palindrome of length at least $x$ among all palindromes centered between $l$ and $r$". I.e. given $x$, we should answer, is there a number greater that or equal to $x$ in the segment $[l + x;r - x]$ (I suppose that $x$ is a half of the length of palindrome). We can answer to these maximum queries using segment tree in $O(\log n)$, so the total solution is $O(n\log^{2}n)$. Alternatively we can use sparse-table to reach $O(n\log n)$ asymptotics (sparse-table is a table where for each position $i$ and power of two $j$ the answer for segment $[i;i + j - 1]$ is precalculated). This can be done using segment tree, built over the palindromic array (the palindromic array should be calculated, as described in the previous solution).
[ "binary search", "constructive algorithms", "data structures", "greedy", "hashing", "strings" ]
2,800
null
32
A
Reconnaissance
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most $d$ centimeters. Captain Bob has $n$ soldiers in his detachment. Their heights are $a_{1}, a_{2}, ..., a_{n}$ centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment. Ways $(1, 2)$ and $(2, 1)$ should be regarded as different.
Problem A is quite straight-forward. You can simply enumerate all pairs using two for loops since N is not greater than 1000. Or you can sort the list and for every Ai, find the first Aj such that Aj-Ai>d in the range [i+1,N] using binary search.
[ "brute force" ]
800
null
32
B
Borze
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Problem B doesn't need an array at all. You can consume a single character at a time using getchar and then output a '0' if the character is '.' or consume another character to determine whether to output '1' or '2' otherwise.
[ "expression parsing", "implementation" ]
800
null
32
C
Flea
It is known that fleas in Berland can jump only vertically and horizontally, and the length of the jump is always equal to $s$ centimeters. A flea has found herself at the center of some cell of the checked board of the size $n × m$ centimeters (each cell is $1 × 1$ centimeters). She can jump as she wishes for an arbitrary number of times, she can even visit a cell more than once. The only restriction is that she cannot jump out of the board. The flea can count the amount of cells that she can reach from the starting position $(x, y)$. Let's denote this amount by $d_{x, y}$. Your task is to find the number of such starting positions $(x, y)$, which have the maximum possible value of $d_{x, y}$.
Problem C is a little tricky. Two cells are reachable from each other if and only if their horizontal or vertical distance is exactly S if they are on the same row or column, which is identical to the property that their indexes of one dimension is the same while those of the other are congruent modulo S. So you are to count the number of remainders modulo S whose occurrence is more frequent than others, which equals N%S when S divides N or N when not for rows. The number of such occurrences is the ceiling of N/S, the smallest integer no smaller than N/S. Multiplying the product of these two numbers for rows and that of the other two for columns together gives the answer. I failed the test of this problem for a silly typing error.
[ "math" ]
1,700
null
32
D
Constellation
A star map in Berland is a checked field $n × m$ squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer $x$ (\underline{radius of the constellation}) the following is true: - the 2nd is on the same vertical line as the 1st, but $x$ squares up - the 3rd is on the same vertical line as the 1st, but $x$ squares down - the 4th is on the same horizontal line as the 1st, but $x$ squares left - the 5th is on the same horizontal line as the 1st, but $x$ squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal — the one, whose central star if higher than the central star of the other one; if their central stars are at the same level — the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index $k$ by the given Berland's star map.
Problem D requires you to scan the map multiple times with increasing radii.
[ "implementation" ]
1,600
null
33
A
What is for dinner?
In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing". For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap). It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again. Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative. As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner. We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.
The solution of the problem is rather trivial. It was needed to make an array, where for each row of teeth the value of residual viability of the sickest thooth in this row would have kept (sickest tooth in the row is called the one with the lowest residual viability). Thus we define for each row of teeth the maximum number of crucians, which Valery able to eat, using this row (Valeria can not eat more crucians, because the residual viability of the sickest tooth will become negative). Knowing these values, you just need to sum them and to give the minimum of the sum and total amount of crucians in Valerie's portion for dinner as answer.
[ "greedy", "implementation" ]
1,200
null
33
C
Wonderful Randomized Sum
Learn, learn and learn again — Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite that Valera is one of the best students, he failed to manage with the new homework. That's why he asks for your help. He has the following task. A sequence of $n$ numbers is given. A prefix of a sequence is the part of the sequence (possibly empty), taken from the start of the sequence. A suffix of a sequence is the part of the sequence (possibly empty), taken from the end of the sequence. It is allowed to sequentially make two operations with the sequence. The first operation is to take some prefix of the sequence and multiply all numbers in this prefix by $ - 1$. The second operation is to take some suffix and multiply all numbers in it by $ - 1$. The chosen prefix and suffix may intersect. What is the maximum total sum of the sequence that can be obtained by applying the described operations?
This problem can be solved in linear time, using the following idea: 1. If desired prefix and suffix intersect, then their common part is remaining with the initial sign and therefore, this case is equivalent to the case when we take the same suffix and prefix, but without their common part: (s1 [s2 )s3 ] is equal to (s1)s2[s3] (s1,s2,s3 - some subsequences). 2. Let the sum of elements A1 .. An be equal to S. Then when inverting signs we get -A1, -A2 .. -An, and the sum is thereafter changed to -S, i.e. sum of elements on the segment will just change its' sign when inverting the whole segment's signs. 3. One can consider the initial problem as follows: we have to choose a consecutive subsequence (the part of the initial sequence, remaining between suffix and prefix), and invert all the numbers remaining out of it. Considering the sum of the whole sequence be S, and the sum of the target subsequence as S1 , the total sum will be equal to -(S-S1) + S1 = 2*S1 - S - this is the value, we want to get. S is a constant, therefore to maximize this value, we just have to maximize S1, i.e. find a consecutive subsequence of the initial sequence that has the biggest sum, and this can be done in linear as follows: mx = 0; for(i=0;i<n;++i) { sum += a[i]; if(sum < 0) sum = 0; mx = max(mx, sum); }
[ "greedy" ]
1,800
null
33
D
Knights
Berland is facing dark times again. The army of evil lord Van de Mart is going to conquer the whole kingdom. To the council of war called by the Berland's king Valery the Severe came $n$ knights. After long discussions it became clear that the kingdom has exactly $n$ control points (if the enemy conquers at least one of these points, the war is lost) and each knight will occupy one of these points. Berland is divided into $m + 1$ regions with $m$ fences, and the only way to get from one region to another is to climb over the fence. Each fence is a circle on a plane, no two fences have common points, and no control point is on the fence. You are given $k$ pairs of numbers $a_{i}$, $b_{i}$. For each pair you have to find out: how many fences a knight from control point with index $a_{i}$ has to climb over to reach control point $b_{i}$ (in case when Van de Mart attacks control point $b_{i}$ first). As each knight rides a horse (it is very difficult to throw a horse over a fence), you are to find out for each pair the minimum amount of fences to climb over.
Denote the number of fences surrounding the control point number i through cnti. Also denote cntij - the number of fences surrounding point i and point j. Then the answer to the query (i, j) is cnti + cntj - cntij. Clearly, that we can calculate all the values cnti with time O(n * m). The problem is the fast computation of the values cntij. And then suggests two solutions: a simple and not very much. Simple is as follows: create for every point i a bitset, j-th is equal to 1 if the j-th fence surrounds the point number i. Then, obviously cntij = count(zi & zj), where count(a) - the number of ones in bitset a. Now another solution. Add another fence with a center at (0, 0) and infinite radius. We construct a graph whose vertices are the fences as follows: we draw an arc from i to j, if the i-th fence is a fence with the minimum radius surrounding the fence number j. Obviously we get a directed tree rooted at the fence of infinite radius. Also, for each control point will find idxi - number of the fence with minimum radius surrounding the i-th control point. Then cntij = distij + distji, where distij - distance from vertex i to the lowest common ancestor of verticex i ans j. With the implementation problems should not arise, because in the first solution could write bitset himself or use the standard bitset from STL (for those who write in C++), while in the second solution we could preprocess all the lca with time O(n2).
[ "geometry", "graphs", "shortest paths", "sortings" ]
2,000
null
33
E
Helper
It's unbelievable, but an exam period has started at the OhWord University. It's even more unbelievable, that Valera got all the tests before the exam period for excellent work during the term. As now he's free, he wants to earn money by solving problems for his groupmates. He's made a $list$ of subjects that he can help with. Having spoken with $n$ of his groupmates, Valera found out the following information about them: what subject each of them passes, time of the exam and sum of money that each person is ready to pay for Valera's help. Having this data, Valera's decided to draw up a timetable, according to which he will solve problems for his groupmates. For sure, Valera can't solve problems round the clock, that's why he's found for himself an optimum order of day and plans to stick to it during the whole exam period. Valera assigned time segments for sleep, breakfast, lunch and dinner. The rest of the time he can work. Obviously, Valera can help a student with some subject, only if this subject is on the $list$. It happened, that all the students, to whom Valera spoke, have different, but one-type problems, that's why Valera can solve any problem of subject $list_{i}$ in $t_{i}$ minutes. Moreover, if Valera starts working at some problem, he can break off only for sleep or meals, but he can't start a new problem, not having finished the current one. Having solved the problem, Valera can send it instantly to the corresponding student via the Internet. If this student's exam hasn't started yet, he can make a crib, use it to pass the exam successfully, and pay Valera the promised sum. Since Valera has little time, he asks you to write a program that finds the order of solving problems, which can bring Valera maximum profit.
To solve the problem, firstly, it was necessary to carefully read the input data and convert all the time specified in the format $day, hour, minute$ in a minute since the beginning of the session for convenience. This could be done by using formula $newTime = (day - 1) * 24 * 60 + hour * 60 + minute$. Secondly, it is necessary to count the number of free minutes for solving the problems, which Valera has throughout the session. In addition, for every free minute $j$ it is needed to determine $t_{j}$ --- number of this minute since the beginning of the session. Next, it is needed calculate the value of $deadline_{i}$ for each student --- the latest free minute since the beginning of the session that if Valerie has finished to perform the task at that moment, he will receive the promised sum from the respective student. Obviously, if Valerie will not be sleeping or eating at the moment of $i$-th student begin to pass the exam, then $deadline_{i}$ will be equal to a minute prior to the beginning of the exam, else $deadline_{i}$ will correspond to the latest free minute prior to sleeping or a meal. In addition, if the free minute from the beginning of the session doesn't exist or Valera can not help $i$-th student, than we define $deadline_{i}$ = -1 in this case. Then we will sort all the students in non-decreasing value of $deadline$ and use the method of dynamic programming. The two parameters $i$ --- amount of viewed students (i.e. those for which the problems is already solved) and $j$ --- the number of free minute, from which Valera can begin to perform tasks for the next student will be the states of "dynamics". The value of the "dynamics" will be the maximum profit that Valerie can get when he will reach the respective state. Obviously, there are two possible transition from state $i$, $j$: in the state $i + 1$, $j$ --- Valera will not solve the problems for the $i$-th student in this casein the state $i + 1$, $j + time[i]$ (where $time[i]$ is the time required for solving problems of $i$-th student) --- Valera will solve the problem for $i$-th student in this case, and he will get sum of money this student is ready to pay. However, such a transition is possible only if $t_{None}(j + time[i])$ does not exceed $deadline_{i}$. Once the value of dynamics for all possible values of $i$, $j$ will be counted, the answer to the problem will be a maximum of $n$-th row of the array (where $n$ --- the total number of students). In addition, you should use an additional array of ancestors and accurately convert the time back to the desired form to restore the answer.
[]
2,600
null
36
A
Extra-terrestrial Intelligence
Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for $n$ days in a row. Each of those $n$ days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.
This task is very easy, and I hope all of you have solved it. But let's talk about it. Let input sequence is named as $a$, and its length is $n$. Then let's save sequence $x_{1}, ..., x_{k}$ is increasing order - all of positions, where $a_{None} = '1'$. We must check if this sequence $x_{1}, ..., x_{k}$ is a arithmetic progression. We save variable $d = x_{2} - x_{1}$ and check: for all $1 \le i < k$, is "$d = x_{None} - x_{i}$" correct. If it's correct, output "YES", else "NO".
[ "implementation" ]
1,300
null
36
B
Fractal
Ever since Kalevitch, a famous Berland abstractionist, heard of fractals, he made them the main topic of his canvases. Every morning the artist takes a piece of graph paper and starts with making a model of his future canvas. He takes a square as big as $n × n$ squares and paints some of them black. Then he takes a clean square piece of paper and paints the fractal using the following algorithm: Step 1. The paper is divided into $n^{2}$ identical squares and some of them are painted black according to the model. Step 2. Every square that remains white is divided into $n^{2}$ smaller squares and some of them are painted black according to the model. Every following step repeats step 2. Unfortunately, this tiresome work demands too much time from the painting genius. Kalevitch has been dreaming of making the process automatic to move to making 3D or even 4D fractals.
In author's solution the fractal is built by a recursive function. Let ''a'' be a square $n^{k} \times n^{k}$ result matrix. Write the recursive function fractal(x, y, k) filling a square part of the matrix with an upper left corner in (x, y) and a length of the side $n^{k}$, drawing the fractal of depth $k$. In case k = 0 put ''.'' at the current position. Otherwise you have to divide the part of the matrix into $n^{2}$ square parts with size $n^{None} \times n^{None}$, and fill them according to the model. If the corresponding symbol in the model is ''*'', fill the square with symbols ''*'', otherwise execute fractal(x1, y1, k-1) for (x1, y1) being the coordinates of the upper left corner of the new square. kdalex offers a solution (http://codeforces.com/blog/entry/764), which is easier in implementation. Consider all positions (x, y). If for some $c = n^{d}$, $0 \le d < k$ the square ((x/c)%n, (y/c)%n) of the model is black then (x, y) must be black, otherwise it is white. It is easy to check that if the square ((x/c)%n, (y/c)%n) is black for d = k - 1 , then we have that the current position (x, y) is in the black square after the first step of the algorithm. If ((x/c)%n, (y/c)%n) is black for d = k - 2, it happens after the second step, etc.
[ "implementation" ]
1,600
null
36
C
Bowls
Once Petya was in such a good mood that he decided to help his mum with the washing-up. There were $n$ dirty bowls in the sink. From the geometrical point of view each bowl looks like a blunted cone. We can disregard the width of the walls and bottom. Petya puts the clean bowls one on another naturally, i. e. so that their vertical axes coincide (see the picture). You will be given the order in which Petya washes the bowls. Determine the height of the construction, i.e. the distance from the bottom of the lowest bowl to the top of the highest one.
Imagine that we have successfully processed first $i - 1$ bowls, i.e. we know height of the bottom $y_{j}$ for every bowl $j$ ($1 \le j < i$). Now we are going to place $i$-th bowl. For each $j$-th already placed bowl, we will calculate the relative height of the bottom of $i$-th bowl above the bottom of $j$-th bowl, assuming that there are no other bowls. Lets denote this value by $ \Delta _{None}$. It is obvious that height of the new bowl is equal to the maximal of the following values: $y_{i} = max(y_{j} + \Delta _{None})$. Now I will describe how to calculate $ \Delta _{None}$. Firstly, consider two trivial cases: I. $r_{i} \ge R_{j}$: bottom of $i$-th bowl rests on the top of $j$-th. Then $ \Delta _{None} = h_{j}$. II. $R_{i} \le r_{j}$: bottom of $i$-th bowl reaches the bottom of $j$-th. Then $ \Delta _{None} = 0$. Then there are three slightly more complicated cases. 1. $r_{i} > r_{j}$: bottom of $i$-th bowl gets stuck somewhere between the top and the bottom of $j$-th, touching it's sides. From the similarity of some triangles we get that $\Delta_{i,j}=\frac{r_{i}-r_{i}}{R_{j}-r_{j}}h_{j}$. 2. $R_{i} \le R_{j}$: top of $i$-th bowl gets stuck somewhere between the top and the bottom of $j$-th, touching it's sides. From the similarity of some triangles we get that $\Delta_{i,j}=\frac{R_{i-r_{i}}}{R_{i-r_{i}}}h_{j}-h_{i}$. 3. $R_{i} > R_{j}$: sides of $i$-th bowl touch the top of $j$-th in it's upper points. Then $\Delta_{i,j}=h_{j}-{\frac{R_{i-r_{i}}}{R_{i}-r_{i}}}h_{i}$. Note that, for example, cases 1 and 2 do not exclude each other, so the final value of $ \Delta _{None}$ is equal to the maximum of the values, computed in all three cases. Note that if the calculated value of $ \Delta _{None}$ is negative, the result should be 0. Thanks to adamax for pointing it.
[ "geometry", "implementation" ]
2,200
null
36
D
New Game with a Chess Piece
Petya and Vasya are inventing a new game that requires a rectangular board and one chess piece. At the beginning of the game the piece stands in the upper-left corner of the board. Two players move the piece in turns. Each turn the chess piece can be moved either one square to the right or one square down or jump $k$ squares diagonally down and to the right. The player who can’t move the piece loses. The guys haven’t yet thought what to call the game or the best size of the board for it. Your task is to write a program that can determine the outcome of the game depending on the board size.
In the problem we have a game on an acyclic graph. Positions in the game (vertices of the graph) are pairs (n, m), where n and m are distances from the current position of the piece to the bottom and to the rights borders of the board. For every position (n, m) there are at most three moves: (n - 1, m), (n, m - 1), (n - k, m - k). The graph is acyclic, because at each move the sum n+m strictly decreases. If the numbers n, m and k do not exeed, say, 1000, the problem is solved by easy dynamics on the acyclic graph, standard for such games. Let d(n, m) = 1, if the position (n, m) is winning, and d(n, m) = 0, if the position (n, m) is losing. The value of d(n, m) is calculated using the following considerations. If there exists a move from the current position to a losing one, then the current position is winning, otherwise it is losing. But conditions of the problem do not allow us to solve it by the standard dynamics. The solution is to implement the dynamics for small values of n and m and to find a pattern! For example, build the matrix of values d(n, m) for k = 2: 010101010101011010101010101001111111111111101101010101010110101010101010110111111111011011010101011011011010101001101101............ Consider the corner stripes in this picture. Start with a corner stripe with width 2 in the upper-left corner (the 'corner stripe' in this case is the set of squares with n <= 2 || m <= 2). Starting from the upper-left corner, we have a stripe with width 2 (k for k > 2) such that 0 and 1 alternate. That is no wonder, because in that stripe we cannot jump by k. Next we have a stripe of only 1, then there is a stripe with width k like the first one, but it is inverted (1 are changed by 0, and 0 by 1), then we have a stripe of 1, and then there is exactly the same stripe as the one in the very beginning! Since every next corner stripe depends only on the previous one with width k, we have the pattern: the following stripe of 1, the inverted stripe, the stripe of 1 again, etc. In fact we get d(n, m) = d(n - (2 k + 2), m - (2 k + 2)) for n, m > 2 k + 2. It yields formulas to calculate d(n, m) for every n and m. To understand given explanations more carefully, implement the dynamics and find the pattern yourself. There is also a tricky case k = 1. It yields to a bit different pattern:) Remark. I want to emphasize that we have not just found the pattern and made a shamanistic hypothesis that it will be repeated. We have proved this. The stripes will alternate further, because every next stripe is uniquely determined by the previous stripe with width k.
[ "games" ]
2,300
null
36
E
Two Paths
Once archaeologists found $m$ mysterious papers, each of which had a pair of integers written on them. Ancient people were known to like writing down the indexes of the roads they walked along, as «$a$ $b$» or «$b$ $a$», where $a, b$ are the indexes of two different cities joint by the road . It is also known that the mysterious papers are pages of two travel journals (those days a new journal was written for every new journey). During one journey the traveler could walk along one and the same road several times in one or several directions but in that case he wrote a new entry for each time in his journal. Besides, the archaeologists think that the direction the traveler took on a road had no effect upon the entry: the entry that looks like «$a$ $b$» could refer to the road from $a$ to $b$ as well as to the road from $b$ to $a$. The archaeologists want to put the pages in the right order and reconstruct the two travel paths but unfortunately, they are bad at programming. That’s where you come in. Go help them!
The problem is to divide edges of a graph into two groups forming two paths in the graph. Clearly, each path is contained in one connected component. So if the given graph has more than two connected components, the problem has no solution. The same we can say if the graph has more than four vertices of an odd degree. Indeed, each vertex in a path (even if the path contains some vertices more than once) have an even degree, exept the first vertex and the last vertex. So the union of two paths can contain no more than four odd vertices. Now consider the cases: 1. One connected component, no vertices of an odd degree. So we have an euler cycle, which can be divided into two paths. 2. One connected component, two odd vertices. The same with an euler path instead of euler cycle. There is a tricky case of a graph with only one edge, which cannot be divided into two nonempty paths. 3. One connected component, four odd vertices. The most interesting case. Connect two vertices of an odd degree by a dummy edge. You will get a graph with an euler path. Find the euler path and delete the dummy edge - you will get two paths. 4. Two connetced components, each having zero or two odd vertices. Two euler paths/cycles. 5. Two connected components, four odd vertices in one and no odd vertices in another. No solution.
[ "constructive algorithms", "dsu", "graphs", "implementation" ]
2,600
null
37
A
Towers
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.
The total number of towers is equal to number of different numbers in this set. To get the maximum height of the tower, it was possible to calculate for each length the number of bars with this length, and from these numbers is to choose the maximum.
[ "sortings" ]
1,000
null
37
B
Computer Game
Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place. While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level: 1) The boss has two parameters: $max$ — the initial amount of health and $reg$ — regeneration rate per second. 2) Every scroll also has two parameters: $pow_{i}$ — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than $pow_{i}$ percent of health the scroll cannot be used); and $dmg_{i}$ the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts $dmg_{i}$ of damage per second upon him until the end of the game. During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates $reg$ of health (at the same time he can’t have more than $max$ of health), then the player may use another scroll (no more than one per second). The boss is considered to be defeated if at the end of a second he has nonpositive ($ ≤ 0$) amount of health. Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.
Constraints in the problem allows us to solve it this way: we keep the current number of health from the boss, and current summary damage from used scrolls per second. At the next step, we choose which scrolls we can use in the current second. Of all these, we find the scroll, which causes the most damage, and apply it. If at some point we could not use any of the scrolls, and the current damage in one second does not exceed regeneration, we deduce that there are no answers. Otherwise, continue to iterate the algorithm until the number hit points will be nonnegative.
[ "greedy", "implementation" ]
1,800
null