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 ⌀ |
|---|---|---|---|---|---|---|---|
37 | C | Old Berland Language | Berland scientists know that the Old Berland language had exactly $n$ words. Those words had lengths of $l_{1}, l_{2}, ..., l_{n}$ letters. Every word consisted of two letters, $0$ and $1$. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand e... | One of the easiest to understand solutions of this problem is as follows: sort the words in ascending order of length, while remembering their positions in the source list. We will consistently build our set, starting with the short strings: strings of length one can only be strings "0" and "1". If the number of words ... | [
"data structures",
"greedy",
"trees"
] | 1,900 | null |
37 | D | Lesson Timetable | When Petya has free from computer games time, he attends university classes. Every day the lessons on Petya’s faculty consist of two double classes. The floor where the lessons take place is a long corridor with $M$ classrooms numbered from $1$ to $M$, situated along it.
All the students of Petya’s year are divided in... | This problem is solved by dynamic programming: state of dynamics will be a pair of numbers - the number of current room and number of groups which have first lesson in the room with a number not exceeding the current and for which the second room is not defined yet. For each state check all possible number of groups fo... | [
"combinatorics",
"dp",
"math"
] | 2,300 | null |
37 | E | Trial for Chief | Having unraveled the Berland Dictionary, the scientists managed to read the notes of the chroniclers of that time. For example, they learned how the chief of the ancient Berland tribe was chosen.
As soon as enough pretenders was picked, the following test took place among them: the chief of the tribe took a slab divid... | First, we construct the following graph: each cell we associate a vertex of the same color as the cell itself. Between neighboring cells hold an edge of weight 0, if the cells share the same color and weight of 1, if different. Now, for each cell count the shortest distance from it to the most distant black cell (denot... | [
"graphs",
"greedy",
"shortest paths"
] | 2,600 | null |
39 | A | C*++ Calculations | C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this ($expression$ is the main term):
- $expression$... | To get the maximal possible result you have just to sort summands in non-decreasing order by coefficients (counting coefficients with preceeding signs + and -). You should not pay attention to 'a++' or '++a'! The question is: why is it true? First, consider an expression with only 'a++'. Then our assertion is obvious: ... | [
"expression parsing",
"greedy"
] | 2,000 | null |
39 | B | Company Income Growth | Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since $2001$ (the year of its founding) till now. Petya knows that in $2001$ the company income amounted to $a_{1}$ billion bourles, in $2002$ — to $a_{2}$ billion, ..., and in the curre... | For this problem, the greedy solution is acceptable. Process given numbers consequently until $1$ is found. Then continue to process searching for $2$, then for $3$, etc. | [
"greedy"
] | 1,300 | null |
39 | C | Moon Craters | There are lots of theories concerning the origin of moon craters. Most scientists stick to the meteorite theory, which says that the craters were formed as a result of celestial bodies colliding with the Moon. The other version is that the craters were parts of volcanoes.
An extraterrestrial intelligence research spec... | The authors solution takes $O(n^{2})$ time and $O(n^{2})$ memory. Solutions with $O(n^{2}\log{n})$ time and $O(n)$ memory are also acceptable. Let us reformulate the problem. Given a set of segments on a line, and the task is to find the largest subset such that segments in it don't intersect ``partially''. Two segment... | [
"dp",
"sortings"
] | 2,100 | null |
39 | D | Cubical Planet | You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points $(0, 0, 0)$ and $(1, 1, 1)$. Two flies live on the planet. At the mom... | The flies can NOT see each other iff they are in opposite vertices. You may use multiple ways to check this. For instance, you can check the Manhattan distance $|x_{1} - x_{2}| + |y_{1} - y_{2}| + |z_{1} - z_{2}| = 3$ or the Euclidian distance ${\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}+(z_{1}-z_{2})^{2}}}={\sqrt{3}}$.... | [
"math"
] | 1,100 | null |
39 | E | What Has Dirichlet Got to Do with That? | You all know the Dirichlet principle, the point of which is that if $n$ boxes have no less than $n + 1$ items, that leads to the existence of a box in which there are at least two items.
Having heard of that principle, but having not mastered the technique of logical thinking, 8 year olds Stas and Masha invented a gam... | The number of ways to put $b$ items into $a$ boxes is, of course, $a^{b}$. So we have an acyclic game for two players with positions $(a, b)$ for which $a^{b} < n$. Unfortunatly, there exists an infinite number of such positions: $a = 1$, $b$ is any. But in this case, if $2^{b} \ge n$, it is a draw position, because ... | [
"dp",
"games"
] | 2,000 | null |
39 | F | Pacifist frogs | Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.
One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from $1$ to... | The simple modelling of frog's jumps works too long, because $n$ can be $10^{9}$. The right solution is to count for each frog a number of smashed mosquitoes by checking divisibility of numbers of hills with mosquitoes by $d_{i}$. | [
"implementation"
] | 1,300 | null |
39 | G | Inverse Function | Petya wrote a programme on C++ that calculated a very interesting function $f(n)$. Petya ran the program with a certain value of $n$ and went to the kitchen to have some tea. The history has no records concerning how long the program had been working. By the time Petya returned, it had completed the calculations and ha... | What can I say about problem G? You should parse a given function and calculate its value for all values of $n$. Of course, it is impossible to do it just implementing the recursion, because this can work too long (see example with Fibonacci sequence). So you should use dynamic programming. | [
"implementation"
] | 2,400 | null |
39 | H | Multiplication Table | Petya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action — multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn... | You have to calculate all products $i * j$, and output them in the system of notations with radix $k$. | [
"implementation"
] | 1,300 | null |
39 | I | Tram | In a Berland city S*** there is a tram engine house and only one tram. Three people work in the house — the tram driver, the conductor and the head of the engine house. The tram used to leave the engine house every morning and drove along his loop route. The tram needed exactly $c$ minutes to complete the route. The he... | Consider only the part of the graph reachable from $1$. The task is to find the largest number $t$, such that a chosen set of vertices is reachable only at moments divisible by $t$. Suppose we have built such a set $S_{0}$. Look at sets $S_{1}$, $S_{2}$, ..., $S_{None}$ of all vertices reachable at moments having remai... | [] | 2,500 | null |
39 | J | Spelling Check | Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he d... | The simplest solution is to find two numbers $l$ and $r$ - the length of the longest common prefix and the length of the longest common suffix of two strings, respectively. If $l + 1 < n - r$ then there is no solution. Here $n$ is the length of the first string. Otherwise we should output positions from $max(n - r, 1)$... | [
"hashing",
"implementation",
"strings"
] | 1,500 | null |
39 | K | Testing | You take part in the testing of new weapon. For the testing a polygon was created. The polygon is a rectangular field $n × m$ in size, divided into unit squares $1 × 1$ in size. The polygon contains $k$ objects, each of which is a rectangle with sides, parallel to the polygon sides and entirely occupying several unit s... | Problem K has a great number of different solutions, so I'm surprised that there was a lack of them during the contest. Solutions with time $O(k^{4})$ and even some $O(k^{5})$ solutions with optimization were acceptable, but KADR describes even better solution in $O(k^{3})$ (http://codeforces.com/blog/entry/793). Here ... | [] | 2,600 | null |
41 | A | Translation | The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a Berlandish word differs from a Birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | Many languages have built-in reverse() function for strings. we can reverse one of the strings and check if it's equal to the other one , or we can check it manually. I prefer the second. | [
"implementation",
"strings"
] | 800 | using System;
namespace Iran
{
class Amir
{
public static void Main()
{
string a=Console.ReadLine();
string b=Console.ReadLine();
bool ok=true;
if(a.Length!=b.Length)
... |
41 | B | Martian Dollar | One day Vasya got hold of information on the Martian dollar course in bourles for the next $n$ days. The buying prices and the selling prices for one dollar on day $i$ are the same and are equal to $a_{i}$. Vasya has $b$ bourles. He can buy a certain number of dollars and then sell it no more than once in $n$ days. Acc... | Since number of days is very small ($2 \times 10^{3}$) we can just iterate over all possibilities of buy-day and sell-day. This will take $ \theta (n^{2})$ time which is OK. | [
"brute force"
] | 1,400 | using System;
namespace Iran
{
class Amir
{
public static void Main()
{
string[] input=Console.ReadLine().Split(' ');
int n=int.Parse(input[0]);
int b=int.Parse(input[1]);
int ... |
41 | C | Email address | Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([email protected]).
It is known that a proper email address contains only such symbols ... | The first letter of the input string can not be part of an "at" or a "dot" so we start from the second character. Greedily put "." wherever you reached "dot" and put "@" the first time you reached "at". This will take $ \theta (n)$ time , where $n$ is the length of input | [
"expression parsing",
"implementation"
] | 1,300 | #include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string input;
cin>>input;
string made=input.substr(0,1);
bool at=false;
for(int i=1;i<input.length();)
{
if(input.substr(i,3)=="dot"&&i+3!=input.length())
... |
41 | D | Pawn | On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having c... | For each cell of the table store $k + 1$ values. Where $i$th value is the maximum number of peas the pawn can take while he is at that cell and this number mod $k + 1$ is $i$. This makes a $O(n^{2} \times m \times k)$ dynamic programming which fits perfectly in the time. | [
"dp"
] | 1,900 | null |
41 | E | 3-cycles | During a recent research Berland scientists found out that there were $n$ cities in Ancient Berland, joined by two-way paths. Any two cities are joined by no more than one path. No path joins a city with itself. According to a well-known tradition, the road network was built so that it would be impossible to choose thr... | The road map with most edges is a complete bipartite graph with equal number of vertices on each side. (Prove it by yourself :D ). We can make such a graph by putting the first $\left\lfloor{\frac{n}{2}}\right\rfloor$ vertices on one side and the other $\textstyle\left[{\frac{n}{2}}\right]$ on the other side.For sure ,... | [
"constructive algorithms",
"graphs",
"greedy"
] | 1,900 | #include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
if(n%2==0)
cout<<n/2*n/2<<endl;
else
cout<<n/2*(n+1)/2<<endl;
for(int i=1;i<=n/2;i++)
for(int j=n/2+1;j<=n;j++)
cout<<i<<" "<<j<<endl;
... |
42 | A | Guilty --- to the kitchen! | It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills.
According to the borscht recipe it consists of $n$ ingredients that have to be mixed in prop... | Let us reformulate the statement: we need to find the maximum possible value of x (mentioned in the statement) so that the amount of each ingredient will be enough. Clearly, such x equals min(b_i / a_i). Now it suffices to take minimum of the two values: soup volume we gained and the volume of the pan. | [
"greedy",
"implementation"
] | 1,400 | null |
42 | B | Game of chess unfinished | Once Volodya was at the museum and saw a regular chessboard as a museum piece. And there were only four chess pieces on it: two white rooks, a white king and a black king. "Aha, blacks certainly didn't win!", — Volodya said and was right for sure. And your task is to say whether whites had won or not.
Pieces on the ch... | In this problem you are to check exactly what the statement says: if the king's position and all the positions reachable by him in one turn are "beaten", - that's a mate. Thus, we have to determine "beaten" positions correctly. Let us remove the black king from the chessboard, leave the positions of the rooks "unbeaten... | [
"implementation"
] | 1,700 | null |
42 | C | Safe cracking | Right now you are to solve a very, very simple problem — to crack the safe. Four positive integers stand one by one on a circle protecting the safe. You know that to unlock this striking safe you have to make all four numbers equal to one. Operations are as follows: you may choose two adjacent numbers and increase both... | The answer in this problem is always affirmative, which means it is always possible to make all the numbers equal to one. Greedy approach (here we somehow make two adjacent numbers even and then divide them by two) leads the sum of numbers to become less or equal to six in logarithmic (and certainly less than 1000) num... | [
"brute force",
"constructive algorithms"
] | 2,200 | null |
42 | D | Strange town | Volodya has recently visited a very odd town. There are $N$ tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing ... | Let us associate some numbers a_i with the vertices of the graph. If, for each edge, we assign it the sum of its endpoints' numbers, then the sum of prices along arbitrary hamiltonian cycle will be equal to the doubled sum of a_i. Therefore, it suffices us to devise such numbers a_i so that their pairwise sums will be ... | [
"constructive algorithms",
"math"
] | 2,300 | null |
42 | E | Baldman and the military | Baldman is a warp master. He possesses a unique ability — creating wormholes! Given two positions in space, Baldman can make a wormhole which makes it possible to move between them in both directions. Unfortunately, such operation isn't free for Baldman: each created wormhole makes him lose plenty of hair from his head... | First note that a valid graph of wormholes is either connected or consists of two connectivity components with one exit in each. The proof is in the end of this text. Also note that the first option is never optimal because one edge can be removed to get the second option. Let's build a minimal spanning tree of the inp... | [
"dfs and similar",
"graphs",
"trees"
] | 2,700 | null |
43 | A | Football | One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are $n$ lines in that description each of which described one goal. E... | This is pretty obvious , you can store the two strings and how many times each of them occurred | [
"strings"
] | 1,000 | null |
43 | B | Letter | Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading $s_{1}$ and text $s_{2}$ that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them.... | For each of the upper or lower case letters , take care about how many times it appeared in each of the strings. if for a character x , repetitions of x in the second string is more than the first string , we can't make it , otherwise the answer is YES. | [
"implementation",
"strings"
] | 1,100 | null |
43 | C | Lucky Tickets | Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid a... | We all know that the remainder of a number when divided by 3 is equal to the remainder of sum of its digits when divided by three. So we can put all of input numbers in 3 sets based on their remainder by 3. Those with remainder 1 can be matched with those with remainder 2 and those with remainder 0 can be matched with ... | [
"greedy"
] | 1,300 | null |
43 | D | Journey | The territory of Berland is represented by a rectangular field $n × m$ in size. The king of Berland lives in the capital, located on the upper left square $(1, 1)$. The lower right square has coordinates $(n, m)$. One day the king decided to travel through the whole country and return back to the capital, having visite... | Actually we're looking for an Eulerian tour. I found it like this: If at least one of m and n was even do it like this figure: else do it like this and add a teleport from last square to the first: But there were really nice hacks as I studied them. like these two: 1 10 and 1 2 | [
"brute force",
"constructive algorithms",
"implementation"
] | 2,000 | null |
43 | E | Race | Today $s$ kilometer long auto race takes place in Berland. The track is represented by a straight line as long as $s$ kilometers. There are $n$ cars taking part in the race, all of them start simultaneously at the very beginning of the track. For every car is known its behavior — the system of segments on each of which... | Let's just take care about 2 cars and see how many times they change their position. This is easy. Then do this for all cars :D | [
"brute force",
"implementation",
"two pointers"
] | 2,300 | null |
44 | A | Indian Summer | Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked. | One of possible ways of solving the problem is to compare every leave with all taken before. If it matches one of them, than do not take it. Since the order of leaves is immaterial, you can just sort all the leaves (for example, as pairs of strings) and delete unique leaves. | [
"implementation"
] | 900 | null |
44 | B | Cola | To celebrate the opening of the Winter Computer School the organizers decided to buy in $n$ liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles $0.5$, $1$ and $2$ liters in volume. At that, there are exactly $a$ bottles $0.5$ in volume, $b$ one-liter bottle... | The problem is to find a number of triples (x, y, z), such that 0 <= x <= a, 0 <= y <= b, 0 <= z <= c and 0.5 * x + y + 2 * z = n. Trying all triples gets TL, but you can try all possible values of x and y, satisfying 0 <= x <= a, 0 <= y <= b. When x and y are fixed, z can be determined uniquely. So we get O(a*b) solut... | [
"implementation"
] | 1,500 | null |
44 | C | Holidays | School holidays come in Berland. The holidays are going to continue for $n$ days. The students of school №$N$ are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people a... | The easiest solution is to process all the days from 1 to n, and check for each day, that it is covered by exactly one segment $[a_{i}, b_{i}]$. If you find a day which is covered by less or more than one segment, output this day. | [
"implementation"
] | 1,300 | null |
44 | D | Hyperdrive | In a far away galaxy there are $n$ inhabited planets, numbered with numbers from $1$ to $n$. They are located at large distances from each other, that's why the communication between them was very difficult until on the planet number $1$ a hyperdrive was invented. As soon as this significant event took place, $n - 1$ s... | Let us call ships that were produced initially ''the ships of the first generation''. When a ship of the first generation reaches a planet, and new ships are build there, we call them ''ships of the second generation'', and so on. Let us prove that the first collision is between two ships of the second generation, movi... | [
"math"
] | 1,800 | null |
44 | E | Anfisa the Monkey | Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into $k$ lines not shorter than $a$ and not longer than $b$, for the text to resemble h... | There are multiple ways to split the string. One of them is to split it into parts of lengths n / k and n / k + 1, if n is not divisible by k. Here n is the length of the given string. If lengths of such parts are not less than a and not greater than b, the answer is found. Otherwise there is no solution. | [
"dp"
] | 1,400 | null |
44 | F | BerPaint | Anfisa the monkey got disappointed in word processors as they aren't good enough at reflecting all the range of her emotions, that's why she decided to switch to graphics editors. Having opened the BerPaint, she saw a white rectangle $W × H$ in size which can be painted on. First Anfisa learnt to navigate the drawing t... | Imagine that all segments were drawn. We will refer to these segments as to initial segments. Lets divide the rectangle of drawing into the set of regions and segments such that there are no points of the initial segments strictly inside any region, and new segments separate the regions. Note that new set of segments c... | [
"geometry",
"graphs"
] | 2,700 | null |
44 | G | Shooting Gallery | Berland amusement park shooting gallery is rightly acknowledged as one of the best in the world. Every day the country's best shooters master their skills there and the many visitors compete in clay pigeon shooting to win decent prizes. And the head of the park has recently decided to make an online version of the shoo... | Lets solve slightly different problem: for every target we will determine the shoot that hits it. Sort the targets in increasing order of their z-coordinate and process them in that order. Each target is processed as follows. Consider all shoots that potentially can hit it. It is obvious that all such shoots belong to ... | [
"data structures",
"implementation"
] | 2,500 | null |
44 | H | Phone Number | Alas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy.
The phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppose... | The answer may be rather large, because it grows exponentially with growth of n, but it fits int64. Indeed, there are 10 ways to choose the first digit, than 1 or 2 ways to choose the second one, 1 or 2 ways for the third one, and so on. So the number of ways doens't exceed $10 \cdot 2^{None}$. The problem can be solv... | [
"dp"
] | 1,700 | null |
44 | I | Toys | Little Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her $n$ toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still ... | In this problem we need to output all partitions of the given set into subsets in the order which is very similar to the Gray code. Lets denote each partition by a restricted growth string. For a restricted growth string $a_{1}a_{2}a_{n}$ holds that $a_{1} = 0$ and $a_{None} \le 1 + max(a_{1}, ..., a_{j})$ for $1 \l... | [
"brute force",
"combinatorics"
] | 2,300 | null |
44 | J | Triminoes | There are many interesting tasks on domino tilings. For example, an interesting fact is known. Let us take a standard chessboard ($8 × 8$) and cut exactly two squares out of it. It turns out that the resulting board can always be tiled using dominoes $1 × 2$, if the two cut out squares are of the same color, otherwise ... | First, if the tiling is possible, it is unique. Consider the most upper-left position (x, y) that is not cut out. If it is black, the tiling is impossible. If it is white, look at the next position (x, y + 1). If it is cut out, the only possible way to put a trimino is to put it vertically. Otherwise we must put a trim... | [
"constructive algorithms",
"greedy"
] | 2,000 | null |
46 | A | Ball Game | A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count.
The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from $1$ to $n$ clockwise and the child number $1$... | The solution of the problem based on modeling of the decribed process. It is important to perform a pass throw the beginning correctly. You can take the current number modulo n (and add 1), or you can subtract n every time the current number increases n. | [
"brute force",
"implementation"
] | 800 | null |
46 | B | T-shirts from Sponsor | One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not ... | Enumerate sizes of t-shirts by integers from 0 to 4. For each size we store the number of t-shirts of this size left. To process each participant, we need to determine the number of his preferable size. Then we iterate over all possible sizes and choose the most suitable one (with the nearest number) among the sizes wi... | [
"implementation"
] | 1,100 | null |
46 | C | Hamsters and Tigers | Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together... | First of all, count the number of hamsters in the sequence. Let it is h. Try positions where the sequence of hamsters will start, and for each position count the number of tigers in the segment of length h starting from the fixed position. These tigers should be swapped with hamsters in a number of swaps equal to the n... | [
"two pointers"
] | 1,600 | null |
46 | D | Parking Lot | Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as $L$ meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors ... | Lets keep a set of cars which are currently parked. In this problem it is not essential how to keep this set. For each car, store its length and position. To process a request of type 2, we need to find the car which should leave the parking and remove it from the set. To do this, we should enumerate the cars and get t... | [
"data structures",
"implementation"
] | 1,800 | null |
46 | E | Comb | Having endured all the hardships, Lara Croft finally found herself in a room with treasures. To her surprise she didn't find golden mountains there. Lara looked around and noticed on the floor a painted table $n × m$ panels in size with integers written on the panels. There also was a huge number of stones lying by the... | Denote the input matrix by $a$. Compute the partial sums in each row first: $s_{i,j}=\sum_{k=1}^{J}a_{i,k}$. All these sums can be easily computed in $O(nm)$. Then solve the task using dynamic programming. By $d_{None}$ denote the maximum sum of numbers that we can take from first $i$ rows, taking exactly $j$ numbers i... | [
"data structures",
"dp"
] | 1,900 | null |
46 | F | Hercule Poirot Problem | Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books.
You are not informed on what crime was committed, when and where the corpse was found and other details. We only... | First, note that all the described operations are invertible: opening/closing doors, moving from one room to another and exchanging keys. So we may perform such operations from the initial arrangement to get some arrangment A, and then perform some operations from the final arrangement to get the same arrangement A, in... | [
"dsu",
"graphs"
] | 2,300 | null |
46 | G | Emperor's Problem | It happened at the times of the Great Berland Empire. Once the Emperor dreamt that the Messenger from the gods ordered to build a temple whose base would be a convex polygon with $n$ angles. Next morning the Emperor gave the command to build a temple whose base was a regular polygon with $n$ angles. The temple was buil... | Note that the lengths of the sides can be $\sqrt{1}$, ${\sqrt{2}}$, ${\sqrt{4}}$, $\sqrt{5}$, and so on, i.e. the roots of integers, that can be represented as $a^{2} + b^{2}$. Generate a proper quantity of such numbers. Denote them $\sqrt{r_{1}}$, ${\sqrt{r}}_{2}$, ... In some cases we can take first $n$ such numbers ... | [
"geometry"
] | 2,500 | null |
47 | A | Triangular numbers | A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The $n$-th triangular number is the number of dots in a triangle with $n$ dots on a side. $T_{n}={\frac{n(n+1)}{2}}$. You can learn m... | Because of small constraints, just iterate $n$ from 1 to $T_{n}$ and check $T_{n}={\frac{n(n+1)}{2}}$ | [
"brute force",
"math"
] | 800 | null |
47 | B | Coins | One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the resul... | Let's consider a graph, where the letters $A$, $B$, $C$ are the vertexes and if $x < y$, then the edge $y - > x$ exists. After that let's perform topological sort. If a cycle was found during this operation, put "Impossible" and exit. Otherwise put the answer. Another approach is acceptable because of small constaints ... | [
"implementation"
] | 1,200 | null |
47 | C | Crossword | Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity ... | Let's iterate over all of $6! = 720$ permutations. For every permutation let's try to put the first 3 words horizontally, the others - vertically: hor[0], ver[0] - left-up hor[2], ver[2] - right-down hor[1]: (len(ver[0]) - 1, 0)ver[1]: (0, len(hor[0]) - 1) Now let's define N = len(ver[1]), M = len(hor[1]). A Conditions... | [
"implementation"
] | 2,000 | null |
47 | D | Safe | Vasya tries to break in a safe. He knows that a code consists of $n$ numbers, and every number is a 0 or a 1. Vasya has made $m$ attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so u... | Let's consider not the most efficient, but AC algorithm, with the complexity $O(mC_{n}^{5}log(C_{n}^{5}))$. Let's consider the 1 answer of the system: <number, v>. The amount of the variants of the password is $C_{n}^{v}$ - not very large number in constaints of the problem, you can simply generate this variants. Decla... | [
"brute force"
] | 2,200 | null |
47 | E | Cannon | Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the $Ox$ axis is ... | Let's consider an algorightm with complexity $O((n + m)log(n + m))$. Exclude from considiration every wall can't be achieved by canon: $x > v^{2} / g$ Because of $ \alpha < = \pi / 4$: Function $X_{max}( \alpha )$ is monotonous Function $Y( \alpha , x)$, when x is fixed, is monotonousSuch observation allows to assign... | [
"data structures",
"geometry",
"sortings"
] | 2,200 | null |
50 | A | Domino piling | You are given a rectangular board of $M × N$ squares. Also you are given an unlimited number of standard domino pieces of $2 × 1$ squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two ... | Answer is floor(N*M*0.5). Since there is N*M cells on the board and each domino covers exactly two of them we cannot place more for sure. Now let's show how to place exactly this number of dominoes. If N is even, then place M rows of N/2 dominoes and cover the whole board. Else N is odd, so cover N-1 row of the board a... | [
"greedy",
"math"
] | 800 | null |
50 | B | Choosing Symbol Pairs | There is a given string $S$ consisting of $N$ symbols. Your task is to find the number of ordered pairs of integers $i$ and $j$ such that
1. $1 ≤ i, j ≤ N$
2. $S[i] = S[j]$, that is the $i$-th symbol of string $S$ is equal to the $j$-th. | Of course you were expected to code solution which is not quadratic in time complexity. Iterate over the string and count how many times each char is used. Let Ki be the number of occurrences of char with ASCII-code i in the string S. Then answer is sum(Ki2). While coding the solution the following common mistakes were... | [
"strings"
] | 1,500 | null |
50 | C | Happy Farm 5 | The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows al... | You were asked to make all the cows strictly inside the interior of the route. Initially I planned to put "non-strict" there, but later I abandoned this idea because the answer for single point was really weird then=) The difference in solution is quite small. The answer for "strict" problem is always more than for "no... | [
"geometry"
] | 2,000 | null |
50 | D | Bombing | The commanding officers decided to drop a nuclear bomb on the enemy's forces. You are ordered to determine the power of the warhead that needs to be used.
The enemy has $N$ strategically important objects. Their positions are known due to the intelligence service. The aim of the strike is to deactivate at least $K$ im... | The problem statement looks intricate and aggressive. That's because the problem legend originates from civil defense classes in the university. Civil defense is such a discipline which for example teaches how to behave before and after nuclear attack... First of all we should notice that the bigger the warhead, the be... | [
"binary search",
"dp",
"probabilities"
] | 2,100 | null |
50 | E | Square Equation Roots | A schoolboy Petya studies square equations. The equations that are included in the school curriculum, usually look simple:
\[
x^{2} + 2bx + c = 0
\]
where $b$, $c$ are natural numbers.Petya noticed that some equations have two real roots, some of them have only one root and some equations don't have real roots at all... | Let D = b2-c be quarter of discriminant. The equation roots are -b-sqrt(D) and -b+sqrt(D). Thus there are two types of roots: irrational ones like x +- sqrt(y) and integer ones. We count the number of different roots separately for these types. Irrational roots are in form x+sqrt(y) (y is not square of integer). If two... | [
"math"
] | 2,300 | null |
53 | A | Autocomplete | Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list co... | In this problem you should read the statement and solve in any way. One of the most simple solutions is read string and last visited pages, sort (even bubble source - 1003 isn't a lot, 3rd power because we need 100 operations to compare two strings), and rundown pages. When we find good string, we should write it and e... | [
"implementation"
] | 1,100 | null |
53 | B | Blog Photo | One popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the $height / width$ quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 ($2^{x}$ for s... | The first thing we need to do is fix one side (which are power of two). Because there are two sides and copy-paste is great place for bugs it'll be better to make one more for from 1 to 2 and on the 2nd step swap w and h. It decreases amount of code. Now we know that h=2x. We need to find such w, that 0.8 <= h/w <= 1.2... | [
"binary search",
"implementation"
] | 1,700 | null |
53 | C | Little Frog | Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are $n$ mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For tha... | IMHO it's the second difficulty problem. If you cannot see solution just after you saw the statement, you can write brute-force solution (rundown all permutation and check), run it for n=10 and see beautiful answer. Answer is 1 n 2 (n-1) 3 (n-2) 4 (n-3) ... Let's define two pointers - l and r. In the beginning, the fir... | [
"constructive algorithms"
] | 1,200 | null |
53 | D | Physical Education | Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is the height of the $i$-th student in the line and $n$ is the number of ... | This problem is also very easy. The first thing we should learn is moving element from position x to position y (y < x). Let's move x to position x - 1 with one oblivious swap. Then to position x -2. And so on. Now we want to make a1=b1. Find in b element, that equals a1 and move it to the first position. Similarly we ... | [
"sortings"
] | 1,500 | null |
53 | E | Dead Ends | Life in Bertown has become hard. The city has too many roads and the government spends too much to maintain them. There are $n$ junctions and $m$ two way roads, at which one can get from each junction to any other one. The mayor wants to close some roads so that the number of roads left totaled to $n - 1$ roads and it ... | The first thing you should notice - - n <= 10. It means, that we have exponential solution and we can rundown some subsets. Solution is dynamic programming d[m][subm] - number of ways to make connected tree from subgraph m (it's a bit mask) with dead ends subm (it's also a bit mask). Answer is sum of d[2n-1][x], where ... | [
"bitmasks",
"dp"
] | 2,500 | null |
54 | C | First Digit Law | In the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law).
Having read about it on Codeforces, the Hedgeho... | Solution for this problem consists of two stages. First stage - counting the numbers with 1 as their first digit in the $[L;R]$ segment. Second stage - using this information (in fact, by given probabilities that $i$-th quantity will be good) solve the problem about $K$ percents. To solve the first sub-problem one can ... | [
"dp",
"math",
"probabilities"
] | 2,000 | null |
54 | D | Writing a Song | One of the Hedgehog and his friend's favorite entertainments is to take some sentence or a song and replace half of the words (sometimes even all of them) with each other's names.
The friend's birthday is approaching and the Hedgehog decided to make a special present to his friend: a very long song, where his name wil... | I'll describe here an author's solution for this problem. The solution is by a method of dynamic programming: the state is a pair $(pos, pref)$, where $pos$ - the position in the string built (it is between $0$ and $n$), and $pref$ - the current prefix of pattern $P$ (i.e. this is a number between $0$ and $length(P)$).... | [
"brute force",
"dp",
"strings"
] | 2,100 | null |
54 | E | Vacuum Сleaner | One winter evening the Hedgehog was relaxing at home in his cozy armchair and clicking through the TV channels. Stumbled on an issue of «TopShop», the Hedgehog was about to change the channel when all of a sudden he was stopped by an advertisement of a new wondrous invention.
Actually, a vacuum cleaner was advertised ... | The most important step on the way to solve this problem - is to understand that it's enough to consider only such rotations of the polygon, that one of its sides lies on the side of the room. Let's try to understand this fact. Suppose that the fact is wrong, and there exists such a position of vacuum cleaner, that nei... | [
"geometry"
] | 2,700 | null |
55 | A | Flea travel | A flea is sitting at one of the $n$ hassocks, arranged in a circle, at the moment. After minute number $k$ the flea jumps through $k - 1$ hassoсks (clockwise). For example, after the first minute the flea jumps to the neighboring hassock. You should answer: will the flea visit all the hassocks or not. We assume that fl... | This problem is solved by simple emulation. After $2n$ jumps flea returns to initial position, because $1 + 2 + 3 + ... + 2n = n(2n + 1)$ is divisible by n. Moreover, after that, jumps would be the same as in the beginning, because $2n$ is divisible by $n$. So it is just enough to emulate first $2n$ jumps.In fact one m... | [
"implementation",
"math"
] | 1,200 | null |
55 | B | Smallest number | Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers $a$, $b$, $c$, $d$ on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced... | One just needs to calculate all possible answers and find the minimum. For example one may run on a set of numbers, for all pairs of numbers apply next operation to that pair and recursively run on a new set of numbers. When only one number remains, compare it to the already obtained minimum, and change that minimum if... | [
"brute force"
] | 1,600 | null |
55 | C | Pie or die | Volodya and Vlad play the following game. There are $k$ pies at the cells of $n × m$ board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the bor... | Vladimir wins exactly when there is a pie with distance to the border not greater than 4. Indeed if there is such a pie, then Vladimir will move it to the border and then move it around the whole rim. Of course if there would be any chance to throw this pie from the board, Vladimir will use it. If he gets no such chanc... | [
"games"
] | 1,900 | null |
55 | D | Beautiful numbers | Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges. | In this problem one should answer the query: how many beautiful numbers are there in the interval from 1 to R. Clearly, to check whether a number is divisible by all its digits, it is sufficient to know the remainder of a division by the lcm of all possible digits (call this lcm M), that is M = 8 * 9 * 5 * 7 = 2520. Th... | [
"dp",
"number theory"
] | 2,500 | null |
55 | E | Very simple problem | You are given a convex polygon. Count, please, the number of triangles that contain a given point in the plane and their vertices are the vertices of the polygon. It is guaranteed, that the point doesn't lie on the sides and the diagonals of the polygon. | Let us solve this problem for every point P independently. We will show how to do this in linear time, that is, O(N). It seems that the most easy way to do this is to count the number of triangles not containing P (call them good), and then subtract this value from the total number of triangles. Consider triples of ver... | [
"geometry",
"two pointers"
] | 2,500 | null |
57 | A | Square Earth? | Meg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side $n$. T... | Since the restrictions were not so big you can offer many different solutions. For example, you can construct a graph with N * 4 vertices and use bfs. But there was a faster solution with complexity O(1): enumerate the integer points lying on the square, for example, as is shown below: Then finding the number of a poin... | [
"dfs and similar",
"greedy",
"implementation"
] | 1,300 | null |
57 | B | Martian Architecture | Chris the Rabbit found the traces of an ancient Martian civilization. The brave astronomer managed to see through a small telescope an architecture masterpiece — "A Road to the Sun". The building stands on cubical stones of the same size. The foundation divides the entire "road" into cells, into which the cubical stone... | Under the restrictions on the number of requests, you cannot iteratively add staircase. But the problem is simplified by the fact that the number of cells in which it was necessary to know the number of stones was no more than 100. That's why you can check for each "interesting" cell all the queries and calculate how m... | [
"implementation"
] | 1,600 | null |
57 | C | Array | Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of $n$, containing only integers from $1$ to $n$. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different bea... | First, let's count how many there are arrays in which each successive element starting from the second one is no less than the previous one. To do this quickly, let's take a piece of squared with height of one square and the length of N*2 - 1 square, then select N-1 squares and put crosses in them - let it encode some ... | [
"combinatorics",
"math"
] | 1,900 | null |
57 | D | Journey | Stewie the Rabbit explores a new parallel universe. This two dimensional universe has the shape of a rectangular grid, containing $n$ lines and $m$ columns. The universe is very small: one cell of the grid can only contain one particle. Each particle in this universe is either static or dynamic. Each static particle al... | Let's see, if there is no occupied cells, then it is not difficult to calculate the answer - the answer is a sum of Manhattan distances, taking into account the fact that the Manhattan distance can be divided: first we can calculate the distance of one coordinate and then of another one and then just to sum up, so the ... | [
"dp",
"math"
] | 2,500 | null |
57 | E | Chess | Brian the Rabbit adores chess. Not long ago he argued with Stewie the Rabbit that a knight is better than a king. To prove his point he tries to show that the knight is very fast but Stewie doesn't accept statements without evidence. He constructed an infinite chessboard for Brian, where he deleted several squares to a... | The task turned out to be very difficult as it was planned. First remove all the deleted cells - let's see how changes the number of accessible cells with the increase of the new moves. First, the changes do not appear stable, but at some point we see a figure which won't to change the form anymore and will only expand... | [
"math",
"shortest paths"
] | 3,000 | null |
59 | A | Word | Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | This was an extremely simple problem. Simply count the number of upper case latin letters. If that is strictly greater than number of lower case letters convert the word to upper case other wise convert it to lower case. Complexity: O(wordlength) | [
"implementation",
"strings"
] | 800 | null |
59 | B | Fortune Telling | Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces a... | For this problem all you need to do is store the smallest odd number of petals and also the sum of all the petals. It is quite obvious that only if the number of petals is odd the result would be "Loves". So if the sum is even print sum - smallest odd, otherwise print the sum. Complexity: O(n). | [
"implementation",
"number theory"
] | 1,200 | null |
59 | C | Title | Vasya has recently finished writing a book. Now he faces the problem of giving it the title. Vasya wants the title to be vague and mysterious for his book to be noticeable among others. That's why the title should be represented by a single word containing at least once each of the first $k$ Latin letters and not conta... | This was a very nice problem. My approach was to first flag all the letters which have already appeared. Notice, that we have to output the lexicographically smallest palindrome. So, start from the middle of the letter and iterate one side... If you get a '?' stop and check if the corresponding position on the other si... | [
"expression parsing"
] | 1,600 | #include <stdio.h>
#include <string.h>
int main()
{
int a[27], k, i, j, len, count = 0, first;
char t[110];
scanf(" %d %s", &k, t);
for(i = 0; i < k; i ++)
a[i] = 0;
len = strlen(t);
for(i = 0; i < len; i ++)
{
if(t[i] == '?')
... |
59 | D | Team Arrangement | Recently personal training sessions have finished in the Berland State University Olympiad Programmer Training Centre. By the results of these training sessions teams are composed for the oncoming team contest season. Each team consists of three people. All the students of the Centre possess numbers from $1$ to $3n$, a... | This was in my opinion was the toughest problem. However once you get the logic, its pretty obvious. However, it was a slightly challenging implementation for me as the structure of the data to be stored was sort of complex. The basic idea was simply that if we have to find the preference list of a number 'p' then two ... | [
"constructive algorithms",
"greedy",
"implementation"
] | 2,000 | null |
60 | A | Where Are My Flakes? | One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of $n$ boxes. The boxes stand in one row, they are numbered from $1$ to $n$ from the left to the right. The roommate left hints like "Hidden to the left... | Solution - $O(n^{2})$. We take phrase and parse it. Mark all cells, that obviously didn't match - $O(n)$. In the end we go through the array and count all unmarked cells. If 0 - we print "-1", else - amount of unmarked cells. | [
"implementation",
"two pointers"
] | 1,300 | null |
60 | B | Serial Time! | The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped $k × n × m$, that is, it has $k$ layers (the first layer is the upper... | Solution - $O(k \times n \times m)$. We start BFS from given point. Go from cell to all 6 directions. The answer - number of visited cells. | [
"dfs and similar",
"dsu"
] | 1,400 | null |
60 | C | Mushroom Strife | Pasha and Akim were making a forest map — the lawns were the graph's vertexes and the roads joining the lawns were its edges. They decided to encode the number of laughy mushrooms on every lawn in the following way: on every edge between two lawns they wrote two numbers, the greatest common divisor (GCD) and the least ... | Solution - $O(2^{7} \times n^{2})$. We can see, that in connected component - if we know 1 number - then we know all others in component, because in each pare we know minimal and maximal power of each primes. Because number of different primes in one number "$< = 1000000$" is less, than 7, we can look over all possib... | [
"brute force",
"dfs and similar"
] | 2,100 | null |
60 | D | Savior | Misha decided to help Pasha and Akim be friends again. He had a cunning plan — to destroy all the laughy mushrooms. He knows that the laughy mushrooms can easily burst when they laugh. Mushrooms grow on the lawns. There are $a[t]$ mushrooms on the $t$-th lawn.
Misha knows that the lawns where the mushrooms grow have a... | Solution - $O($max numebr$)$. We can notice, that each beautiful triplet has form - $(x^{2} - y^{2}, 2xy, x^{2} + y^{2})$. Now we can gen all such triples. For each triple, we watch - if we have more than 1 number in given set - we union them. How to gen all the triples? $x > y$. $2x y\leq m a x;\Rightarrow y\leq{\sqrt... | [
"brute force",
"dsu",
"math"
] | 2,500 | null |
60 | E | Mushroom Gnomes | Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighbori... | Solution - $O(n + log(xy))$. We can see, that after one minute the sum changes - it multiply on 3, and substract first and last elements of sequence. Because of that we can count of sum with help of power of matrix. What happens after sorting. First number stay on his place. On the last place - $F_{x}a_{n} + F_{None}a_... | [
"math",
"matrices"
] | 2,600 | null |
61 | A | Ultra-Fast Mathematician | Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum $10^{18}$ numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possib... | This was indeed the easiest problem. You just needed to XOR the given sequences. The only common mistake was removing initial 0s which led to "Wrong Answer" Common mistake in hacks which led to "Invalid Input" was forgetting that all lines in input ends with EOLN. | [
"implementation"
] | 800 | null |
61 | B | Hard Work | After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!
Some days before the contest, the teacher took a very simple-looking exam and all his $n$ students took part in the exam. The teach... | In this problem signs can be ignored in both initial and answer strings, so first we remove signs from initial strings. Then we make a list of the six possible concatenations of the 3 initial strings and convert all of them to lowercase.For checking an answer string , we remove the signs , convert it to lowercase and c... | [
"strings"
] | 1,300 | null |
61 | C | Capture Valerian | It's now $260$ AD. Shapur, being extremely smart, became the King of Persia. He is now called Shapur, His majesty King of kings of Iran and Aniran.
Recently the Romans declared war on Persia. They dreamed to occupy Armenia. In the recent war, the Romans were badly defeated. Now their senior army general, Philip is cap... | The code for converting decimal numbers to Roman was on Wikipedia , so I'm not going to explain it.Since we have the upper limit 1015 for all of our numbers , we can first convert them to decimal (and store the answer in a 64-bit integer) and then to the target base. For converting a number to decimal we first set the ... | [
"math"
] | 2,000 | null |
61 | D | Eternal Victory | Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all $n$ cities of Persia to find the best available mountain, but after the recent war he was too ... | This one has two different linear-time solutions. Greedy and dynamic programming. Greedy solution: You should stop at the city with maximum distance from the root (city number 1). So all roads are traversed twice except for the roads between the root and this city. Dynamic Programming: For each city i we declare patrol... | [
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"trees"
] | 1,800 | null |
61 | E | Enemy is weak | The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep".
Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.
In Shapur's opinion the weakness... | This one can be solved in O(nlgn) using a segment tree.First we convert all powers to numbers in range 0..n-1 to avoid working with segments as large as 109 in our segment tree. Then for each of the men we should find number of men who are placed before him and have more power let's call this gr[j]. When ever we reach ... | [
"data structures",
"trees"
] | 1,900 | null |
62 | A | A Student's Dream | Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them.
A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable profess... | There was a lot of troubles because of incorrect statement. Now I hope statement is ok. Let's solve it. =) If boy will goes to the left he will take her left hand with his right one and boy's left hand and girl's right hand will be unused. Situation is looks like the same if we swap them vice versa. So, we need to chec... | [
"greedy",
"math"
] | 1,300 | null |
62 | B | Tyndex.Brome | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!
The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac... | Let's define $p$ as total length of all potential addresses $c$. In this problem obvious solution has O($p \cdot k$) difficulty and it is getting a TLE verdict. Let's speed up it by next way: we will save all position of letters 'a', 'b', ..., 'z' in address entered by user $s$ separately in increasing order. After th... | [
"binary search",
"implementation"
] | 1,800 | null |
62 | C | Inquisition | In Medieval times existed the tradition of burning witches at steaks together with their pets, black cats. By the end of the 15-th century the population of black cats ceased to exist. The difficulty of the situation led to creating the EIC - the Emergency Inquisitory Commission.
The resolution #666 says that a white ... | All triangles are located strickly inside of square. It makes problem more simplify, because you don't need to check situations of touching sides. Let's save all segments of every triangle and cross them in pairs. There are many points at every segment - the results of crossing. Look at the every subsegment which do no... | [
"geometry",
"implementation",
"sortings"
] | 2,300 | null |
62 | D | Wormhouse | Arnie the Worm has finished eating an apple house yet again and decided to move. He made up his mind on the plan, the way the rooms are located and how they are joined by corridors. He numbered all the rooms from $1$ to $n$. All the corridors are bidirectional.
Arnie wants the new house to look just like the previous ... | In this problem you asks to find lexicographically next euler cycle or say that there is no way. Let's solve this problem backwards. We should repeat way of Arnie. Now it needs to rollback every his step and add edges for empty graph (graph without edges). Let's assume we had rollback edge from some vertix $x$ to verti... | [
"dfs and similar",
"graphs"
] | 2,300 | null |
62 | E | World Evil | As a result of Pinky and Brain's mysterious experiments in the Large Hadron Collider some portals or black holes opened to the parallel dimension. And the World Evil has crept to the veil between their world and ours. Brain quickly evaluated the situation and he understood that the more evil tentacles creep out and bec... | In this problem you were to find the maximal flow in network with a cyllinder structure. The dynamic solution with complexity $O(mn2^{n})$ was considered.It's well known that the maximal flow is equal to value of the minimal cut. Also all the sources must belong to one part of the cut and all the drains --- to the othe... | [
"dp",
"flows"
] | 2,700 | null |
63 | A | Sinking Ship | The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All $n$ crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to $n$) and await further instructions. However, one should evacuate the crew properly, in a stri... | This problem can be easily solved with the following algorithm. First, read names ans statuses of all crew members into an array. Next, iterate over the entire array 4 times. In the first pass output names of rats. In the second pass output names of women and children. In the third pass output names of men. Finally, in... | [
"implementation",
"sortings",
"strings"
] | 900 | null |
63 | B | Settlers' Training | In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly $n$ soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either i... | In this problem you can simulate the process of soliders training until there is at least one soldier with rank less than $k$. We iterate over the array of ranks and increase by one the ranks of every soldier who is the last in his group (if he has the rank less than $k$, of course). This operation preserves non-decrea... | [
"implementation"
] | 1,200 | null |
63 | C | Bulls and Cows | The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all... | Consider all of the numbers which the thinker may thinks of. Next we select from them ones which fit all thinker's answers. If there is exactly one such number, output it. If there are no such numbers, output "Incorrect data". Otherwise output "Need more data". The complexity of this solution is $O(10^{4} \times n)$.... | [
"brute force",
"implementation"
] | 1,700 | null |
63 | D | Dividing Island | A revolution took place on the Buka Island. New government replaced the old one. The new government includes $n$ parties and each of them is entitled to some part of the island according to their contribution to the revolution. However, they can't divide the island.
The island can be conventionally represented as two ... | Main idea of the solution is walk the island around with a "snake". You can do it, for example, this way: or this way: Then we can just "cut" the snake into the pieces of appropriate length. It is clear that all the resulting figures will be connected. The complexity of this solution is $O(max(B, D) \times (A + C))$. | [
"constructive algorithms"
] | 1,900 | null |
63 | E | Sweets Game | Karlsson has visited Lillebror again. They found a box of chocolates and a big whipped cream cake at Lillebror's place. Karlsson immediately suggested to divide the sweets fairly between Lillebror and himself. Specifically, to play together a game he has just invented with the chocolates. The winner will get the cake a... | Define a state as some layout of sweets in a box. We have to detrmine for every state whether it is winning or losing. The state is winning if you can do a acceptable move to a losing state. Otherwise it is losing. For example, the state corresponding to the empty box is losing because there are no moves from this stat... | [
"bitmasks",
"dfs and similar",
"dp",
"games",
"implementation"
] | 2,000 | null |
65 | A | Harry Potter and Three Spells | A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert $a$ grams of sand into $b$ grams of lead, the second one allows you to convert $c$ grams of lead into $d$ grams o... | Fist, consider the case when all the numbers are non-zero. You can take a*c*e grams of sand, turn them into b*c*e grams of lead, and them turn into b*d*e grams of gold, and them turn into b*d*f grams of sand. If b*d*f > a*c*e, you can infinitely increase the amount of sand and consequently the amount of gold. Otherwise... | [
"implementation",
"math"
] | 1,800 | null |
65 | B | Harry Potter and the History of Magic | The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has ... | The problem has greedy solution. Change a digit in the first date to make it as small as possible. At each of the next steps try all one-digit exchanges in the current date and choose one that makes the date not less than the previous one and as small as possible at the same time. If the last year won't exceed 2011 - t... | [
"brute force",
"greedy",
"implementation"
] | 1,700 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.