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
873
F
Forbidden Indices
You are given a string $s$ consisting of $n$ lowercase Latin letters. Some indices in this string are marked as forbidden. You want to find a string $a$ such that the value of $|a|·f(a)$ is maximum possible, where $f(a)$ is the number of occurences of $a$ in $s$ such that these occurences end in non-forbidden indices....
This problem can be solved with different suffix structures. Model solution uses suffix array. First of all, let's reverse $s$, so for $f(a)$ we will count only occurences that start in non-forbidden indices. Then, if there is at least one non-forbidden index, there are two cases: $f(a) = 1$, then the best option to ch...
[ "dsu", "string suffix structures", "strings" ]
2,400
null
875
A
Classroom Watch
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number $n$. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that $n$ is the answer to the arithmetic task for first-graders. In the textbook, a certain ...
For numbers that doesn't exceed $10^{9}$ sum of digits doesn't exceed $100$, so we can just iterate over all possible sums of digits $x$ and check if sum of digits of $n - x$ equals $x$.
[ "brute force", "math" ]
1,200
null
875
B
Sorting the Coins
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then...
We denote, for 0, a coin that has left circulation and for one coin in circulation. We solve the problem for a fixed array. If it consists of only 1, then the answer is 0, since the array is already sorted. Otherwise, consider the most right zero. If there is not a single 1 to the left of this zero, then the array is a...
[ "dsu", "implementation", "sortings", "two pointers" ]
1,500
null
875
C
National Property
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library. Some long and uninteresting story was removed... The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large ve...
Let the strings $s_{i}$ and $s_{i + 1}$ are not prefixes of each other. Then it is necessary that $s_{i, k} < s_{i + 1, k}$, where k is the first position, where $s_{i}$ and $s_{i + 1}$ differ. Consider strings $s_{i}$ and $s_{i + 1}$. Let $k$ be the first position in which they differ. Then there are two cases: If $s_...
[ "2-sat", "dfs and similar", "graphs", "implementation" ]
2,100
null
875
D
High Cry
Disclaimer: there are lots of untranslateable puns in the Russian version of the statement, so there is one more reason for you to learn Russian :) Rick and Morty like to go to the ridge High Cry for crying loudly — there is an extraordinary echo. Recently they discovered an interesting acoustic characteristic of this...
First we find for each element the nearest element on the left and on the right more than it. It can be done by many ways, for example using stack. Then you find for each element $x$ the nearest on the left and on the right element $y$ so that $x|y > x$. For this note that in $y$ must be some bit set, which is not set ...
[ "binary search", "bitmasks", "combinatorics", "data structures", "divide and conquer" ]
2,200
null
875
E
Delivery Club
Petya and Vasya got employed as couriers. During the working day they are to deliver packages to $n$ different points on the line. According to the company's internal rules, the delivery of packages must be carried out strictly in a certain order. Initially, Petya is at the point with the coordinate $s_{1}$, Vasya is a...
We will learn to check that the answer is no more $p$. If we learn to do this, we can make a binary search for the answer and get the answer. To check we calculate $dp_{i}$ - is it possible to process the first $i$ orders so that the last order of one courier is $i$, and the second order is $i + 1$. In this case, the t...
[ "binary search", "data structures", "dp" ]
2,600
null
875
F
Royal Questions
In a medieval kingdom, the economic crisis is raging. Milk drops fall, Economic indicators are deteriorating every day, money from the treasury disappear. To remedy the situation, King Charles Sunnyface decided make his $n$ sons-princes marry the brides with as big dowry as possible. In search of candidates, the king ...
Consider bipartite graph in which princesses are in the left part and princes in the right part. Because of the propriety of transversal matroid you can choose princesses greedily: let's sort princesses according to decrease in size of dowry and in this order try to add to matching. It can be done at $O(nm)$ every time...
[ "dsu", "graphs", "greedy" ]
2,500
null
876
A
Trip For Meal
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is $a$ meters, between Rabbit's ...
If minimum of numbers $a, b, c$ equals $a$ or $b$, or $n = 1$. Then answer equals $min(a, b) \cdot (n - 1)$. Otherwise answer equals $min(a, b) + c \cdot (n - 2)$. Also there is solution that uses dynamic programming.
[ "math" ]
900
null
876
B
Divisiblity of Differences
You are given a multiset of $n$ integers. You should select exactly $k$ of them in a such way that the difference between any two of them is divisible by $m$, or tell that it is impossible. Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number...
If $x - y$ is divisible by $m$, then $x$ and $y$ have same reminder when divided by $m$. Let's divide number to groups by reminder by modulo $m$, and if there is a group with size at least $k$ print $k$ numbers from it.
[ "implementation", "math", "number theory" ]
1,300
null
877
A
Alex and broken contest
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems. But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest ...
You need just implement what is written in the statements. Count the total number of entries of the names and check if it's equal to $1$. 877B - Nikita and string
[ "implementation", "strings" ]
1,100
null
877
B
Nikita and string
One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into $3$ strings (possibly empty) without changing the order of the letters, where the $1$-st and the $3$-rd one contain only letters "a" and the $2$-nd contains only letters "b". Nikita wants ...
Let $pref_{a}[i]$ be the count of letter "a" in prefix of length $i$ and $pref_{b}[i]$ be the count of letter "b" in prefix of length $i$. Let's fix two positions $i$ and $j$, $1 \le i \le j \le n$, so we remove all "b" from prefix, which ends in $i$, and suffix, which starts in $j$, and all "a" between positions...
[ "brute force", "dp" ]
1,500
null
877
C
Slava and tanks
Slava plays his favorite game "Peace Lightning". Now he is flying a bomber on a very specific map. Formally, map is a checkered field of size $1 × n$, the cells of which are numbered from $1$ to $n$, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he ...
Let's call the tanks, which are initially in even positions even, and the tansk, which are initially in odd positions odd. Let's throw bombs in all even positions. Now all tanks are in odd positons. Now let's throw bombs in all odd positions. Now all even tanks are exterminated and all odd tanks are in even positions. ...
[ "constructive algorithms" ]
1,600
null
877
D
Olya and Energy Drinks
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks. Formally, her room can be represented as a field of $n × m$ cells, each cell of which is empty or littered with cans. Olya drank a lot of energy drink, so now she can run $k$ meters per second. Each second she cho...
Note, that bfs can find right answer, but works in $O(n \cdot m \cdot k)$. It's too slow. We'll store all not visited cells in set. For each row and column we'll make own set. Now it's easy to find all not visited cell which is reachable from vertex in $O(cnt \cdot log(n))$, where $cnt$ is number of this cells. Then su...
[ "data structures", "dfs and similar", "graphs", "shortest paths" ]
2,100
null
877
E
Danil and a Part-time Job
Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with $n$ vertices, vertex $1$ is the root of the tree. There is a room in each vertex, light can be switched on or off in eac...
Let's construct Euler tour tree. We'll put vertex in vector when first time visit it. For each vertext subtree is segment in this vector, borders of which we can calculate while constructing. Now we need to make inversion on segment and get sum of segment. Segment tree is good for it. 877F - Ann and Books
[ "bitmasks", "data structures", "trees" ]
2,000
null
877
F
Ann and Books
In Ann's favorite book shop are as many as $n$ books on math and economics. Books are numbered from $1$ to $n$. Each of them contains non-negative number of problems. Today there is a sale: any subsegment of a segment from $l$ to $r$ can be bought at a fixed price. Ann decided that she wants to buy such non-empty sub...
If $i$-th book is on economics, $a[i] = - a[i]$. Now problem is to calculate count of segments of sum $k$. Calculate prefix sums: $p[j]=\sum_{i=1}^{J}a[i]$. Then $\sum_{i=l}^{r}=p[r]-p[l-1]$. Now we can solve it in $O(n \cdot q \cdot log(n))$. We'll go along the segment and calculate $cnt[i]$ - number of occurences of ...
[ "data structures", "flows", "hashing" ]
2,300
null
878
A
Short Program
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an...
Let's see what happens with a single bit. All operations work with each bit separately, so each bit of output depends only on the corresponding bit of input. There are only four options: bit doesn't change, bit always changes, bit is set to 0, bit is set to 1. For each bit it's easy to find which of these options happe...
[ "bitmasks", "constructive algorithms" ]
1,600
null
878
B
Teams Formation
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has $n$ passenger seats, seat $i$ can be occupied only by a participant from the city $a_{i}$. Today the bus has completed $m$ trips, each time bringing $n$ participants. The participants were the...
First, let's see what happens inside one bus. We can use a stack containing pairs (city, number of participants from it). When the number of participants reaches $k$, we erase the pair. Suppose we build this stack. $r$ is its size, $(c_{i}, d_{i})$ are pairs in it. Now consider the interaction of two such buses. At the...
[ "data structures", "implementation" ]
2,300
null
878
C
Tournament
Recently a tournament in $k$ kinds of sports has begun in Berland. Vasya wants to make money on the bets. The scheme of the tournament is very mysterious and not fully disclosed. Competitions are held back to back, each of them involves two sportsmen who have not left the tournament yet. Each match can be held in any ...
Imagine a directed graph, in which the vertices are participants, and the edge means that one participant can win the other in some kind of sports. A participant can win a tournament if there is a directed tree in this graph that contains all vertices, and this player is a root. Consider the condensation of this graph....
[ "data structures", "graphs" ]
2,700
null
878
D
Magic Breeding
Nikita and Sasha play a computer game where you have to breed some magical creatures. Initially, they have $k$ creatures numbered from $1$ to $k$. Creatures have $n$ different characteristics. Sasha has a spell that allows to create a new creature from two given creatures. Each of its characteristics will be equal to ...
Let's consider a special case of the problem: all $a_{ij}$ are 0 or 1. In this case there are at most $2^{k}$ different characteristics. So we can use trivial solution, it works in $O(q2^{k})$. Also we can sped up it using bitset. Now we reduce the problem to this special case. We have a characteristic with values $x_{...
[ "bitmasks" ]
2,900
null
878
E
Numbers on the blackboard
A sequence of $n$ integers is written on a blackboard. Soon Sasha will come to the blackboard and start the following actions: let $x$ and $y$ be two adjacent numbers ($x$ before $y$), then he can remove them and write $x + 2y$ instead of them. He will perform these operations until one number is left. Sasha likes big ...
Let's find a strategy for Sasha. His result can be represented in the form $\sum_{i=1}^{n}a_{i}2^{k_{i}}$, where $k_{1} = 0$, $1 \le k_{i} \le k_{i - 1} + 1$ for $i > 1$. For all $k_{i}$ satisfying these conditions he can obtain such result. We prove this by induction. For $n = 1$ is't obvious. Let $n > 1$. Find th...
[ "combinatorics", "dp" ]
3,300
null
879
A
Borya's Diagnosis
It seems that Borya is seriously sick. He is going visit $n$ doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor $1$, then doctor $2$, then doctor $3$ and so on). Borya will...
Note that Borya can use a greedy algorithm. He will visit each doctor as soon as possible. We only need to find the earliest day when he can do it. Constraints are pretty low, so we can use almost any reasonable way. For example, we can just go through all the days, starting from the current one, and check if the docto...
[ "implementation" ]
900
null
879
B
Table Tennis
$n$ people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins $k$ games in a row. This player becomes the winner. For each of t...
It's not very difficult to solve this problem in $O(k + n)$. The statement hints us that we can use the data structure queue. We need to maintain the queue of players, the current winner and the number of wins he has. Each game is processed in $O(1)$. It can be shown that number of games is less than $n + k$. Of course...
[ "data structures", "implementation" ]
1,200
null
884
A
Book Reading
Recently Luba bought a very interesting book. She knows that it will take $t$ seconds to read the book. Luba wants to finish reading as fast as she can. But she has some work to do in each of $n$ next days. The number of seconds that Luba has to spend working during $i$-th day is $a_{i}$. If some free time remains, sh...
Let's read the book greedily. On $i$-th day Luba will read for $86400 - a_{i}$ seconds. Subtract value for each day from $t$ until $t$ becomes less or equal to zero. That will be the day Luba finishes the book. Overall complexity: $O(n)$.
[ "implementation" ]
800
null
884
B
Japanese Crosswords Strike Back
A one-dimensional Japanese crossword can be represented as a binary string of length $x$. An encoding of this crossword is an array $a$ of size $n$, where $n$ is the number of segments formed completely of $1$'s, and $a_{i}$ is the length of $i$-th segment. No two segments touch or intersect. For example: - If $x = 6...
The only answer is when no segment can be moved one cell either to the left or to the right. So there should be exactly one cell between two consecutive segments and the first and the last segments should touch the borders. Thus total count of cells needed is $\sum_{i=1}^{n}a_{i}+n-1$. Overall complexity; $O(n)$.
[ "implementation" ]
1,100
null
884
C
Bertown Subway
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself. There are $n$ stations in the subway. It was built according to the Bertown Transport Law: - For each station $i$ there exists exactly one train that goes from this station. ...
Let's notice that one swap can affect at most two cycles of this permutation. Moreover you can join two cycles into one with the length equal to the sums of lengths of initial ones. The function we are going to maximize is $f(a, b) = (a + b)^{2} - a^{2} - b^{2}$, where $a$ and $b$ are the lengths of the cycles we are j...
[ "dfs and similar", "greedy", "math" ]
1,500
null
884
D
Boxes And Balls
Ivan has $n$ different boxes. The first of them contains some balls of $n$ different colors. Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every $i$ ($1 ≤ i ≤ n$) $i$-th box will contain all balls with color $i$. In order to do this, Ivan will make some turns. E...
Let's consider the process backwards: we will store the number of balls of each color in a multiset and then "merge" some of them. If $n$ is odd, then we can always pick three groups of balls with minimal sizes and replace them by one group (adding the size of this group to the penalty). Repeat until you have only one ...
[ "data structures", "greedy" ]
2,300
null
884
E
Binary Matrix
You are given a matrix of size $n × m$. Each element of the matrix is either 1 or 0. You have to determine the number of connected components consisting of 1's. Two cells belong to the same component if they have a common border, and both elements in these cells are 1's. \textbf{Note that the memory limit is unusual!}
The main idea is to read and process each row of the matrix separately. To do this, we will use DSU data structure. The answer will be equal to the difference between the number of 1's and the number of merge operations in DSU. When processing the row, we will keep the DSU for the previous row. When processing a certai...
[ "dsu" ]
2,500
null
884
F
Anti-Palindromize
A string $a$ of length $m$ is called antipalindromic iff $m$ is even, and for each $i$ ($1 ≤ i ≤ m$) $a_{i} ≠ a_{m - i + 1}$. Ivan has a string $s$ consisting of $n$ lowercase Latin letters; $n$ is even. He wants to form some string $t$ that will be an antipalindromic permutation of $s$. Also Ivan has denoted the beau...
This problem has two different solutions: a mincost maxflow approach and a greedy one. We will tell you about the latter. First of all, let $t = s$. Then find all pairs of indices $(i, n - i + 1)$ such that $t_{i} = t_{n - i + 1}$ (let the number of these pairs be $m$). It's obvious that we have to replace at least one...
[ "flows", "graphs", "greedy" ]
2,500
null
886
A
ACM ICPC
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only $6$ students who wished to participate, the decision was to build exactly two teams. After practice competition, participant number $i$ got a score of $a_{i}...
In this problem it's enough to iterate through all the triples checking whether its sum equals to the sum of remaining triple or not. Answer is "YES" if equality is possible and "NO" - otherwise.
[ "brute force" ]
1,000
null
886
B
Vlad and Cafes
Vlad likes to eat in cafes very much. During his life, he has visited cafes $n$ times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research. First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes...
There are two steps to solve this problem: 1. Put in array last the last time when Petya visited each cafe. 2. Now you need to find the position of minimum in this array and print it.
[]
1,000
null
886
C
Petya and Catacombs
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs. Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages ...
First, we notice that if journal contains two equal notes $t_{i} = t_{j}, i < j$, then at least one of them was made in newly visited room, because otherwise $t_{j}$ would be at least $i$. Thus there could be at most one note corresponding to previously visited room among equal notes. Let's denote by $cnt_{i}$ number o...
[ "dsu", "greedy", "implementation", "trees" ]
1,300
null
886
D
Restoration of string
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring. You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Res...
If some string is the most frequent then all its substrings are the most frequent too. If string ab or similar is the most frequent then letter $a$ is always followed by letter $b$ and $b$ always follow $a$. Let's consider directed graph on letters where edge $a \rightarrow b$ exists only if ab is the most frequent. ...
[ "constructive algorithms", "graphs", "implementation" ]
2,000
null
886
E
Maximum Element
One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of $n$ positive integers was too slow. D...
You asked to find the number of permutations $p$ of length $n$ such that exists index $i$, such that $p_{i} \neq n$, $p_{i}$ is greater than any $p_{j}$ for j in $[1, i - 1]$ and greater then any $p_{j}$ for j in $[i + 1, i + k]$. We will call such permutations good. Define $D(n)$ as number of good permutations that ...
[ "combinatorics", "dp", "math" ]
2,400
null
886
F
Symmetric Projections
You are given a set of $n$ points on the plane. A line containing the origin is called good, if projection of the given set to this line forms a symmetric multiset of points. Find the total number of good lines. Multiset is a set where equal elements are allowed. Multiset is called symmetric, if there is a point $P$ ...
Let us note that projection of set of points to line move center of mass of initial set to center of mass of initial set to center of mass of projections multiset. So if the line is good then the center of mass of initial set move to center of symmetry. Also If there is two points, which are symmetric with respect to c...
[ "geometry" ]
2,900
null
887
A
Div. 64
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills. Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi...
If the string contains no ones then the answer is "NO" as the remainig number must be positive. Otherwise we can find the leftmost one and check if it is followed by at least six zeroes.
[ "implementation" ]
1,000
null
887
B
Cubes for Masha
Absent-minded Masha got set of $n$ cubes for her birthday. At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural $x$ such she can make using her new cubes all integers from 1 to $x$. To make a number Masha can rotate her cubes and put them in a ro...
The answer is always less or equal to 98. We can go through numbers from 1 to 99 and find the first one which we cannot make using cubes.
[ "brute force", "implementation" ]
1,300
null
887
C
Solution for Cube
During the breaks between competitions, top-model Izabella tries to develop herself and not to be bored. For example, now she tries to solve Rubik's cube 2x2x2. It's too hard to learn to solve Rubik's cube instantly, so she learns to understand if it's possible to solve the cube in some state using 90-degrees rotation...
The amount of variants of input data for which the answer is "YES" is not more than 12 without considering rearrangement of colours. They all could be written in an array. The alternative solution is writing a function of rotating a specific edge of the cube and checking if it is solved.
[ "brute force", "implementation" ]
1,500
null
887
D
Ratings and Reality Shows
There are two main kinds of events in the life of top-model: fashion shows and photo shoots. Participating in any of these events affects the rating of appropriate top-model. After each photo shoot model's rating increases by $a$ and after each fashion show decreases by $b$ (designers do too many experiments nowadays)....
We can create two arrays of prefix sums of events given in input. The first one on values ($a$, $b$) and the second one on values ($c$, $d$). The answer is either 0 or the moment of time right after an event occured. Let's use the method of two pointers. One pointer will indicate an event $V$ after which we want to par...
[ "data structures", "two pointers" ]
2,400
null
887
E
Little Brother
Masha's little brother draw two points on a sheet of paper. After that, he draws some circles and gave the sheet to his sister. Masha has just returned from geometry lesson so she instantly noticed some interesting facts about brother's drawing. At first, the line going through two points, that brother drew, doesn't ...
The center of required circle is on a perpendicular to the middle of the segment $AB$ where $A$ and $B$ are two points from the input. If a circle with the center on the segment $AB$ and the radius equal to half of its length satisfies the conditions then it is the answer. Otherwise we can find on which side relative t...
[ "binary search", "geometry", "sortings" ]
2,800
null
887
F
Row of Models
During the final part of fashion show all models come to the stage and stay in one row and fashion designer stays to right to model on the right. During the rehearsal, Izabella noticed, that row isn't nice, but she can't figure out how to fix it. Like many other creative people, Izabella has a specific sense of beauty...
For every element of an array $a_{i}$ we can check $x$ elements on its right. If there are no elements less than $a_{i}$ we will mark it as "-1" and call it "bad". If there is exactly one element then make an edge from $a_{i}$ to this element. Otherwise swapping elements of the array will never make $a_{i}$ "bad". If t...
[ "greedy", "sortings" ]
2,500
null
888
A
Local Extrema
You are given an array $a$. Some element of this array $a_{i}$ is a local minimum iff it is strictly less than both of its neighbours (that is, $a_{i} < a_{i - 1}$ and $a_{i} < a_{i + 1}$). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, $a_{i} > a_{i - 1}$ and $a_{...
Iterate over indices from $2$ to $n - 1$ and check if at least one of given local extremum conditions holds. Overall complexity: $O(n)$.
[ "brute force", "implementation" ]
800
null
888
B
Buggy Robot
Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell $(0, 0)$. The robot can process commands. There are four types of commands it can perform: - U — move from the cell $(x, y)$ to $(x, y + 1)$; - D — move from $(x, y)$ to $(x, y - 1)$; - L — move from $(x, y)$ t...
Consider the final cell after original path. It has some distance $dx$ to $x = 0$ and $dy$ to $y = 0$. That means the path included at least $dx$ and $dy$ in corresponding directions. Let's remove just these minimal numbers of moves. Finally, the answer will be $n - dx - dy$, where $(dx, dy)$ are distances from the fin...
[ "greedy" ]
1,000
null
888
C
K-Dominant Character
You are given a string $s$ consisting of lowercase Latin letters. Character $c$ is called $k$-dominant iff each substring of $s$ with length at least $k$ contains this character $c$. You have to find minimum $k$ such that there exists at least one $k$-dominant character.
At first, notice that the final answer is minimum over answers for each character. The answer for one character can be obtained like this. Write down lengths of segments between two consecutive occurrences of this character, from the first occurrence to the start of the string and from the last to the end of the string...
[ "binary search", "implementation", "two pointers" ]
1,400
null
888
D
Almost Identity Permutations
A permutation $p$ of size $n$ is an array such that every integer from $1$ to $n$ occurs exactly once in this array. Let's call a permutation an almost identity permutation iff there exist at least $n - k$ indices $i$ ($1 ≤ i ≤ n$) such that $p_{i} = i$. Your task is to count the number of almost identity permutation...
Let's iterate on $m$ - the number of indices such that $p_{i} \neq i$. Obviously, $0 \le m \le k$. How to count the number of permutations with fixed $m$? First of all, we need to choose the indices that have the property $p_{i} \neq i$ - there are $\binom{n}{m}$ ways to do this. Secondly, we need to construct ...
[ "combinatorics", "dp", "math" ]
1,600
null
888
E
Maximum Subsequence
You are given an array $a$ consisting of $n$ integers, and additionally an integer $m$. You have to choose some sequence of indices $b_{1}, b_{2}, ..., b_{k}$ ($1 ≤ b_{1} < b_{2} < ... < b_{k} ≤ n$) in such a way that the value of $\sum_{i=1}^{k}a_{b_{i}}\,m o d\,m$ is maximized. Chosen sequence can be empty. Print th...
Let's consider the naive solution in $O(2^{n})$ or $O(2^{n} \cdot n)$. Iterate over all subsets of original set, calculate sums and take maximum of them modulo $m$. Now we can use meet-in-the-middle technique to optimize it to $O(2^{\lfloor{\frac{n}{2}}\rfloor}\cdot\log(2^{\lfloor{\frac{n}{2}}\rfloor}))$. Preprocess th...
[ "bitmasks", "divide and conquer", "meet-in-the-middle" ]
1,800
null
888
F
Connecting Vertices
There are $n$ points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw $n - 1$ segments, each connecting any two marked points, in such a way that all points have to be connected wi...
We can use dynamic programming to solve this problem, but we need to choose the states we maintain very carefully. One of the approaches might be: $dp[i][j]$ - the number of ways to connect the vertices between $i$ and $j$ to vertices $i$ or $j$ if $i$ and $j$ are already connected (so there is no possibility to connec...
[ "dp", "graphs" ]
2,500
null
888
G
Xor-MST
You are given a complete undirected graph with $n$ vertices. A number $a_{i}$ is assigned to each vertex, and the weight of an edge between vertices $i$ and $j$ is equal to $a_{i} xor a_{j}$. Calculate the weight of the minimum spanning tree in this graph.
We can use Boruvka's algorithm to solve this problem. This algorithm usually works in $O(m\log n)$: initially MST is empty, and then we run a number of iterations. During each iteration we find connected components in the graph formed by already added edges, and for each component we find the shortest edge that leads o...
[ "bitmasks", "constructive algorithms", "data structures" ]
2,300
null
889
E
Mod Mod Mod
You are given a sequence of integers $a_{1}, a_{2}, ..., a_{n}$. Let $f(x,n)=x\operatorname*{mod}\,a_{n}$, and $f(x,i)=(x\,\mathrm{mod}\,a_{i})+f(x\,\mathrm{mod}\,a_{i},i+1)$ for $1 ≤ i < n$. Here, $\mathrm{mod}$ denotes the modulus operation. Find the maximum value of $f(x, 1)$ over all nonnegative integers $x$.
Hint 1: let $x_{i}=x{\mathrm{~mod~}}a_{1}{\mathrm{~mod~}}a_{2}{\mathrm{~mod~}}a_{\cdot}\cdot{\mathrm{~mod~}}a_{i}$. Can you define some interesting segments of value $x_{i}$? Hint 2: think of some dp. Hint 3: once you get the dp in $O(n^{2})$, to speed it up, note the following fact: if $c=a{\mathrm{~mod~}}b$, then eit...
[ "binary search", "dp", "math" ]
3,000
null
891
A
Pride
You have an array $a$ with length $n$, you can perform operations. Each operation is like this: choose two \textbf{adjacent} elements from $a$, say $x$ and $y$, and replace one of them with $gcd(x, y)$, where $gcd$ denotes the greatest common divisor. What is the minimum number of operations you need to make all of th...
Consider $cnt_{1}$ as number of $1$s in the $a$. If $0 < cnt_{1}$ then the answer is $n - cnt_{1}$. otherwise We should find a segment with its $gcd$ equal to 1 and minimum length. consider a segment as $(L, R)$ which $L \le R$ and it's gcd as $D(L, R)$ We fix $L$ and then iterate through all $R$ in order. Consider w...
[ "brute force", "dp", "greedy", "math", "number theory" ]
1,500
null
891
B
Gluttony
You are given an array $a$ with $n$ distinct integers. Construct an array $b$ by permuting $a$ such that for every non-empty subset of indices $S = {x_{1}, x_{2}, ..., x_{k}}$ ($1 ≤ x_{i} ≤ n$, $0 < k < n$) the sums of elements on that positions in $a$ and $b$ are different, i. e. \[ \textstyle\sum_{i=1}^{k}a_{x_{i}}\...
Sort the array and shift it by one. This array will be an answer. Proof: When we shift the sorted array all of the elements become greater except the first one, consider $f = {1, 2, ..., n}$ and $t = {x_{1}, x_{2}, ..., x_{k}}$ if 1 wasn't in t we would have $\textstyle\sum_{i=1}^{k}b_{x_{i}}>\sum_{i=1}^{k}a_{x_{i}}$ $...
[ "constructive algorithms", "greedy" ]
2,000
null
891
C
Envy
For a connected undirected weighted graph $G$, MST (minimum spanning tree) is a subgraph of $G$ that contains all of $G$'s vertices, is a tree, and sum of its edges is minimum possible. You are given a graph $G$. If you run a MST algorithm on graph it would give you only one MST and it causes other edges to become jea...
It can be proven that there's a MST containing these edges if and only if there are MSTs that contain edges with same weight. So for each query we need to check if the edges with weight X have a MST. For checking this, if we remove all edges with weight greater than or equal to X, and consider each connected component ...
[ "data structures", "dsu", "graphs" ]
2,300
null
891
D
Sloth
Sloth is bad, mkay? So we decided to prepare a problem to punish lazy guys. You are given a tree, you should count the number of ways to remove an edge from it and then add an edge to it such that the final graph is a tree and has a perfect matching. Two ways of this operation are considered different if their removed...
If graph had odd number of vertices the answer is $0$. Otherwise let's call edges that by removing them the remaining graph would have two even components good, and all the other edges are bad. If you remove a good edge and put another edge somewhere such that the final graph is a tree, then it would have prefect match...
[ "dfs and similar", "dp", "graph matchings", "trees" ]
3,100
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template<typename T> using pair2 = pair<T, T>; #ifdef WIN32 #define LLD "%I64d" #else #define LLD "%lld" #endif #define pb push_back #define mp make_pair #define all(x...
891
E
Lust
A false witness that speaketh lies! You are given a sequence containing $n$ integers. There is a variable $res$ that is equal to $0$ initially. The following process repeats $k$ times. Choose an index from $1$ to $n$ uniformly at random. Name it $x$. Add to $res$ the multiply of all $a_{i}$'s such that $1 ≤ i ≤ n$, b...
Lemma : expected value of res is equal to multiply of $a_{i}$s minus expected value of multiply of $a_{i}$s at the end of process. Prove : Imagine that at the end of process, $a_{i}$ turns to $b_{i}$ ($b_{i} \le a_{i}$). For this case, it is easy to prove that res is equal to multiply of $a_{i}$s minus multiply of $b...
[ "combinatorics", "math", "matrices" ]
3,000
null
892
A
Greed
Jafar has $n$ cans of cola. Each can is described by two integers: remaining volume of cola $a_{i}$ and can's capacity $b_{i}$ ($a_{i}$ $ ≤ $ $b_{i}$). Jafar has decided to pour all remaining cola into just $2$ cans, determine if he can do this or not!
we sort the capacities in nonincreasing order and let $s = capacity_{1} + capacity_{2}$ if $s<\sum_{i=1}^{n}a_{i}$
[ "greedy", "implementation" ]
900
null
892
B
Wrath
Hands that shed innocent blood! There are $n$ guilty people in a line, the $i$-th of them holds a claw with length $L_{i}$. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the $i$-th person kills the $j$-th person if and only if $j < i$ and $j ≥ i ...
The i'th person will be alive if $min(j - L_{j}) > i$ over all $j > i$. Consider you know the $j$th person is alive or not if $j > i$ and you have $x = min(j - L_{j})$ over all $j > i$. If $x > i$ then the $i$th person will be alive. And you can update $x$ easily.
[ "greedy", "implementation", "two pointers" ]
1,200
null
893
A
Chess For Three
Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three. So they play with each other according to following rules: - ...
This task is about pure implementation. Maintain the number of current spectator and check if he doesn't win. With knowledge of current winner $w$ and current spectator $s$ you can easily get the third player by formula $6 - w - s$ (just the sum of all numbers without the known ones). Overall complexity: $O(n)$.
[ "implementation" ]
900
null
893
B
Beautiful Divisors
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of $k + 1$ consecutive ones, and then $k$ consecutive zeroes. Some examples of beautiful numbers: - $1_{2}$ ($1_{10}$); - $110_{2}$ ($6_{10}$); - $1111000_{2}$ ...
Let's notice that there are only $8$ beautiful numbers less than $10^{5}$. Generate them all and select the greatest one which is also divisor of $n$. Overall complexity: $O(1)$.
[ "brute force", "implementation" ]
1,000
null
893
C
Rumor
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it. Now he tries to solve a quest. The task is to come to a settlement named Ove...
In this problem you are given an undirected graph with weighted vertices. And the problem is to calculate the sum of minimum values in every connected component. To do this we just need to run DFS or BFS several times.
[ "dfs and similar", "graphs", "greedy" ]
1,300
null
893
D
Credit Card
Recenlty Luba got a credit card and started to use it. Let's consider $n$ consecutive days Luba uses the card. \textbf{She starts with $0$ money on her account.} In the \textbf{evening} of $i$-th day a transaction $a_{i}$ occurs. If $a_{i} > 0$, then $a_{i}$ bourles are deposited to Luba's account. If $a_{i} < 0$, th...
The following greedy solution works. Firstly, deposite money only on days with $a_{i} = 0$. Secondly, every time the balance is negative to the day with $a_{i} = 0$, refill it to maximal possible value such that it won't go over $d$ later. Days with $a_{i} \neq 0$ can only lead to invalid state by going over card lim...
[ "data structures", "dp", "greedy", "implementation" ]
1,900
null
893
E
Counting Arrays
You are given two positive integer numbers $x$ and $y$. An array $F$ is called an $y$-factorization of $x$ iff the following conditions are met: - There are $y$ elements in $F$, and all of them are integer numbers; - $\prod_{i=1}^{y}F_{i}=x$. You have to count the number of pairwise distinct arrays that are $y$-facto...
Fill the array with ones. Now we should take every prime divisor $i$ of $x$ and distribute $cnt_{i}$ (maximum power of this prime to appear in $x$) of it into some cells of the array. It is pretty well-known problem, it's equal to $\left\langle\int_{0}^{+\left|{\mathcal{H}}\left|t_{\mathrm{i}}-\right|}\right\rangle$. T...
[ "combinatorics", "dp", "math", "number theory" ]
2,000
null
893
F
Subtree Minimum Query
You are given a rooted tree consisting of $n$ vertices. Each vertex has a number written on it; number $a_{i}$ is written on vertex $i$. Let's denote $d(i, j)$ as the distance between vertices $i$ and $j$ in the tree (that is, the number of edges in the shortest path from $i$ to $j$). Also let's denote the $k$-blocked...
The main idea is to use a two-dimensional data structure: one dimension is depth of vertices, and other dimension is the time we entered a vertex during DFS. Model solution uses sparse table for these purposes. First of all, let's renumerate the vertices so we can handle them easier. We run DFS from the root and then s...
[ "data structures", "trees" ]
2,300
null
894
A
QAQ
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length $n$. There is a great number of "QAQ" in the string (Diamond is so cute!). \begin{center} {\tiny illustration by 猫屋 https://t...
Since $n \le 100$, we can iterate on the place of first 'Q','A' and second 'Q'. The brute force solution will work in $O(n^{3})$ time which can surely pass. If we only iterate on the place of 'A', we can get the number of 'Q' before and after it using prefix sums, and it leads to $O(n)$ solution.
[ "brute force", "dp" ]
800
null
894
B
Ralph And His Magic Field
Ralph has a magic field which is divided into $n × m$ blocks. That is to say, there are $n$ rows and $m$ columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to $k$, where $k$ is e...
First, it's obvious that the numbers put can be only 1 or -1. If $k$ equals to -1 and the parity of $n$ and $m$ differ, the answer is obviously $0$. Otherwise, for the first $(n - 1)$ lines and the first $(m - 1)$ columns, we can put either 1 or -1 in it, and there're $pow(2, [(n - 1) * (m - 1)])$ ways in total. Then i...
[ "combinatorics", "constructive algorithms", "math", "number theory" ]
1,800
null
894
C
Marco and GCD Sequence
In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time. When he woke up, he only remembered that the key was a sequence of positive integers of some length $n$, but forgot the exact sequence. Let the elements of the sequence ...
If the minimum element isn't the gcd of the given set, the answer is -1. Otherwise, we can insert the minimum element between two consecutive elements of the set. And the length of the sequence is $2n - 1$ which satisfies the constraints.
[ "constructive algorithms", "math" ]
1,900
null
894
D
Ralph And His Tour in Binary Country
Ralph is in the Binary Country. The Binary Country consists of $n$ cities and $(n - 1)$ bidirectional roads connecting the cities. The roads are numbered from $1$ to $(n - 1)$, the $i$-th road connects the city labeled $\textstyle{\left\lfloor{\frac{(i+1)}{2}}\right\rfloor}$ (here $⌊ x⌋$ denotes the $x$ rounded down to...
Before answering each query, pre-process on the tree. On each vertice, we can get a sorted array of all the vertices in its subtree sorted by distance to this vertex. And it costs $O(nlog(n))$ time using merge sort or $O(n(log(n))^{2})$ time using std::sort. If you use std::sort, you should implement it carefully or it...
[ "brute force", "data structures", "trees" ]
2,200
null
894
E
Ralph and Mushrooms
Ralph is going to collect mushrooms in the Mushroom Forest. There are $m$ directed paths connecting $n$ trees in the Mushroom Forest. On each path grow some mushrooms. When Ralph passes a path, he collects all the mushrooms on the path. The Mushroom Forest has a magical fertile ground where mushrooms grow at a fantast...
For collecting the most mushrooms, when in a strongly-connected component we can pass all the edges in the component until the mushrooms on the edges are all $0$. So we can run Tarjan's algorithm to find all the SCCs in $O(n + m)$ time and calculate the sum of mushrooms picked in each component by binary search or math...
[ "dp", "graphs" ]
2,100
null
895
A
Pizza Separation
Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into $n$ pieces. The $i$-th piece is a sector of angle equal to $a_{i}$. Vasya and Petya want to divide ...
We can notice that if one of the sectors is continuous then all the remaining pieces also form a continuous sector.If angle of the first sector is equal to $x$ then difference between angles of first and second sectors is $|x - (360 - x)| = |2 * x - 360| = 2 * |x - 180|$. So for each possible continuous sector we can c...
[ "brute force", "implementation" ]
1,200
"#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\nint n;\nint sum;\nint l, r;\nint ans = 360;\nint a[360];\n\nint main()\n{\n\tcin >> n;\n\tfor (int i = 0; i < n; i++)\n\t\tcin >> a[i];\n\twhile (r < n)\n\t{\n\t\tsum += a[r];\n\t\twhile (sum >= 180)\n\t\t{\n\t\t\tans = min(ans, 2 * abs(180 - sum));\...
895
B
XK Segments
While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array $a$ and integer $x$. He should find the number of different ordered pairs of indexes $(i, j)$ such that $a_{i} ≤ a_{j}$ and ther...
First, we need to understand how to find the number of integers in $[l, r]$ segment which are divisible by $x$. It is $r / x-(l - 1) / x$. After that we should sort array in ascending order. For each left boundary of the segment $l = a[i]$ we need to find minimal and maximal index of good right boundaries. All right bo...
[ "binary search", "math", "sortings", "two pointers" ]
1,700
"#include <iostream>\n#include <algorithm>\n\nusing namespace std;\ntypedef long long ll;\n\nll n, x, k;\nll a[100100];\nll ans;\n\nll solve(ll le, ll ri)\n{\n\tif (le > a[n - 1] || ri < a[0])\n\t\treturn 0;\n\tll res = 0;\n\tint l = 0;\n\tint r = n - 1;\n\tint m;\n\twhile (r - l > 1)\n\t{\n\t\tm = (l + r) / 2;\n\t\tif...
895
C
Square Subsets
Petya was late for the lesson too. The teacher gave him an additional task. For some array $a$ Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer. Two ways are considered different if sets of indexes of ele...
We can notice that $x$ is a perfect square of some integer if and only if each prime number enters decomposition of $x$ into prime factors even times. There are only $19$ prime numbers less than $70$. Now we should find the bitmask for each integer in $[1, 70]$ by the following way: There is $1$ in bit representation o...
[ "bitmasks", "combinatorics", "dp", "math" ]
2,000
"#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <iomanip>\n#include <iterator>\n#include <bitset>\n#include <vector>\n#include <math.h>\n#include <queue>\n#include <map>\n#include <set>\n#include <list>\n#include <time.h>\n#include <algorithm>\n#define mkp make_pai...
895
D
String Mark
At the Byteland State University marks are strings of the same length. Mark $x$ is considered better than $y$ if string $y$ is lexicographically smaller than $x$. Recently at the BSU was an important test work on which Vasya recived the mark $a$. It is very hard for the teacher to remember the exact mark of every stud...
Suppose that we can calculate the function $f(s)$ equal to the number of permutations of the string $a$ strictly less than $s$. Then the answer is $f(b) - f(a) - 1$. Now we need to understand how to find $f(s)$. First we should count the number of occurrences of each letter in the string $a$, $cnt[26]$.Than we can iter...
[ "combinatorics", "math", "strings" ]
2,100
// God & me #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e6 + 17, z = 26, mod = 1e9 + 7; int n; string a, b; int cnt[z], c[z], fac[maxn], rfac[maxn], save_rev[maxn]; int solve(string &s){ memcpy(c, cnt, sizeof c); int cur = fac[n]; for(int i = 0; i < z; i++) if(c[i]) ...
895
E
Eyes Closed
Vasya and Petya were tired of studying so they decided to play a game. Before the game begins Vasya looks at array $a$ consisting of $n$ integers. As soon as he remembers all elements of $a$ the game begins. Vasya closes his eyes and Petya does $q$ actions of one of two types: $1)$ Petya says 4 integers $l1, r1, l2, r...
For each position we need to maintain mathematical expectation of the value on it. Initially, for position $i$, it is $a[i]$. Let's process the query of the first type. Each number from the interval $[l1, r1]$ remains on its place with probability $(r1 - l1) / (r1 - l1 + 1)$. The probability that it will be replaced by...
[ "data structures", "probabilities" ]
2,300
// God & me #include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 17, lg = 32; int n, q; double iman[maxn << 2]; struct lz{ double a, b; lz() : a(1), b(0) {} lz(double x, double y) : a(x), b(y) {} } sina[maxn << 2]; lz& operator += (lz &a, const lz &b){ a.a *= b.a; a.b *= b.a; a.b += b.b...
896
A
Nephren gives a riddle
\begin{quote} What are you doing at the end of the world? Are you busy? Will you save us? \end{quote} Nephren is playing a game with little leprechauns. She gives them an infinite array of strings, $f_{0... ∞}$. $f_{0}$ is "What are you doing at the end of the world? Are you busy? Will you save us?". She wants to l...
$f(n) = str_{1} + f(n - 1) + str_{2} + f(n - 1) + str_{3}$. First we can compute the length of $f(n)$ for all possible $n$. For a pair of $(n, k)$, we can easily determine which part the $k$-th character is in. If it's in $f(n - 1)$, we can solve the problem recursively. The complexity of this algorithm is $O(n)$, whic...
[ "binary search", "dfs and similar" ]
1,700
null
896
B
Ithea Plays With Chtholly
This is an interactive problem. Refer to the Interaction section below for better understanding. Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight. Initially, Ithea puts $n$ clear sheets of paper in a line. They are numbered from $1$ to $n$ from left to right. This game wil...
As the initial sheet "has already" in a non-decreasing order (although it has no numbers), what we should do is just "maintain" this order. We use a simple method to do so: find the first sheet whose number is strictly greater than the given number (or it's an empty sheet) and replace it with the new number. For each r...
[ "binary search", "constructive algorithms", "games", "greedy", "interactive" ]
2,000
null
896
C
Willem, Chtholly and Seniorious
\begin{quote} — Willem... — What's the matter? — It seems that there's something wrong with Seniorious... — I'll have a look... \end{quote} Seniorious is made by linking special talismans in particular order. After over 500 years, the carillon is now in bad condition, so Willem decides to examine it thoroughly. S...
This is an interesting algorithm which can easily deal with many data structure problems------if the data is random... I initially named it as "Old Driver Tree" ( Which is my codeforces ID ). (But now I call it Chtholly Tree~). We can find that there is an operation that makes a range of number the same. We can use an ...
[ "data structures", "probabilities" ]
2,600
#include <cstdio> #include <algorithm> #include <map> using namespace std; typedef long long int64; struct IO_Tp { bool is_digit(const char ch) { return '0' <= ch && ch <= '9'; } IO_Tp& operator>>(int& res) { res = 0; static char ch; while (ch = getchar(), !is_digit(ch)) ; do (res *= 10) +=...
896
D
Nephren Runs a Cinema
Lakhesh loves to make movies, so Nephren helps her run a cinema. We may call it No. 68 Cinema. However, one day, the No. 68 Cinema runs out of changes (they don't have 50-yuan notes currently), but Nephren still wants to start their business. (Assume that yuan is a kind of currency in Regulu Ere.) There are three typ...
First let's consider a simpler problem that there are no customers with VIP cards and there are no 50-$yuan$ notes left. For convinence, we suppose that $n$ is an even number. The situation that $n$ is an odd number will be similar. By defining points (number of customers currently, number of 50-$yuan$ note left) on a ...
[ "chinese remainder theorem", "combinatorics", "math", "number theory" ]
2,900
null
896
E
Welcome home, Chtholly
\begin{quote} — I... I survived. — Welcome home, Chtholly. — I kept my promise... — I made it... I really made it! \end{quote} After several days of fighting, Chtholly Nota Seniorious miraculously returned from the fierce battle. As promised, Willem is now baking butter cake for her. However, although Willem is s...
My solution to this problem: Split the array into $O({\sqrt{n}})$ blocks, each containing $O({\sqrt{n}})$ numbers. In each block, for example block $x$, use $f[x][v]$ to represent the number of $v$ in block $x$. For each number $i$, $belong[i]$ is the the block that $i$ is in. We need to maintain each number in the blo...
[ "data structures", "dsu" ]
3,100
#include <iostream> #include <stdio.h> #include <math.h> #define block 254 #define MAXD 400 #define MAXN 100010 + MAXD #define Merge( p , a , b ) if( V[p][a].root ) merge( p , a , b ) #define l( x ) ( x * 254 - 253 ) #define r( x ) ( x * 254 ) using namespace std; int n , m , belong[ MAXN ] , a[ MAXN ]; int pre[ MA...
897
A
Scarborough Fair
\begin{quote} Are you going to Scarborough Fair?Parsley, sage, rosemary and thyme. Remember me to one who lives there. He once was the true love of mine. \end{quote} Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there. Willem asks his friend, Grick for ...
For every $i$ in range $[l, r]$, if $c_{i}$ is $c_{1}$ then change it into $c_{2}$... Because $n, m$ are all very small, $O(nm)$ can easily pass it. PS. You can use binary search tree to solve it in $O(m\log n)$ time.
[ "implementation" ]
800
null
897
B
Chtholly's request
\begin{quote} — Thanks a lot for today.— I experienced so many great things. — You gave me memories like dreams... But I have to leave now... — One last request, can you... — Help me solve a Codeforces problem? — ...... — What? \end{quote} Chtholly has been thinking about a problem for days: If a number is palin...
The $k$-th smallest zcy number is $conn(str(k), rev(str(k)))$, where $str$ denotes the decimal representation of a positive integer as a string, $conn$ denotes the concatenation two strings, and $rev$ denotes the reverse of a string. Then go over the smallest $k$ such numbers and sum them up to obtain the answer.
[ "brute force" ]
1,300
null
898
A
Rounding
Vasya has a non-negative integer $n$. He wants to round it to nearest integer, which ends up with $0$. If $n$ already ends up with $0$, Vasya considers it already rounded. For example, if $n = 4722$ answer is $4720$. If $n = 5$ Vasya can round it to $0$ or to $10$. Both ways are correct. For given $n$ find out to whi...
At first let's round down the given number $n$ to the nearest integer which ends with $0$ and store this value in a variable $a$: $a = (n / 10) * 10$. So, the round up $n$ (call it $b$) is $b = a + 10$. If $n - a > b - n$ then the answer is $b$. In the other case, the answer is $a$.
[ "implementation", "math" ]
800
null
898
B
Proper Nutrition
Vasya has $n$ burles. One bottle of Ber-Cola costs $a$ burles and one Bars bar costs $b$ burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars. Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend \textbf{exactl...
To solve this problem we need to brute how many bottles of Ber-Cola Vasya will buy. Let this number equals to $x$. Then, if $n - a \cdot x$ is non-negative and divided by $b$ we found the answer - Vasya should by $x$ bottles of Ber-Cola and $(n - a \cdot x) / b$ Bars bars. In case that $(n - a \cdot x)$ became negative...
[ "brute force", "implementation", "number theory" ]
1,100
null
898
C
Phone Numbers
Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers. Vasya decided to organize information about the phone numbers of friends. You will be given $n$ strings — all entries from Vasya's phone books. Each entry starts with a f...
Let's use map from string to vector of strings to simplify implementation. The map keys is friend names, and the values - list of phone numbers. At first let's put all input data in map, but if vector for a current friend already contains a current number we should not put this number in the vector (for example, we can...
[ "implementation", "strings" ]
1,400
null
898
D
Alarm Clock
Every evening Vitalya sets $n$ alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer $a_{i}$ — number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute. Vitalya will...
At first we need to sort all alarms in increasing order of their times. Also we will use set, where we will store alarm times. We will iterate through the alarms beginning from the first. Let current alarm time equals to $x$. Until set does not empty and the first set element less than $x - m + 1$ we should remove the ...
[ "greedy" ]
1,600
null
898
E
Squares and not squares
Ann and Borya have $n$ piles with candies and $n$ is even number. There are $a_{i}$ candies in pile with number $i$. Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this ca...
At first we need to implement a function to check integer $a$ if it is a square of an integer. Let $x$ is a round down square root of $x$. If $x \cdot x = = a$ then $a$ is a square of an integer. Let's calculate two values: $cnt_{1}$ - how many given numbers are integer squares and $cnt_{2}$ - how many given numbers ar...
[ "constructive algorithms", "greedy" ]
1,600
null
898
F
Restoring the Expression
A correct expression of the form a+b=c was written; $a$, $b$ and $c$ are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits ...
At first we should calculate "hash" by big prime module from the given string, and the base must be equal to $10$ because we work with numbers. We can use prime module about $10^{15}$, if we will use multiple of long longs by module with help of long doubles. After that we will brute the length of the result of summati...
[ "brute force", "hashing", "math" ]
2,300
null
899
A
Splitting in Teams
There were $n$ groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of tea...
it is profitably to the coach to unite groups from two students with groups from one student and after that unite in teams three groups from one student. Let's calculate two values: $cnt_{1}$ - the number of groups from one student, and $cnt_{2}$ - the number of groups from two students. Then if $cnt_{1} > cnt_{2}$ - t...
[ "constructive algorithms", "greedy", "math" ]
800
null
899
B
Months and Years
Everybody in Russia uses Gregorian calendar. In this calendar there are $31$ days in January, $28$ or $29$ days in February (depending on whether the year is leap or not), $31$ days in March, $30$ days in April, $31$ days in May, $30$ in June, $31$ in July, $31$ in August, $30$ in September, $31$ in October, $30$ in No...
Note, that $n \le 24$, so we should consider the following cycle: not leap-year - leap-year - not leap-year - not leap-year. This cycle repeats every $4$ years, except in some cases. We should generate an array describing the duration of the months in the described cycle. After that we should check that the given seq...
[ "implementation" ]
1,200
null
899
C
Dividing the numbers
Petya has $n$ integers: $1, 2, 3, ..., n$. He wants to split these integers in \textbf{two non-empty} groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of $n$ integers should be exactly in one group.
To solve this problem we should consider $4$ cases. If $n$ divided by $4$ without remnant than the sum of all numbers from $1$ to $n$ is even. Then we can divide numbers on two groups in such a way that absolute difference between sum of numbers in each part is $0$. To make it we should take in one group all numbers wh...
[ "constructive algorithms", "graphs", "math" ]
1,300
null
899
D
Shovel Sale
There are $n$ shovels in Polycarp's shop. The $i$-th shovel costs $i$ burles, that is, the first shovel costs $1$ burle, the second shovel costs $2$ burles, the third shovel costs $3$ burles, and so on. Polycarps wants to sell shovels in pairs. Visitors are more likely to buy a pair of shovels if their total cost ends...
At first let's check that the sum $sum = n + (n - 1)$ consisting of only digits nine. If it is true then the answer is $1$. In the other case, we should calculate the number of digits in the number $sum$. Let this value if $len$. We should construct the number $cur$ which consisting of $(len - 1)$ digits nine. After th...
[ "constructive algorithms", "math" ]
1,800
null
899
E
Segments Removal
Vasya has an array of integers of length $n$. Vasya performs the following operations on the array: on each step he finds the longest segment of consecutive equal integers (the leftmost, if there are several such segments) and removes it. For example, if Vasya's array is $[13, 13, 7, 7, 7, 2, 2, 2]$, then after one op...
We will use to set of pairs. In the first set (call it $len$) we will store all segments consisting of the same numbers in a format - the length of the segment multiplied on $- 1$ and the position of the beginning of the segment. In the second set (call it $segments$) we will store all segments consisting of the same n...
[ "data structures", "dsu", "flows", "implementation", "two pointers" ]
2,000
null
899
F
Letters Removing
Petya has a string of length $n$ consisting of small and large English letters and digits. He performs $m$ operations. Each operation is described with two integers $l$ and $r$ and a character $c$: Petya removes from the string all characters $c$ on positions between $l$ and $r$, inclusive. It's obvious that the lengt...
For each character $c$ we should use set, where we will store positions of all non-deleted characters $c$. Let the next query equals to $l, r, c$. Then at first we should transform the given positions $l$ and $r$ to the positions of the initial string, taking into account already deleted characters. We can do it with h...
[ "data structures", "strings" ]
2,100
null
900
A
Find Extra One
You have $n$ distinct points on a plane, none of them lie on $OY$ axis. Check that there is a point after removal of which the remaining points are located on one side of the $OY$ axis.
Count number of points located on left and right side of the $OY$ axis. Answer will be "Yes" if number of points of one of the sets is smaller than two, "No" - otherwise. Time complexity $O(n)$.
[ "geometry", "implementation" ]
800
null
900
B
Position in Fraction
You have a fraction $\overset{\stackrel{\alpha}{b}}$. You need to find the first occurrence of digit $c$ into decimal notation of the fraction after decimal point.
In this task you should complete long division and stop, when one period passed. Period can't be more than $b$ by pigeonhole principle. So you need to complete $b$ iterations and if $c$ digit hasn't been met, print $- 1$. Time complexity $O(b)$.
[ "math", "number theory" ]
1,300
null
900
C
Remove Extra One
You are given a permutation $p$ of length $n$. Remove one element from permutation to make the number of records the maximum possible. We remind that in a sequence of numbers $a_{1}, a_{2}, ..., a_{k}$ the element $a_{i}$ is a record if for every integer $j$ ($1 ≤ j < i$) the following holds: $a_{j} < a_{i}$.
In this problem you have to find an element after which removal the number of records is maximum possible. Let $r_{i}$ be an array consisting of $0$ and $1$ depending on whether the $i$-th element was a record initially or not. We can compute it easily in $O(N)$. Let $x_{i}$ be the difference between the number of reco...
[ "brute force", "data structures", "math" ]
1,700
null
900
D
Unusual Sequences
Count the number of distinct sequences $a_{1}, a_{2}, ..., a_{n}$ ($1 ≤ a_{i}$) consisting of positive integers such that $gcd(a_{1}, a_{2}, ..., a_{n}) = x$ and $\textstyle\sum_{i=1}^{n}a_{i}=y$. As this number could be large, print the answer modulo $10^{9} + 7$. $gcd$ here means the greatest common divisor.
It's obvious that if $y$ is not divisible by $x$, then the answer is $0$. Let $f(t)$ be the number of sequences such that their sum is $t$, and $gcd$ is $1$. Then the answer for the problem is $f{\bigl(}{\frac{y}{x}}{\bigr)}$. How to compute $f(t)$?. Let's denote the number of sequences such that their sum is $t$ as $g...
[ "bitmasks", "combinatorics", "dp", "math", "number theory" ]
2,000
null
900
E
Maximum Questions
Vasya wrote down two strings $s$ of length $n$ and $t$ of length $m$ consisting of small English letters 'a' and 'b'. What is more, he knows that string $t$ has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions. Suddenly in the morning, Vasya found that somebody spoiled ...
Let's find all positions $i$ in string $s$ such that occurrence $t$ can start at position $i$ after making some replacements. How to find them? As $t$ has a form "abab..." letters $s_{i}, s_{i + 2}, s_{i + 4}, ..., s_{(i + m - 1|i + m - 2)}$ should be equal to '?' or 'a' and $s_{i + 1}, s_{i + 3}..., s_{(i + m - 1|i + ...
[ "data structures", "dp", "strings" ]
2,100
null
901
A
Hashing Trees
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of tree...
There are many ways to solve the problem. First of all you should build any single tree. To do this, you first build the longest path from the root and then attach remained vertices on proper heights. Thus each vertex is either on the longest path or has parent on this path. To build the second tree you should use diff...
[ "constructive algorithms", "trees" ]
1,500
null
901
B
GCD of Polynomials
Suppose you have two polynomials $A(x)=\sum_{k=\mathbf{a}}^{n}a_{k}x^{k}$ and $B(x)=\sum_{k=\mathbb{Q}}^{m}b_{k}x^{k}$. Then polynomial $A(x)$ can be uniquely represented in the following way: \[ A(x)=B(x)\cdot D(x)+R(x),\deg R(x)<\deg B(x). \] This can be done using long division. Here, $\deg P(x)$ denotes the degre...
As for integers it is well known that worst case are consequent Fibonacci's numbers $F_{n + 1} = F_{n} + F_{n - 1}$. Solutions to this problem are based on the same idea. There were two main intended solutions. First of all you should note that sequence $p_{0} = 1, p_{1} = x,$ $p_{n + 1} = x \cdot p_{n} \pm p_{n - 1}...
[ "constructive algorithms", "math" ]
2,200
null
901
C
Bipartite Segments
You are given an undirected graph with $n$ vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from $1$ to $n$. You have to answer $q$ queries. Each query is described by a segment of vertice...
If two cycles of odd length intersect, then they can be bypassed so as to obtain an edge-simple cycle of even length. It follows that the given graph is a vertex cactus, with cycles of odd length, then the vertex segment is good - if there is no loop, that the vertex with the minimum number from this cycle is present o...
[ "binary search", "data structures", "dfs and similar", "dsu", "graphs", "two pointers" ]
2,300
null
901
D
Weighting a Tree
You are given a connected undirected graph with $n$ vertices and $m$ edges. The vertices are enumerated from $1$ to $n$. You are given $n$ integers $c_{1}, c_{2}, ..., c_{n}$, each of them is between $ - n$ and $n$, inclusive. It is also guaranteed that the parity of $c_{v}$ equals the parity of degree of vertex $v$. ...
Let's solve two cases. First case is when graph is the bipartite graph Then the sum of weights of the left part should be equal to the sum of weights of the right part (because each edge will bring an equal contribution to the sums of both part). We will leave any spanning tree of this graph, then for it the solution i...
[ "constructive algorithms", "dfs and similar", "graphs" ]
2,700
"#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <iomanip>\n#include <bi...
901
E
Cyclic Cipher
Senor Vorpal Kickass'o invented an innovative method to encrypt integer sequences of length $n$. To encrypt a sequence, one has to choose a secret sequence $\{b_{i}\}_{i=0}^{n-1}$, that acts as a key. Vorpal is very selective, so the key should be such a sequence $b_{i}$, that its cyclic shifts are linearly independen...
$(a - b)^{2} = a^{2} + b^{2} - 2ab$, hence, $c_{k}-c_{k-1}=-2\sum_{i=1}^{n-1}b_{i}(a_{i+k}-a_{i+k-1})$. Let $a'_{i} = a_{i} - a_{i - 1}$, $c_{k}^{\prime}={\frac{c_{k-1}-c_{k}}{2}}$. Then $c_{k}^{\prime}=\sum_{i=0}^{n-1}b_{i}a_{i+k}^{\prime}\;\;\mathrm{mod}\;n=\sum_{u-x=k}\sum_{\mathrm{mod}\;n}b_{x}a_{y}^{\prime}$. This...
[ "fft", "math" ]
3,300
null