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 ⌀ |
|---|---|---|---|---|---|---|---|
185 | D | Visit of the Great | The Great Mushroom King descended to the dwarves, but not everyone managed to see him. Only the few chosen ones could see the King.
We know that only $LCM(k^{2l} + 1, k^{2l + 1} + 1, ..., k^{2r} + 1)$ dwarves can see the Great Mushroom King. Numbers $k$, $l$, $r$ are chosen by the Great Mushroom King himself in some c... | This is number theory problem. I'm trying to explain it step by step: 1) Let's prove, that LCD is maximum 2. Let $k^{2^{n}}+1\dot{z}d\Leftrightarrow k^{2^{n}}\equiv\!\!d-1$. Squaring both sides we get $k^{2^{n+1}}\equiv_{d}1\stackrel{\leftrightarrow}{\leftrightarrow}k^{2^{n+1}}-1^{;}d$, but we want to $k^{2^{n+1}}+1;d$... | [
"math",
"number theory"
] | 2,600 | null |
185 | E | Soap Time! - 2 | Imagine the Cartesian coordinate system. There are $k$ different points containing subway stations. One can get from any subway station to any one instantly. That is, the duration of the transfer between any two subway stations can be considered equal to zero. You are allowed to travel only between subway stations, tha... | This problem wasn't taken to ROI, because of that I gave it here. This is pretty hard problem. I can't now realize, what cerealguy wrote, but his solution is $O(nlogn)$ - without binary search. For me it's quite hard to understand, because my first solution was with binary search. And there were solutions, that has a w... | [
"binary search",
"data structures"
] | 3,000 | null |
186 | A | Comparing Strings | Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.
Dwarf Mish... | If the lengths of 2 strings aren't equal - that means "NO". We try to find the positions in strings, where chars are different. If there 1 or more than 2 such positions - "NO". After that we swap 2 characters in the first string, and check for their equality. | [
"implementation",
"strings"
] | 1,100 | null |
186 | B | Growing Mushrooms | Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules ... | We can see, that we can do all in integers, because k is integer number of percent. For each dwarf we should find his optimal strategy - to check 2 strategies with speed. We should sort them. | [
"greedy",
"sortings"
] | 1,200 | null |
187 | A | Permutations | Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.
One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers $1$ through $n$ and is asked to convert the first one to the second. In one move he can remove the last number from the ... | It is easy to see that if we replace each number in the first permutation with position of that number in the second permutation, the problem reduces to sorting the first permutation. Each time we take a number from the end of array, we can postpone its insertion until we know the most suitable position for insertion. ... | [
"greedy"
] | 1,500 | null |
187 | B | AlgoRace | PMP is getting a warrior. He is practicing a lot, but the results are not acceptable yet. This time instead of programming contests, he decided to compete in a car racing to increase the spirit of victory. He decides to choose a competition that also exhibits algorithmic features.
AlgoRace is a special league of car r... | First we solve the problem when the number of allowed car changes is zero (_k=0_). Let W(i,j,l) be the length of shortest path from i to j with car l. We use Floyd-Warshal on graph of each car to find this value. Then answer for the case that we can use only one car for each pair of cities i and j is: ans(0,i,j) = min ... | [
"dp",
"shortest paths"
] | 1,800 | null |
187 | C | Weak Memory | \underline{Zart PMP} is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.
The park has $n$ intersections numbered $1$ through $n$.... | There were many different correct approaches to this problem during the contest. But I will explain author's solution. First we can use binary search over the value of q. Now for a fixed q we want to check s-t connectivity. Let K be the set of all intersections with volunteers union s and t. One can use BFS from each k... | [
"dfs and similar",
"dsu"
] | 2,000 | null |
187 | D | BRT Contract | In the last war of PMP, he defeated all his opponents and advanced to the final round. But after the end of semi-final round evil attacked him from behind and killed him! God bless him.
Before his death, PMP signed a contract with the bus rapid transit (BRT) that improves public transportations by optimizing time of t... | We define ti as follows: assume a bus starts moving from i-th intersection exactly at the time when the light changes to green. The time it takes for the bus to get the final station is ti. We call the times when a green interval begins t0 (so every g+r seconds t0 occurs once) If a bus gets to i-th intersection during ... | [
"data structures"
] | 2,800 | null |
187 | E | Heaven Tour | The story was not finished as PMP thought. God offered him one more chance to reincarnate and come back to life. But before he can come back, God told him that PMP should ask $n$ great men including prominent programmers about their life experiences.
The men are standing on a straight line. They are numbered $1$ throu... | Step 1. Solve the problem if the starting man is the leftmost man and the finishing man is the rightmost man. Obviously every segment (the distance between two consecutive men) should be covered at least once. We also argue that at least l (the number of left tickets) segments should be covered at least three times. Pr... | [
"data structures",
"greedy"
] | 2,900 | null |
189 | A | Cut Ribbon | Polycarpus has a ribbon, its length is $n$. He wants to cut the ribbon in a way that fulfils the following two conditions:
- After the cutting each ribbon piece should have length $a$, $b$ or $c$.
- After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces a... | The problem is to maximize x+y+z subject to ax+by+cz=n. Constraints are low, so simply iterate over two variables (say x and y) and find the third variable (if any) from the second equation. Find the maximum over all feasible solutions. Other approaches: Use dynamic programming with each state being the remainder of ri... | [
"brute force",
"dp"
] | 1,300 | null |
189 | B | Counting Rhombi | You have two positive integers $w$ and $h$. Your task is to count the number of rhombi which have the following properties:
- Have positive area.
- With vertices at integer points.
- All vertices of the rhombi are located inside or on the border of the rectangle with vertices at points $(0, 0)$, $(w, 0)$, $(w, h)$, $(... | Observe that lots of rhombi have the same shape, but are in different locations. What uniquely determines the shape of a rhombus? Its width and its height. Is it possible to build a rhombus with every width and every height such that the vertices of the rhombus are in integer points? No, it is possible only if the widt... | [
"brute force",
"math"
] | 1,300 | null |
190 | A | Vasya and the Bus | One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had $n$ grown-ups and $m$ kids..."
The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers cou... | Firstly, if $n = 0$, then children can't be in the bus, so if $m = 0$ then the answer is $(0, 0)$, otherwise the answer is $"Impossible"$. Now $n > 0$. If $m = = 0$, than it is only one possible variant of passage - the answer is $(n, n)$. Otherwise, more grown-up take some children, less the sum that people pay. So, i... | [
"greedy",
"math"
] | 1,100 | null |
190 | B | Surrounded | So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounde... | Let's find the minimum distance between two circles $L$. Then the answer to our problem is $L / 2$. Now $d$ is the distance between the centers of the circles, $R$, $r$ - their radiuses. There are 3 possible cases: - Circles don't intersect. Then $L = d - R - r$. Firstly, it's reachable: let's consider the segment, con... | [
"geometry"
] | 1,800 | null |
190 | C | STL | Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.
We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integer... | In this problem we have an array of strings $(s_{1}, s_{2}, ...s_{n})$, where $s_{i}$ $= pair$ or $int$. Let's consider $bal_{i}$ = the difference between number of "pair" and "int" int the subarray $(s_{1}, s_{2}, ...s_{i})$. Than we can prove that the type can be reestablished from the array $s$ $< = >$ $bal_{i} > = ... | [
"dfs and similar"
] | 1,500 | null |
190 | D | Non-Secret Cypher | Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the informati... | First solution: Let's use the method of two pointers. For every number we will know how many times it occurs in the current segment $[l, r]$. For fixed $l$ we increase $r$ until $a[r]$ occurs in the current segment less than $k$ times. If $a[r]$ occurs int the segment $[l, r]$ $k$ times, we add to the answer all segmen... | [
"two pointers"
] | 1,900 | null |
190 | E | Counter Attack | Berland has managed to repel the flatlanders' attack and is now starting the counter attack.
Flatland has $n$ cities, numbered from $1$ to $n$, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities... | This problem has several different solutions. Anyway, we should consider towns as the vertices of the graph, roads as its edges. Now we are to find the connected components of the complementary graph (CG) of the given graph. Let's take the vertex $A$ with the minimal degree $c$: $c<={\frac{m}{n}}$. We call the set of t... | [
"data structures",
"dsu",
"graphs",
"hashing",
"sortings"
] | 2,100 | null |
193 | A | Cutting Figure | You've gotten an $n × m$ sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as $A$. Set $A$ is connected. Your task is to find the minimum number of squares that we can delete from set $A$ to make it not connected.
A set of painted squares is called connected, if for eve... | Main idea: using the fact that the answer cannot be greater than 2, check answer 1. Let's proof that the answer is not greater than 2. Let area of the figure be greater than 3. Let's examine the leftmost of all topmost squares. There is no neighbors left or up to it. So, number of its neighbors is not more than 2. Thus... | [
"constructive algorithms",
"graphs",
"trees"
] | 1,700 | null |
193 | B | Xor | John Doe has four arrays: $a$, $b$, $k$, and $p$. Each array consists of $n$ integers. Elements of all arrays are indexed starting from $1$. Array $p$ is a permutation of integers $1$ to $n$.
John invented a game for his friends and himself. Initially a player is given array $a$. The player must consecutively execute ... | Main idea: bruteforce in complexity $O(F_{u}n)$ where $F_{u}$ if fibonacci number at position $u$. This problem had complex statements. We have an array $a$, and we can transform it in two ways. The goal was to maximize the sum of all its elements with given multipliers after exactly $u$ operations. A simple bruteforce... | [
"brute force"
] | 2,000 | null |
193 | C | Hamming Distance | Hamming distance between strings $a$ and $b$ of equal length (denoted by $h(a, b)$) is equal to the number of distinct integers $i$ $(1 ≤ i ≤ |a|)$, such that $a_{i} ≠ b_{i}$, where $a_{i}$ is the $i$-th symbol of string $a$, $b_{i}$ is the $i$-th symbol of string $b$. For example, the Hamming distance between strings ... | Main idea: reduction to system of linear equations and solving it using Gauss algorithm. Let's notice that order of columns in answer doesn't matter. That's why there is only one important thing - quantity of every type of column. There is only $2^{4} = 16$ different columns. Let's represent Hamming distance between ev... | [
"constructive algorithms",
"greedy",
"math",
"matrices"
] | 2,400 | null |
193 | D | Two Segments | Nick has some permutation consisting of $p$ integers from $1$ to $n$. A segment $[l, r]$ ($l ≤ r$) is a set of elements $p_{i}$ satisfying $l ≤ i ≤ r$.
Nick calls a pair of segments $[a_{0}, a_{1}]$ and $[b_{0}, b_{1}]$ ($1 ≤ a_{0} ≤ a_{1} < b_{0} ≤ b_{1} ≤ n$) good if all their $(a_{1} - a_{0} + b_{1} - b_{0} + 2)$ e... | Main idea: inverse the permutation and solve simplified problem (see below), consider function "quantity of segments of permutation that form the given segment of natural series". In order to solve this problem, we suggest solve another: <<we have a permutation $p_{n}$, we have to calculate the count of segments such t... | [
"data structures"
] | 2,900 | null |
193 | E | Fibonacci Number | John Doe has a list of all Fibonacci numbers modulo $10^{13}$. This list is infinite, it starts with numbers $0$ and $1$. Each number in the list, apart from the first two, is a sum of previous two modulo $10^{13}$. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the rema... | Main idea: baby-step-giant-step. In this problem we had some Fibonacci number modulo $10^{13}$ $f$, and we had to determine the position of its first occurence in Fibonacci sequence modulo $10^{13}$. Let $a$ and $b$ be two different coprime modula - divisors of $10^{13}$. Let $F$ be the actual Fibonacci number such tha... | [
"brute force",
"math",
"matrices"
] | 2,900 | null |
194 | A | Exams | One day the Codeforces round author sat exams. He had $n$ exams and he needed to get an integer from $2$ to $5$ for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark $2$.
The author would need to spend too much time and effort to make the sum of his marks strictly more than $k$. That cou... | Let's notice that $2n \le k \le 5n$. If $k < 3n$ author has to get $2$ on some exams. There are $3n - k$ such exams and that's the answer). If $3n \le k$ author will pass all exams (answer is $0$). | [
"implementation",
"math"
] | 900 | null |
194 | B | Square | There is a square painted on a piece of paper, the square's side equals $n$ meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwa... | Let the pencil move by the line and put crosses through every $(n + 1)$ point. Lets associate every point on the line with point on square perimeter. Namely, point $x$ on the line will be associated with point on square perimeter that we will reach if we move pencil around square to $x$ clockwise. Then lower left corne... | [
"math"
] | 1,200 | null |
195 | A | Let's Watch Football | Valeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will "hang up" as the size of data to watch per second will be more than the si... | The whole video will be downloaded in $all = (c \cdot a + b - 1) / b$ seconds. In this problem you can choose every $1 < = t < = all$ as an answer. To fulfill coditions of the problem it is enough to check the condition $t0 \cdot b > = (t0 - t) \cdot a$ at the moment of time t0 = all. | [
"binary search",
"brute force",
"math"
] | 1,000 | null |
195 | B | After Training | After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has $n$ balls and $m$ baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from $1$ to $m$, corresponding... | In this problem you should carefully implement the given process. Firstly note that ball number $i > m$ will be in the same basket as ball number $i - m$. Therefore it is enough to distribute first $m$ balls. It can be done using two pointers $lf$, $rg$ from the middle. Alternately put one ball to the left and to the r... | [
"data structures",
"implementation",
"math"
] | 1,300 | null |
195 | C | Try and Catch | Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.
The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks:
- The try opera... | In this problem you was to implement what was writen in the statement. In my solution I did the following. Erase all spaces from the text except spaces in messages in try-catch blocks. Then when we get word "try" we put number of the new try-catch block in stack. When we get word "throw" we remember it's type and curre... | [
"expression parsing",
"implementation"
] | 1,800 | null |
195 | D | Analyzing Polyline | As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of fun... | In fact in this problem we were given lines $y_{i} = k_{i} * x + b_{i}$ but negative values were replaced by zero. Your task was to find the number of angles that do not equal 180 degrees in the graph s(x), that is the sum of the given functions. Firstly note that sum of two lines is also line. Indeed $y = y_{1} + y_{2... | [
"geometry",
"math",
"sortings"
] | 1,900 | null |
195 | E | Building Forest | An oriented weighted forest is an acyclic weighted digraph in which from each vertex at most one edge goes.
The root of vertex $v$ of an oriented weighted forest is a vertex from which no edge goes and which can be reached from vertex $v$ moving along the edges of the weighted oriented forest. We denote the root of ve... | The longest operation in this problem is to find the root of some vertex and the sum of the path to this root. To find these values fast we will use compression ways heuristics which is used in data structure "disjoint-set-union". For every vertex v we keep two values : $c[v]$ and $sum[v]$. $c[v] = v$, if $v$ - root, e... | [
"data structures",
"dsu",
"graphs"
] | 2,000 | null |
196 | A | Lexicographically Maximum Subsequence | You've got string $s$, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string $s[p_{1}p_{2}... p_{k}] = s_{p1}s_{p2}... s_{pk}(1 ≤ p_{1} < p_{2} < ... < p_{k} ≤ |s|)$ a subsequence of string $s = s_{1}s_{2}... s_{|s|}$.
String $x = x_{1}x_{2}... x_{... | Solution is greedy. First, write all 'z' letters (if there is any) - answer must contain them all for sure. Now it's time for 'y' letters. We can use only those of them which are on the right of last used 'z' letter. Then write 'x' letters - they must be on the right of the last used 'y' and 'z' letters. And so on. | [
"greedy",
"strings"
] | 1,100 | null |
196 | B | Infinite Maze | We've got a rectangular $n × m$-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell $(x, y)$ is a wall if and only if cell $(x{\mathrm{~mod~}}n,y{\mathrm{~mod~}}m)$ is a wal... | Answer is "Yes" iff there are two distinct, reachable from start position cells, which correspond to same cell in initial labyrinth. Proof: If these cells exist, move to first of them, and infinitely repeat moves leading from first to second. On the contrary, if infinite far path exist, on this path we obviously can fi... | [
"dfs and similar",
"graphs"
] | 2,000 | null |
196 | C | Paint Tree | You are given a tree with $n$ vertexes and $n$ points on a plane, no three points lie on one straight line.
Your task is to paint the given tree on a plane, using the given points as vertexes.
That is, you should correspond each vertex of the tree to exactly one point and each point should correspond to a vertex. If ... | No three points are in the same line, so the solution always exists. First, choose any one vertex as the root of tree. Find size of each subtree using dfs. Then, we can build the answer recursively. Put the root of tree to the most lower left point. Sort all other points by angle relative to this lower left point. Let ... | [
"constructive algorithms",
"divide and conquer",
"geometry",
"sortings",
"trees"
] | 2,200 | null |
196 | D | The Next Good String | In problems on strings one often has to find a string with some particular properties. The problem authors were reluctant to waste time on thinking of a name for some string so they called it good. A string is good if it doesn't have palindrome substrings longer than or equal to $d$.
You are given string $s$, consisti... | 464B - Restore Cube | [
"data structures",
"greedy",
"hashing",
"strings"
] | 2,800 | null |
196 | D | The Next Good String | In problems on strings one often has to find a string with some particular properties. The problem authors were reluctant to waste time on thinking of a name for some string so they called it good. A string is good if it doesn't have palindrome substrings longer than or equal to $d$.
You are given string $s$, consisti... | Notice, that only palindromes with length $d$ and $d + 1$ matter. Any palindrome with greater length contains one of them. Let's call these palindromes bad. First, find leftmost position $pos$, in which we surely should increase value of symbol. If there are no bad subpalindromes, $pos = |s| - 1$, else $pos$ is leftmos... | [
"data structures",
"greedy",
"hashing",
"strings"
] | 2,800 | null |
196 | E | Opening Portals | Pavel plays a famous computer game. A player is responsible for a whole country and he can travel there freely, complete quests and earn experience.
This country has $n$ cities connected by $m$ bidirectional roads of different lengths so that it is possible to get from any city to any other one. There are portals in $... | First of all, we can note that if each graph vertex is portal, the answer will be a sum of all edges' weights in MST (minimal spanning tree). We can find MST by using Kruskal's algo. In this problem, not an every vertex is portal. Let's fix this. Start with a precalculation. Run Dijkstra's algo from all the portals, si... | [
"dsu",
"graphs",
"shortest paths"
] | 2,600 | null |
197 | A | Plate Game | You've got a rectangular table with length $a$ and width $b$ and the infinite number of plates of radius $r$. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located with... | If first player can't make first move (table is too small and plate doesn't fit it, i.e. $2r > min(a, b)$), second player wins. Else first player wins. Winning strategy for first player: place first plate to the center of table. After that he symmetrically reflects moves of second player with respect to center of table... | [
"constructive algorithms",
"games",
"math"
] | 1,600 | null |
197 | B | Limit | You are given two polynomials:
- $P(x) = a_{0}·x^{n} + a_{1}·x^{n - 1} + ... + a_{n - 1}·x + a_{n}$ and
- $Q(x) = b_{0}·x^{m} + b_{1}·x^{m - 1} + ... + b_{m - 1}·x + b_{m}$.
Calculate limit $\operatorname*{lim}_{x\to+\infty}{\frac{P(x)}{Q(x)}}$. | From math lessons we know, that only higher degrees of polinomials matter in this problem. If denominator degree is larger than numenator degree, answer is "0/1". If numenator degree is larger, answer is infinity. But what is sign of this infinity? To get it consider signs of highest degree factors of polinomials. If t... | [
"math"
] | 1,400 | null |
200 | A | Cinema | The capital of Berland has the only movie theater in the country. Besides, it consists of only one room. The room is divided into $n$ rows, each row consists of $m$ seats.
There are $k$ people lined up to the box office, each person wants to buy exactly one ticket for his own entertainment. Before the box office start... | In this problem were given the field, which size is $n \times m$, and $k$ queries. Each query is the cell of the field. You had to find closest free cell for given one (there was used manhattan metric). Than found cell was marked as used. The time complexity of the solution is supposed to be $O(k \cdot \sqrt{k})$. Fi... | [
"brute force",
"data structures"
] | 2,400 | null |
200 | B | Drinks | Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are $n$ drinks in his fridge, the volume fraction of orange juice in the $i$-th drink equals $p_{i}$ percent.
One day Vasya decided to make himself an orange cocktail. He took equal proporti... | This problem was the easiest problem of the contest. There you had to find average of the given numbers. The most participants solved this problem. | [
"implementation",
"math"
] | 800 | null |
200 | C | Football Championship | Any resemblance to any real championship and sport is accidental.
The Berland National team takes part in the local Football championship which now has a group stage. Let's describe the formal rules of the local championship:
- the team that kicked most balls in the enemy's goal area wins the game;
- the victory give... | In this problem was given description of the group stage of some football competition and scoring system. There were given results of all matches, excepting one, and you had to find result of the last match, satisfied some given criterias. Also Berland's team must be first or the second team of the group after than mat... | [
"brute force",
"implementation"
] | 1,800 | null |
200 | D | Programming Language | Recently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, de... | In this task were given the list of template functions. Each function have its name and the list of types of arguments (also it can be used universal type). Also there were given set of variables and thier types, and some queries. Each query is function, which has name and list of arguments. For each query you had to f... | [
"binary search",
"brute force",
"expression parsing",
"implementation"
] | 1,800 | null |
200 | E | Tractor College | While most students still sit their exams, the tractor college has completed the summer exam session. In fact, students study only one subject at this college — the Art of Operating a Tractor. Therefore, at the end of a term a student gets only one mark, a three (satisfactory), a four (good) or a five (excellent). Thos... | In this problem were given four integer numbers $c_{3}, c_{4}, c_{5}, s$. You had to find $0 \le k_{3} \le k_{4} \le k_{5}$ such, that $c_{3} \cdot k_{3} + c_{4} \cdot k_{4} + c_{5} \cdot k_{5} = s$ and $|c_{3} \cdot k_{3}-c_{4} \cdot k_{4}| + |c_{4} \cdot k_{4}-c_{5} \cdot k_{5}|$ is minimal. Firstly, brute-forc... | [
"implementation",
"math",
"number theory",
"ternary search"
] | 2,400 | null |
201 | A | Clear Symmetry | Consider some square matrix $A$ with side $n$ consisting of zeros and ones. There are $n$ rows numbered from $1$ to $n$ from top to bottom and $n$ columns numbered from $1$ to $n$ from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the $i$-row and the $j$-th... | It's interesting that originally the authors had an idea not to include the $x = 3$ case into pretests. Imagine the number of successful hacking attempts in this contest -- considering the fact that none of the first $43$ solutions to this problem passed pretests :) Note that the sought $n$ is always an odd number. Ind... | [
"constructive algorithms",
"dp",
"math"
] | 1,700 | null |
201 | B | Guess That Car! | A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!".
The game show takes place on a giant parking lot, which is $4n$ meters long from north to south and $4m$ meters wide from w... | We need to find such $x$ and $y$ that the value of $\textstyle\sum_{i_{j}}c_{i j}((x-x_{i})^{2}+(y-y_{j})^{2})$ is minimum possible. This expression can be rewritten as $\textstyle\sum_{i,j}c_{i j}(x-x_{i})^{2}+\sum_{i,j}c_{i j}(y-y_{j})^{2}$. Note that the first part doesn't depend on $y$ and the second part doesn't d... | [
"math",
"ternary search"
] | 1,800 | null |
201 | C | Fragile Bridges | You are playing a video game and you have just reached the bonus level, where the only possible goal is to score as many points as possible. Being a perfectionist, you've decided that you won't leave this level until you've gained the maximum possible number of points there.
The bonus level consists of $n$ small platf... | There are a few different ways to solve this problem, the editorial contains one of them. For any solution the following fact is useful. Suppose the sought path starts on platform $i$ and ends on platform $j$ ($i \le j$, if that's not the case, we can reverse the path). Then all bridges between platforms $i$ and $j$ ... | [
"dp"
] | 2,000 | null |
201 | D | Brand New Problem | A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's probl... | The first solution coming to mind is dynamic programming $f[i][j] =$ (the smallest possible number of inversions to the moment if among the first $j$ words of the archive problem we've found a permutation of words included in bitmask $i$). In this solution parameter $j$ varies from $0$ to $500000$, parameter $i$ varies... | [
"bitmasks",
"brute force",
"dp"
] | 2,600 | null |
201 | E | Thoroughly Bureaucratic Organization | Once $n$ people simultaneously signed in to the reception at the recently opened, but already thoroughly bureaucratic organization (abbreviated TBO). As the organization is thoroughly bureaucratic, it can accept and cater for exactly one person per day. As a consequence, each of $n$ people made an appointment on one of... | Let's imagine that we have a magic function $maxN(m, k)$ that returns, given $m$ and $k$, the largest value of $n$ such that it's possible to solve the problem for $n$ people and $m$ empty lines in the form using $k$ requests. Then we'll be able to use binary search on the answer -- the number of requests $k$. Suppose ... | [
"binary search",
"combinatorics"
] | 2,600 | null |
202 | A | LLPS | \underline{This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.}
You are given string $s$ consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string $s[p_{1}$$p_{2}... p_{... | It's assumed that this problem can be solved just looking at the samples and without reading the statement itself :) Let's find the letter in the given string which comes last in the alphabet, denote this letter by $z$. If this letter occurs $p$ times in the given string, then the answer is string $a$ consisting of let... | [
"binary search",
"bitmasks",
"brute force",
"greedy",
"implementation",
"strings"
] | 800 | null |
202 | B | Brand New Easy Problem | A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's probl... | The constraints in this problem were so low that a solution with complexity $O(m \cdot k^{n})$ was just fine. In each problem's description it's enough to loop over all possible subsequences of words which are permutations of words in Lesha's problem, for each of them calculate the number of inversions and choose a per... | [
"brute force"
] | 1,700 | null |
204 | A | Little Elephant and Interval | The Little Elephant very much loves sums on intervals.
This time he has a pair of integers $l$ and $r$ $(l ≤ r)$. The Little Elephant has to find the number of such integers $x$ $(l ≤ x ≤ r)$, that the first digit of integer $x$ equals the last one (in decimal notation). For example, such numbers as $101$, $477474$ or... | It is well-known that for such problem you need to write function $F(x)$ which solves the problem for the interval $0..x$, and the answer then is $F(r) - F(l - 1)$. Now you need to write $F(x)$ function. If $x < 10$, then answer is, of course, equal to $x$. Otherwise, let $len$ be the length of $x$, $x'$ - the integer ... | [
"binary search",
"combinatorics",
"dp"
] | 1,500 | null |
204 | B | Little Elephant and Cards | The Little Elephant loves to play with color cards.
He has $n$ cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thin... | It is nice to use the $map$ structure in this problem, but you can solve it without $map$ (using sorting and binary serach). Lets iterate through all possible colors that we have and suppose that this currect color is the one that will make our set funny. The minimal number through all this will be the answer. To find ... | [
"binary search",
"data structures"
] | 1,500 | null |
204 | C | Little Elephant and Furik and Rubik | Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug.
The Little Elephant has two strings of equal length $a$ and $b$, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length — the first one from string $a$, the second one from string $b$. ... | This problem is to find the expected value. Important fact here is the linearity of the expected value. This means that we can for each element of the first strings find the probability that exactly this element will me matched with some other (but, of course, equal) from the second string. The answer will be the sum o... | [
"math",
"probabilities"
] | 2,000 | null |
204 | D | Little Elephant and Retro Strings | The Little Elephant has found a ragged old black-and-white string $s$ on the attic.
The characters of string $s$ are numbered from the left to the right from $1$ to $|s|$, where $|s|$ is the length of the string. Let's denote the $i$-th character of string $s$ as $s_{i}$. As the string is black-and-white, each charact... | Firstly we should solve following subproblem: for each prefix find the number of it's fillings such that there is no consecutive block of $k$ characters $B$. Let it be $F(x)$, where $x$ is the index in of the last character if the prefix. Assing $F(x) = F(x - 1) * cnt$, where $cnt = 2$ if $S_{x}$ = 'X' and $1$ otherwis... | [
"dp"
] | 2,400 | null |
204 | E | Little Elephant and Strings | The Little Elephant loves strings very much.
He has an array $a$ from $n$ strings, consisting of lowercase English letters. Let's number the elements of the array from 1 to $n$, then let's denote the element number $i$ as $a_{i}$. For each string $a_{i}$ $(1 ≤ i ≤ n)$ the Little Elephant wants to find the number of pa... | To solve this problems we can use suffix array. More information about suffix arrays you can find in the Internet. Firstly, concatenate all strings into the one separating consecutive strings by some unique characters (it was also useful to not use strings, but arrays of integers). For example, three strings $abc, a, a... | [
"data structures",
"implementation",
"string suffix structures",
"two pointers"
] | 2,800 | null |
205 | A | Little Elephant and Rozdil | The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").
However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum ti... | This problem was the simplest in the problemset. All you need to do is just to sort all distances (keeping track on all indices). If the first two distances are equal, just output "Still Rozdil", otherwise output the index of the first element of the array. The complexity is $O(NlogN)$. | [
"brute force",
"implementation"
] | 900 | null |
205 | B | Little Elephant and Sorting | The Little Elephant loves sortings.
He has an array $a$ consisting of $n$ integers. Let's number the array elements from 1 to $n$, then the $i$-th element will be denoted as $a_{i}$. The Little Elephant can make one move to choose an arbitrary pair of integers $l$ and $r$ $(1 ≤ l ≤ r ≤ n)$ and increase $a_{i}$ by $1$ ... | In this problem you need to notice the fact (which can be proven, but it is almost obvious) that if you are doing some operation for interval from $l$ to $r$ (inclusive), $r$ must be equal to $n$. This is becuase when you add something to all right part the answer can't be worse. After that you need to go from left to ... | [
"brute force",
"greedy"
] | 1,400 | null |
208 | A | Dubstep | Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | This problem was technical. First, you should erase all occurrences or word WUB in the beginning and in the end of the string. And then parse the remaining string separating tokens by word WUB. Empty tokens should be also erased. Given string was rather small, you can realize the algorithm in any way. | [
"strings"
] | 900 | null |
208 | B | Solitaire | A boy named Vasya wants to play an old Russian solitaire called "Accordion". In this solitaire, the player must observe the following rules:
- A deck of $n$ cards is carefully shuffled, then all $n$ cards are put on the table in a line from left to right;
- Before each move the table has several piles of cards lying i... | In this problem you could write breadth-first search. The state is the following four elements: number of remaining piles and three strings - three rightmost cards on the top of three rightmost piles. We have two transitions in general case. We can take the rightmost pile and shift it left by $1$ or $3$ on another pile... | [
"dfs and similar",
"dp"
] | 1,900 | null |
208 | C | Police Station | The Berland road network consists of $n$ cities and of $m$ bidirectional roads. The cities are numbered from 1 to $n$, where the main capital city has number $n$, and the culture capital — number $1$. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each roa... | In this problem we will find the sought quantity for every vertex and find the maximum value. For this for every vertex $v$ count two values: $cnt1[v]$ and $cnt2[v]$ - number of shortest paths from vertex $v$ to $n$-th and $1$-st vertices respectively. For this you should construct graph of shortest paths and use dynam... | [
"dp",
"graphs",
"shortest paths"
] | 1,900 | null |
208 | D | Prizes, Prizes, more Prizes | Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After ... | In this problem every time you get points you should greedily get as much prizes as you can. For this, consider every prize from the most expensive and try to get as much as you can. If we have $cnt$ points and the prize costs $p$ points you can get $\left\lfloor{\frac{c-t}{p}}\right\rfloor$ prizes. So we get simple so... | [
"implementation"
] | 1,200 | null |
208 | E | Blood Cousins | Polycarpus got hold of a family relationship tree. The tree describes family relationships of $n$ people, numbered 1 through $n$. Each person in the tree has no more than one parent.
Let's call person $a$ a 1-ancestor of person $b$, if $a$ is the parent of $b$.
Let's call person $a$ a $k$-ancestor $(k > 1)$ of person... | In this problem you have some set of rooted down- oriented trees. First, launch depth-first search from every root of every tree and renumber the vertices. Denote size of subtree of vertex $v$ as $cnt[v]$. In this way all descendants of vertex $v$ (including $v$) wiil have numbers $[v;v + cnt[v]-1]$. Then we wiil handl... | [
"binary search",
"data structures",
"dfs and similar",
"trees"
] | 2,100 | null |
213 | A | Game | Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of $n$ parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencie... | Solution - Greedy. Lets our computers settled on circle, and moves (1->2, 2->3, 3->1) will be steps "forward", and moves (1->3,3->2,2->1) will steps "back". Note that "back" moves is not optimal, as we can make two moves "forward" that is identical in time. We will look over all starts. Further, we will go by circle wh... | [
"dfs and similar",
"greedy"
] | 1,700 | null |
213 | B | Numbers | Furik loves writing all sorts of problems, especially such that he can't solve himself. You've got one of his problems, the one Furik gave to Rubik. And Rubik asks you to solve it.
There is integer $n$ and array $a$, consisting of ten integers, indexed by numbers from 0 to 9. Your task is to count the number of positi... | Solution - dynamic programming. Look over for length of the number that we will build. Further, we will use DP f(len,i) - how many numbers with length len we can make with digits i..9. Recount: - f(len,0) = sum(f(len-i,1)*C(len-1,i), i=a[0]..len); - f(len,j) = sum(f(len-i,j+1)*C(len,i), i=a[j]..len), 0<j<9; - f(len,9) ... | [
"combinatorics",
"dp"
] | 1,900 | null |
213 | C | Relay Race | Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of $n$ meters. The given square is split into $n × n$ cells (represented as unit squares), each cell has some number.
At the beginning of the race Furik stands in a cell with coordinates $(1, 1)$, and Rubik stands in a c... | Solution - dynamic programming. Note, that we can make 2 pathes form cell (1,1) to cell (n,n). Note, that after each move our cells will be located on the same diagonal. We will solve the problem with DP f(d,i1,i2), d - diagonal number, i1 - 1st coordinate 1st path, i2 - 1st coordinate 2nd path. It is clear that we can... | [
"dp"
] | 2,000 | null |
213 | D | Stars | Furik loves painting stars. A star is a shape that results if we take a regular pentagon and paint all diagonals in it.
Recently he decided to teach Rubik to paint stars. After many years of training Rubik could paint stars easily. But now Furik decided to test Rubik and complicated the task. Rubik must paint $n$ star... | I present solution as few pictures: Implementation. We have only one difficult moment - how to count coordinates? We can calculate them from regular pentagon, all that you need, you can read there. | [
"constructive algorithms",
"geometry"
] | 2,300 | null |
213 | E | Two Permutations | Rubik is very keen on number permutations.
A permutation $a$ with length $n$ is a sequence, consisting of $n$ different numbers from 1 to $n$. Element number $i$ $(1 ≤ i ≤ n)$ of this permutation will be denoted as $a_{i}$.
Furik decided to make a present to Rubik and came up with a new problem on permutations. Furik... | For given two permutation we will make two another by next transformation: New_A[A[i]] = i, where New_A - news permutation, A - given permutation. Lets we get two permutation A and B. Now our problem is next: how many sub-arrays of length n are equals to firs permutation. Two arrays will be equal if after swaping every... | [
"data structures",
"hashing",
"strings"
] | 2,700 | null |
215 | A | Bicycle Chain | Vasya's bicycle chain drive consists of two parts: $n$ stars are attached to the pedal axle, $m$ stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.
We know that the $i$-th star on the pedal axle has $a_{i}$ $(0 < a_{1} < a_{2} < ... < a_{n})$ teeth, ... | Because of small constraints we can iterate $i$ from $1$ to $n$, iterate $j$ from $1$ to $m$, check that $b_{j}$ divide $a_{i}$ and find max value of $\frac{b_j}{a_i}$. Then we can start this process again and find amount of the pairs in which $\frac{b_j}{a_i}$ is max value. | [
"brute force",
"implementation"
] | 900 | null |
215 | B | Olympic Medal | The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of $r_{1}$ cm, inner radius of $r_{2}$ cm, $(0 < r2 < r1)$ made of metal with density $p_{1}$ g/cm$^{3}$. The second part is an inner disk with radius $r_{2}$ cm, it is made of metal with density $p... | Let amagine we have values of $r_{1}$, $p_{1}$ and $p_{2}$. Then: ${\frac{m_{\omega u t}}{m_{i n}}}={\frac{A}{B}}$ $\frac{\pi{\cdot}p_{1}{\cdot}(r_{1}^{2}-r_{2}^{2})}{\pi{\cdot}p_{2}{\cdot}r_{2}^{2}}\ =\ \frac{A}{B}$ $r_{2}^{2} \cdot (B \cdot p_{1} + A \cdot p_{2}) = r_{1}^{2} \cdot B \cdot p_{1}$ $r_{2}=r_{1}\cdot{\sq... | [
"greedy",
"math"
] | 1,300 | null |
215 | C | Crosses | There is a board with a grid consisting of $n$ rows and $m$ columns, the rows are numbered from $1$ from top to bottom and the columns are numbered from $1$ from left to right. In this grid we will denote the cell that lies on row number $i$ and column number $j$ as $(i, j)$.
A group of six numbers $(a, b, c, d, x_{0}... | Let's iterate $n_{1} = max(a, c)$ and $m_{1} = max(b, d)$ - sides of bounding box. Then we can calculate value of function $f(n_{1}, m_{1}, s)$, and add to the answer $f(n_{1}, m_{1}, s) \cdot (n - n_{1} + 1) \cdot (m - m_{1} + 1)$, where two lastest brackets mean amount of placing this bounding box to a field $n \tim... | [
"brute force",
"implementation"
] | 2,100 | null |
215 | D | Hot Days | The official capital and the cultural capital of Berland are connected by a single road running through $n$ regions. Each region has a unique climate, so the $i$-th $(1 ≤ i ≤ n)$ region has a stable temperature of $t_{i}$ degrees in summer.
This summer a group of $m$ schoolchildren wants to get from the official capit... | You can use only two features about this problem: the solution is independenly for all regions and there are only 2 possible situations: all children are in exactly one bus or organizers must take minimum amount of bus such no children got a compensation. It's bad idea to place some children to hot bus and to place som... | [
"greedy"
] | 1,900 | null |
215 | E | Periodical Numbers | A non-empty string $s$ is called binary, if it consists only of characters "0" and "1". Let's number the characters of binary string $s$ from 1 to the string's length and let's denote the $i$-th character in string $s$ as $s_{i}$.
Binary string $s$ with length $n$ is periodical, if there is an integer $1 ≤ k < n$ such... | Ok, in the very beginning let's try solve some other task. We'll find the number of such integers in the interval $(2^{k}, x]$, where $k=\lfloor\log_{2}(x)\rfloor$. And someone can see that $x$ has length $len = k + 1$. Then we should try blocks of ${0, 1}$ to be the same part of periodical number. These blocks have le... | [
"combinatorics",
"dp",
"number theory"
] | 2,100 | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
#define pb push_back
#define VI vector <int... |
216 | A | Tiling with Hexagons | Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles.
The hall also turned out hexagonal in its shape. The King walked along the perimeter of ... | For solving this problem you might find some formula like $res = abc - (a - 1)(b - 1)(c - 1)$, $res = ab + bc + ca - a - b - c + 1$, or something else. Also the problem can be solved in $O(a + b + c)$ time - you can move from the top line to the bottom line of hexagon and sum number of tiles in every line. | [
"implementation",
"math"
] | 1,200 | null |
216 | B | Forming Teams | One day $n$ students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.
We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student $A$ is an archenemy to student $B$, then stud... | You can build some graph where vertices are students and edges are enmities. You should drop some vertices and then paint them in two colors. Any edge should connect vertices of distinct colors and numbers of vertices of every color should be same. You can see that graph consists chians, cycles and sepatated vertices. ... | [
"dfs and similar",
"implementation"
] | 1,700 | null |
216 | C | Hiring Staff | A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.
The store will work seven days a week, but not around the clock. Every day at least $k$ people must work in the store.
Berland has a law that determines the order of working days and non-worki... | The first solution: analysis of the cases 1. $k = 1$. For $n \le m + 1$ 3 employees is enough (in most cases). For $n > m + 1$ answer is 2. Also, there are only one tricky corner case: for $n = 2, m = 2, k = 1$ answer is 4. 2. $k > 1$. If $n = m$, answer is $2k + 1$, otherwise answer is $2k$. For any case it is easy ... | [
"greedy"
] | 1,800 | null |
216 | D | Spider's Web | Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web.
There are $n$ main threads going from the center of the web. All main threads are located in one plane and divide it into $n$ equal infinite sectors. The sectors are indexed... | For every sector you should sort bridges in order of increasing distance from the conter of the web. Now for every sector you should iterate over bridges of the current sector and two adjacent sectors using 3 pointers. During every pass you should carefully calculate number of bad cells. That is all solution. Solition ... | [
"binary search",
"sortings",
"two pointers"
] | 1,700 | null |
216 | E | Martian Luck | You know that the Martians use a number system with base $k$. Digit $b$ ($0 ≤ b < k$) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year $b$ (by Martian chronology).
A digital root $d(x)$ of number $x$ is a number that consists of a single digit, resulting after cascadin... | Digital root of number is equal to that number modulo $k - 1$ for most cases. It is lie only for digital roots 0 and $k - 1$ - in that cases number modulo $k - 1$ will be 0. But you can get digital root 0 only for numbers like $00...00$. Total number of numbers that type you can find using any other way. So, now you ca... | [
"math",
"number theory"
] | 2,000 | null |
217 | A | Ice Skating | Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves... | Notice that the existence of a snow drift at the point $(x, y)$ implies that "if I'm on the horizontal line at $y$ then I am certainly able to get to the vertical line at $x$, and vice versa". Thus, the snow drifts are the edges of a bipartite graph between x- and y- coordinates. The number of snow drifts that need to ... | [
"brute force",
"dfs and similar",
"dsu",
"graphs"
] | 1,200 | null |
217 | B | Blackboard Fibonacci | Fibonacci numbers are the sequence of integers: $f_{0} = 0$, $f_{1} = 1$, $f_{2} = 1$, $f_{3} = 2$, $f_{4} = 3$, $f_{5} = 5$, $...$, $f_{n} = f_{n - 2} + f_{n - 1}$. So every next number is the sum of the previous two.
Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. ... | If you look at the described process backwards, it resembles the Euclidean algorithm a lot. Indeed, if you rewinded a recording of Bajtek's actions, he always takes the larger out of two numbers (say Unable to parse markup [type=CF_TEX] ) and replaces them by $a - b, b$. Since we know one of the final numbers ($r$) we ... | [
"brute force",
"math"
] | 2,100 | null |
217 | C | Formurosa | The Bytelandian Institute for Biological Research (BIBR) is investigating the properties of two species of bacteria, named simply 0 and 1. Even under a microscope, bacteria of those two species are very difficult to distinguish. In fact, the only thing the scientists possess that is able to differentiate between them i... | One of the major difficulties in this problem is finding an easily formulated condition for when Formurosa can be used to distinguish the bacteria. Let Formurosa's digestive process be a function $F(s)$ that maps binary sequences of length $m$ to elements of ${0, 1}$. It turns out that the condition we seek for can be ... | [
"divide and conquer",
"dp",
"expression parsing"
] | 2,600 | null |
217 | D | Bitonix' Patrol | Byteland is trying to send a space mission onto the Bit-X planet. Their task is complicated by the fact that the orbit of the planet is regularly patrolled by Captain Bitonix, the leader of the space forces of Bit-X.
There are $n$ stations around Bit-X numbered clockwise from 1 to $n$. The stations are evenly placed o... | Observation 1. Fuel tanks for which capacity gives the same remainder $\bmod d$ are equivalent for Bitonix's purposes. Moreover, fuel tanks for which the capacities' remainders $\bmod d$ sum to $D$ are also equivalent. Out of every group of equivalent tanks, the agency can only leave at most one. Observation 2. If more... | [
"bitmasks",
"brute force",
"combinatorics",
"dfs and similar",
"math"
] | 2,900 | null |
217 | E | Alien DNA | Professor Bajtocy is conducting experiments on alien DNA. He has discovered that it is subject to repetitive mutations — each mutation happens in the same way: some continuous subsequence of the alien DNA becomes active, copies itself, the copy gets mangled and inserts itself right after the original subsequence. The m... | Note that it is easy to determine, looking at only the last mutation, how many letters it adds to the final result. Indeed, if we need to print out the first $k$ letters of the sequence, and the last mutation is $[l, r]$, it suffices to find out the length of the overlap of segments $[1, k]$ and $[r + 1, 2r - l + 1]$. ... | [
"data structures",
"dsu",
"trees"
] | 2,800 | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cst... |
219 | A | k-String | A string is called a $k$-string if it can be represented as $k$ concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string... | Count the occurrences of each character. If any character appears a number of times not divisible by K, obviously, there is no solution. Otherwise, form the solution by first making the string B. The string B can be any string with the following property: if some character ch appears q times in the string B, the same c... | [
"implementation",
"strings"
] | 1,000 | null |
219 | B | Special Offer! Super Price 999 Bourles! | Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.
Polycaprus calculated that the optimal celling price for such scissors would be $p$ bourles. However, ... | The following observation will help you code the solution: The largest number smaller than p ending with at least k nines is p - p MOD 10^k - 1 If the result turns out to be -1 , you can not reach a positive number with k or more nines. I will not explain the solution in detail - be careful when coding and have all the... | [
"implementation"
] | 1,400 | null |
219 | C | Color Stripe | A colored stripe is represented by a horizontal row of $n$ square cells, each cell is pained one of $k$ colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to $k$ to repaint the cells. | There are two cases to consider , when K=2 and when K>2. For K=2 there are only two possible solutions: the string "ABABAB..." and "BABABA..." For both strings, simply count the number of differences between it and the given string and print a string with fewer differences. For K>2 , decompose the string into contiguou... | [
"brute force",
"dp",
"greedy"
] | 1,600 | null |
219 | D | Choosing Capital for Treeland | The country Treeland consists of $n$ cities, some pairs of them are connected with unidirectional roads. Overall there are $n - 1$ roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided... | Arbitrarily root the tree at some vertex, say vertex 1. Now, all the edges are oriented either up (towards the root) or down (away from it). We will call upwards oriented edges red, and downwards oriented edges green. Now, with a single depth-first search, for each vertex, calculate its distance from the root (in numbe... | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | 1,700 | null |
219 | E | Parking Lot | A parking lot in the City consists of $n$ parking spaces, standing in a line. The parking spaces are numbered from 1 to $n$ from left to right.
When a car arrives at the lot, the operator determines an empty parking space for it. For the safety's sake the chosen place should be located as far from the already occupied... | Use a heap to maintain sequences of empty parking spaces as intervals. The comparison function for such intervals should return an interval which could store a car farthest from any other car, and if there is a tie, it should return the leftmost such interval. When inserting a car, pop the heap, look at the interval, p... | [
"data structures"
] | 2,200 | null |
220 | A | Little Elephant and Problem | The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array $a$ of length $n$ and possibly swapped some elements of the array.
The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he co... | There are multiple possible solutions for this problem. For example, the following. Find the last index $x$ such that there exists some $y$ $(y < x)$ (minimal possible) that $A_{x}$ < $A_{y}$. Then you just need to try two possibilities - either swap $A_{x}$ and $A_{y}$, or don't change anything. | [
"implementation",
"sortings"
] | 1,300 | null |
220 | B | Little Elephant and Array | The Little Elephant loves playing with arrays. He has array $a$, consisting of $n$ positive integers, indexed from 1 to $n$. Let's denote the number with index $i$ as $a_{i}$.
Additionally the Little Elephant has $m$ queries to the array, each query is characterised by a pair of integers $l_{j}$ and $r_{j}$ $(1 ≤ l_{j... | This problem can be solve in simpler $O(NsqrtN)$ solution, but I will describe $O(NlogN)$ one. We will solve this problem in offline. For each $x$ $(0 \le x < n)$ we should keep all the queries that end in $x$. Iterate that $x$ from 0 to $n - 1$. Also we need to keep some array $D$ such that for current $x$ $D_{l} + ... | [
"constructive algorithms",
"data structures"
] | 1,800 | null |
220 | C | Little Elephant and Shifts | The Little Elephant has two permutations $a$ and $b$ of length $n$, consisting of numbers from 1 to $n$, inclusive. Let's denote the $i$-th $(1 ≤ i ≤ n)$ element of the permutation $a$ as $a_{i}$, the $j$-th $(1 ≤ j ≤ n)$ element of the permutation $b$ — as $b_{j}$.
The distance between permutations $a$ and $b$ is the... | Each of the shifts can be divided into two parts - the right (the one that starts from occurrence 1) and the left (the rest of the elements). If we could keep minimal distance for each part, the minimal of these numbers will be the answers for the corresponding shift. Lets solve the problems of the right part, the left... | [
"data structures"
] | 2,100 | null |
220 | D | Little Elephant and Triangle | The Little Elephant is playing with the Cartesian coordinates' system. Most of all he likes playing with integer points. The Little Elephant defines an integer point as a pair of integers $(x; y)$, such that $0 ≤ x ≤ w$ and $0 ≤ y ≤ h$. Thus, the Little Elephant knows only $(w + 1)·(h + 1)$ distinct integer points.
Th... | Let iterate all possible points that, as we consider, must be the first point. Let it be $(x;y)$. Let the second and the third points be $(x1;y1)$ and $(x2;y2)$. Then the doubled area is $|(x1 - x)(y2 - y) - (x2 - x)(y1 - y)|$. We need this number to be even and nonzero. For first we will find the number of groups of p... | [
"geometry",
"math"
] | 2,500 | null |
220 | E | Little Elephant and Inversions | The Little Elephant has array $a$, consisting of $n$ positive integers, indexed from 1 to $n$. Let's denote the number with index $i$ as $a_{i}$.
The Little Elephant wants to count, how many pairs of integers $l$ and $r$ are there, such that $1 ≤ l < r ≤ n$ and sequence $b = a_{1}a_{2}... a_{l}a_{r}a_{r + 1}... a_{n}$... | In this problems you can use a method of two pointers. Also some RMQ are required. If you do not know about RMQ, please, read about it in the Internet before solving this problem. Firstly, map all the elements in the input array. After that all of them will be in range $[0..n - 1]$. We need to keep two RMQs, both of si... | [
"data structures",
"two pointers"
] | 2,400 | null |
221 | A | Little Elephant and Function | The Little Elephant enjoys recursive functions.
This time he enjoys the sorting function. Let $a$ is a permutation of an integers from 1 to $n$, inclusive, and $a_{i}$ denotes the $i$-th element of the permutation. The Little Elephant's recursive function $f(x)$, that sorts the first $x$ permutation's elements, works ... | In this problems you should notice that the answer for the problem is always of the following form: $n$, 1, 2, 3, ..., $n$-1. In such case array will be always sorted after the end of the algorithm. | [
"implementation",
"math"
] | 1,000 | null |
221 | B | Little Elephant and Numbers | The Little Elephant loves numbers.
He has a positive integer $x$. The Little Elephant wants to find the number of positive integers $d$, such that $d$ is the divisor of $x$, and $x$ and $d$ have at least one common (the same) digit in their decimal representations.
Help the Little Elephant to find the described numbe... | Here you just need to find all divisors of $n$. This can be done using standart algorithm with iterating from 1 to $sqrt(n)$. After that you need to write some function that checks whether two numbers has same digits. This also can be done using simple loops. | [
"implementation"
] | 1,300 | null |
222 | A | Shooshuns and Sequence | One day shooshuns found a sequence of $n$ integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:
- Find the number that goes $k$-th in the current sequence and add the same number to the end of the sequence;
- Delete the first number of the current sequ... | Note that the k-th element is copied to the end. Then the (k+1)-th element from the initial sequence is copied, then (k+2)-th, \dots , n-th, k-th, (k+1)-th, etc. So all the numbers on the blackboard will become equal if and only if all the numbers from the k-th to the n-th in the initial sequence were equal. It's now... | [
"brute force",
"implementation"
] | 1,200 | null |
222 | B | Cosmic Tables | The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement.
UCDHP stores some secret information about meteors as an $n × m$ table with integers in its cells. The order of meteors i... | Let's store the order of the rows and columns of table. Thus, row[x] is the number of the row x in the initial table and column[x] is the number of column x in the initial table. Then, the value of an element in the row x and column y in the current table is equal to t[row[x], column[y]], where t - initial table. When ... | [
"data structures",
"implementation"
] | 1,300 | null |
222 | C | Reducing Fractions | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that t... | Let's factorize the numerator and denominator. Now for each prime integer x we know the extent of x in the factorization of the numerator(a[x]) and the denominator(b[x]). For each prime number x we can calculate the extent of x in the factorization of the numerator and the denominator after reduction : newa[x]=a[x]-min... | [
"implementation",
"math",
"number theory",
"sortings"
] | 1,800 | null |
222 | D | Olympiad | A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least $x$ points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.... | First of all, note that in any case the best place which Vasya can take is the first place for he can earn maximum points. Now we must find the worst place which Vasya can take. We need to find maximal matching in bipartite graph, where the edge between vertice i from the first part and vertice j from the second part e... | [
"binary search",
"greedy",
"sortings",
"two pointers"
] | 1,900 | null |
222 | E | Decoding Genome | Recently a top secret mission to Mars has taken place. As a result, scientists managed to obtain some information about the Martian DNA. Now we know that any Martian DNA contains at most $m$ different nucleotides, numbered from $1$ to $m$. Special characteristics of the Martian DNA prevent some nucleotide pairs from fo... | 1) Solution with complexity O(n*m*m), using the dynamic programming: State - d[n][m] - the number of allowed chains of length n that ends in symbol m. Transition - sort out all possible characters, and check if you can put the symbol k after symbol m. 2) Solution with complexity O(m*m*m*log n): Note that the transition... | [
"dp",
"matrices"
] | 1,900 | null |
223 | A | Bracket Sequence | A bracket sequence is a string, containing only characters "(", ")", "[" and "]".
A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([... | You were given a bracket sequence $s$ consisting of brackets of two kinds. You were to find regular bracket sequence that was a substring of $s$ and contains as many <<[>> braces as possible. We will try to determine corresponding closing bracket for every opening one. Formally, let a bracket on the i-th position be op... | [
"data structures",
"expression parsing",
"implementation"
] | 1,700 | null |
223 | B | Two Strings | A subsequence of length $|x|$ of string $s = s_{1}s_{2}... s_{|s|}$ (where $|s|$ is the length of string $s$) is a string $x = s_{k1}s_{k2}... s_{k|x|}$ $(1 ≤ k_{1} < k_{2} < ... < k_{|x|} ≤ |s|)$.
You've got two strings — $s$ and $t$. Let's consider all subsequences of string $s$, coinciding with string $t$. Is it tr... | You were given two strings: $s$ and $t$. You were required to examine all occurrences of the string $t$ in the string $s$ as subsequence and to find out if it is true that for each position of the $s$ string there are such occurrence, that includes this position. For each position $i$ of the $s$ string we calculate two... | [
"data structures",
"dp",
"strings"
] | 1,900 | null |
223 | C | Partial Sums | You've got an array $a$, consisting of $n$ integers. The array elements are indexed from 1 to $n$. Let's determine a two step operation like that:
- First we build by the array $a$ an array $s$ of partial sums, consisting of $n$ elements. Element number $i$ ($1 ≤ i ≤ n$) of array $s$ equals $s_{i}=\left(\sum_{j=1}^{i}... | You were given an array $a$ in this problem. You could replace $a$ by the array of its partial sums by one step. You had to find the array after $k$ such steps. All the calculations were modulo $P = 10^{9} + 7$. Write partial sums in following way: $s_{i}=\sum_{j=1}^{n}B_{i,j}a_{j}$where $B_{i, j} = 1$ if $i \ge j$ a... | [
"combinatorics",
"math",
"number theory"
] | 1,900 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.