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. So, for example, if $s$ is aaaa, $a$ is aa and index $3$ is forbidden, then $f(a) = 2$ because there are three occurences of $a$ in $s$ (starting in indices $1$, $2$ and $3$), but one of them (starting in index $2$) ends in a forbidden index.
Calculate the maximum possible value of $|a|·f(a)$ you can get.
|
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 choose $a$ is to use a suffix which begins in the leftmost (after reversing $s$) non-forbidden index. $f(a) > 1$, then $a$ is the longest common prefix of some two suffixes of $s$. Let's build a suffix array, then calculate the LCP array. Then recall the fact that a LCP of two suffixes is the minimum on the segment of LCP array between these two suffixes, so we can use a common stack algorithm that will for each LCP find the segment of suffixes such that this LCP is a prefix of these suffixes (to do this, for each element of LCP array we find the largest segment such that this element is minimal on that segment), and then we can use prefix sums to find the number of non-forbidden suffixes such that chosen LCP is a prefix of this suffix (and so calculate $f(a)$ easily for each LCP).
|
[
"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 \textbf{positive integer} $x$ was given. The task was to add $x$ to the sum of the digits of the number $x$ written in decimal numeral system.
Since the number $n$ on the board was small, Vova quickly guessed which $x$ could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number $n$ for all suitable values of $x$ or determine that such $x$ does not exist. Write such a program for Vova.
|
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 come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
- He looks through all the coins from left to right;
- If he sees that the $i$-th coin is still in circulation, and $(i + 1)$-th coin is already out of circulation, he exchanges these two coins and continues watching coins from $(i + 1)$-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts $n$ coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for $n$ times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
|
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 already sorted and the answer is $1$. Let 1 appears $k$ times to the left of the rightmost zero. For one iteration the nearest 1 on the left will move to the position of this zero, and zero will move one position to the left. After this iteration, $k - 1$ ones will remain to the left of the rightmost zero. Hence the answer is $k + 1$. Let us return to the original problem. We will keep the pointer to the rightmost zero. Since as a result of queries the zeros only disappear, the pointer moves only to the left. If the rightmost zero has disappeared, move the pointer to the left by a cycle, until we find the next zero. Consider pointer is at the position $x$ (numeration from zero), and there are only $p$ ones in the array. On the right of $x$ all the symbols are ones so on the right there are only $n-x-1$ ones. So on the left are $p-(n-x-1)$ ones. This solution works in $O(n + q)$.
|
[
"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 version of a letter $x$ is denoted by $x'$. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are \textbf{before} all small letters. For example, the following conditions hold: $2 < 3$, $2' < 3'$, $3' < 2$.
A word $x_{1}, x_{2}, ..., x_{a}$ is not lexicographically greater than $y_{1}, y_{2}, ..., y_{b}$ if one of the two following conditions holds:
- $a ≤ b$ and $x_{1} = y_{1}, ..., x_{a} = y_{a}$, i.e. the first word is the prefix of the second word;
- there is a position $1 ≤ j ≤ min(a, b)$, such that $x_{1} = y_{1}, ..., x_{j - 1} = y_{j - 1}$ and $x_{j} < y_{j}$, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "$3'$ $7$ $5$" is before the word "$2$ $4'$ $6$" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in \textbf{all} words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be \textbf{equal}.
|
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_{i, k} > s_{i + 1, k}$, you capitalize $s_{i, k}$ and not capitalize $s_{i, k + 1}$. If $s_{i, k} < s_{i + 1, k}$, both these letters should be capitalized or not capitalizes simultaneously. Let's make a graph in which letters will be vertexes. If $s_{i, k} > s_{i + 1, k}$, then mark $s_{i, k}$ as capitalized, otherwise make a directed edge between $s_{i + 1, k}$ and $s_{i, k}$. It means that if we capitalize $s_{i + 1, k}$, you also should capitalize $s_{i, k}$. Note that our graph is acyclic because the edges are directed from big letters to small letters. Using dfs we capitalize all the letters, that are reachable from the capitalized letters and check the answer. If the answer is wrong, there is no answer.
|
[
"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 ridge: if Rick and Morty begin crying simultaneously from different mountains, their cry would be heard between these mountains up to the height equal the bitwise OR of mountains they've climbed and all the mountains between them.
Bitwise OR is a binary operation which is determined the following way. Consider representation of numbers $x$ and $y$ in binary numeric system (probably with leading zeroes) $x = x_{k}... x_{1}x_{0}$ and $y = y_{k}... y_{1}y_{0}$. Then $z = x | y$ is defined following way: $z = z_{k}... z_{1}z_{0}$, where $z_{i} = 1$, if $x_{i} = 1$ or $y_{i} = 1$, and $z_{i} = 0$ otherwise. In the other words, digit of bitwise OR of two numbers equals zero if and only if digits at corresponding positions is both numbers equals zero. For example bitwise OR of numbers $10 = 1010_{2}$ and $9 = 1001_{2}$ equals $11 = 1011_{2}$. In programming languages C/C++/Java/Python this operation is defined as «|», and in Pascal as «or».
Help Rick and Morty calculate the number of ways they can select two mountains in such a way that if they start crying from these mountains their cry will be heard above these mountains and all mountains between them. More formally you should find number of pairs $l$ and $r$ ($1 ≤ l < r ≤ n$) such that bitwise OR of heights of all mountains between $l$ and $r$ (inclusive) is larger than the height of any mountain at this interval.
|
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 in $x$. So you can just pass from left to the right (and then from right to the left) along the array, calculating $go_{i}$ - the nearest on the left (on the right) element in which the bit $i$ equals $1$. We fix the mountain which will be the highest on the segment from the answer (if the heights are equal - the most left, for example). Then the segment must be completely nested in the segment on which the given mountain is the highest and must cross at least one element, OR with which our element is greater than the element itself. This solution works in $O(n) + O(nlogc) + O(n) = O(nlogc)$.
|
[
"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 at the point with the coordinate $s_{2}$, and the clients are at the points $x_{1}, x_{2}, ..., x_{n}$ in the order of the required visit.
The guys agree in advance who of them will deliver the package to which of the customers, and then they act as follows. When the package for the $i$-th client is delivered, the one who delivers the package to the $(i + 1)$-st client is sent to the path (it can be the same person who went to the point $x_{i}$, or the other). The friend who is not busy in delivering the current package, is standing still.
To communicate with each other, the guys have got walkie-talkies. The walkie-talkies work rather poorly at great distances, so Petya and Vasya want to distribute the orders so that the maximum distance between them during the day is as low as possible. Help Petya and Vasya to minimize the maximum distance between them, observing all delivery rules.
|
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 transition can be done immediately by several steps forward. Transition from $i$ to $j$ means that the first courier will execute the orders $i + 1, i + 2, ... j - 1$, and the second - the order with the number $j$. The transition can be made if $|x_{j} - x{j - 1}| \le p$ and $|x_{k} - x{i - 1}| \le p$ for all $k$ from $i$ to $j - 1$. It may be rewritten as $x_{i - 1} - p \le x_{k} \le x_{i - 1} + p$, and so the maximum $j$ for given $i$ can be found using segment tree or analogical structure. After that you only set $dp_{j} = 1$ to all possible $j$ on the segment. It can be done for example going along the massive and knowing maximum segment of possible $j$. The solution works in $O(nlognlogANS)$.
|
[
"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 asked neighboring kingdoms, and after a while several delegations arrived with $m$ unmarried princesses. Receiving guests, Karl learned that the dowry of the $i$ th princess is $w_{i}$ of golden coins.
Although the action takes place in the Middle Ages, progressive ideas are widespread in society, according to which no one can force a princess to marry a prince whom she does not like. Therefore, each princess has an opportunity to choose two princes, for each of which she is ready to become a wife. The princes were less fortunate, they will obey the will of their father in the matter of choosing a bride.
Knowing the value of the dowry and the preferences of each princess, Charles wants to play weddings in such a way that the total dowry of the brides of all his sons would be as great as possible. At the same time to marry all the princes or princesses is not necessary. Each prince can marry no more than one princess, and vice versa, each princess can marry no more than one prince.
Help the king to organize the marriage of his sons in the most profitable way for the treasury.
|
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 finding alternating chain. But this solution can be speed up. Let's try to attribute to each (not isolated) vertex of right part the most expensive vertex of left part. If resulting set of edges is a matching it will be the solution. The set of edges can not form matching only if in the left part there are some vertexes for which both edges are taken. Let's name these vertexes "popular". Suppose that we didn't take any popular vertex in the optimal answer. Then you can take any its neighbor from right part and improve the answer. That' why weight of popular vertex can be added to the answer and remove it from the graph uniting its neighbors to one vertex. This vertex will describe the prince who has not got popular princess. As in the previous case we'll consider vertexes of left part in descending order and the vertexes of right part we will keep is disjoint set union. If the current vertex of right part has two neighbors in right part, we add its weight to the answer and unite its neighbors in DSU. In the vertex has one neighbor in right part, we add the weight of vertex to the answer and remove the vertex of right part. Otherwise we don't add the weight of vertex to the answer. Solution works in $O(nlogn)$.
|
[
"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 and Eeyore's house is $b$ meters, between Owl's and Eeyore's house is $c$ meters.
For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal $n$ times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).
Winnie-the-Pooh does not like physical activity. He wants to have a meal $n$ times, traveling minimum possible distance. Help him to find this distance.
|
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 in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.
|
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 by its name.
It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name \textbf{exactly once}. His friends' names are "Danil", "Olya", "Slava", "Ann" and "Nikita".
\textbf{Names are case sensitive.}
|
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 to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?
|
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 $i$ and $j$. Then length of string is $(pref_{a}[n] - pref_{a}[j]) + (pref_{b}[j] - pref_{b}[i]) + (pref_{a}[i])$. Using two for loops we find optimal $i$ and $j$ and calculate answer. 877C - Slava and tanks
|
[
"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 flies very high, but he can drop a bomb in any cell. All tanks in this cell will be damaged.
If a tank takes damage for the first time, it instantly moves to one of the neighboring cells (a tank in the cell $n$ can only move to the cell $n - 1$, a tank in the cell $1$ can only move to the cell $2$). If a tank takes damage for the second time, it's counted as destroyed and never moves again. The tanks move only when they are damaged for the first time, they do not move by themselves.
Help Slava to destroy all tanks using as few bombs as possible.
|
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. Throw bombs in all even positions again. Now all tanks are extemintated. It's not hard to prove that this strategy is optimal. 877D - Olya and Energy Drinks
|
[
"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 chooses one of the four directions (up, down, left or right) and runs from $1$ to $k$ meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell $(x_{1}, y_{1})$ to cell $(x_{2}, y_{2})$. How many seconds will it take her if she moves optimally?
It's guaranteed that cells $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ are empty. These cells can coincide.
|
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 summary it works in $O(n \cdot m \cdot log(n))$. 877E - Danil and a Part-time Job
|
[
"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 each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on.
Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages.
There are two types of tasks:
- pow v describes a task to switch lights in the subtree of vertex $v$.
- get v describes a task to count the number of rooms in the subtree of $v$, in which the light is turned on. Danil should send the answer to his boss using Workforces messages.
A subtree of vertex $v$ is a set of vertices for which the shortest path from them to the root passes through $v$. In particular, the vertex $v$ is in the subtree of $v$.
Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him.
|
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 subsegment that the sale operates on it and the number of math problems is greater than the number of economics problems \textbf{exactly} by $k$. Note that $k$ may be positive, negative or zero.
Unfortunately, Ann is not sure on which segment the sale operates, but she has $q$ assumptions. For each of them she wants to know the number of options to buy a subsegment satisfying the condition (because the time she spends on choosing depends on that).
Currently Ann is too busy solving other problems, she asks you for help. For each her assumption determine the number of subsegments of the given segment such that the number of math problems is greaten than the number of economics problems on that subsegment exactly by $k$.
|
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 $i$ in segment. Then we'll add $cnt[p[i] - k]$ to answer. $p[i]$ can be big enought, so we should use something like map. This is where the logarithm comes from. Note, that we can easily move both borders to the left and to the right. Then we can solve it using Mo's algorhitm in $O(q \cdot sqrt(n) \cdot log(n))$. Unfortunatelly, it's still too slow. Let's use coordinate compression. For each prefsum calculate $v[i]$ - compressed value of $p[i]$, $l[i]$ - compressed value $p[i] - k$ and $r[i]$ - compressed value $p[i] + k$. It allows us to get rid of logarithm.
|
[
"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 arbitrary sequence of these operations with arbitrary constants from $0$ to $1023$. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.
Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than $5$ lines. Your program should return the same integer as Petya's program for all arguments from $0$ to $1023$.
|
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 happens to it. Now let's write a program of three lines: Depending on the implementation, it may works in $O(n)$ or $O(n\log X)$. BONUS: solve a problem using at most two commands.
|
[
"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 then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence $a_{1}, a_{2}, ..., a_{n}$ repeated $m$ times).
After that some teams were formed, each consisting of $k$ participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no $k$ neighboring participants from the same city.
Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected.
|
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 border, a team is formed, if $c_{1} = c_{r}$ and $d_{1} + d_{r} \ge k$. If the inequality becomes an equality, then another team can be formed from the second and penultimate groups, etc. Let's find the greatest $p$ such that for each $i = 1... p$ we have $c_{i} = c_{r + 1 - i}$ and $d_{i} + d_{r + 1 - i} = k$. Since the condition on $i$ is symmetric with respect to $i\mapsto r+1-i$, if $p \ge \lceil r / 2 \rceil $, then $p = r$. Consider the case $p = r$ separately. This means that the two buses are completely divided into teams. If $m$ is even, answer is zero, otherwise answer is the sum of $d_{i}$. Also, consider the case when $r$ is odd and $p = \lfloor r / 2 \rfloor $. In this case, after removing all teams at the borders of the buses, the queue looks like: left part of the first bus - $md_{p + 1}$ people from the $c_{p + 1}$ city - right part of the last bus. If the number of people in the middle is divisible by $k$, then they will be divided into the commands, and the first half will unite with the last, and the answer is zero. If it doesn't, then some teams will be formed in the middle, and the process will end there. Finally, if $r$ is even smaller, it can be seen that after the formation of teams at the borders of buses the process will end.
|
[
"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 of the $k$ kinds of sport. Loser leaves the tournament. The last remaining sportsman becomes the winner. Apart of this, the scheme can be arbitrary, it is not disclosed in advance.
Vasya knows powers of sportsmen in each kind of sport. He believes that the sportsmen with higher power always wins.
The tournament is held every year, and each year one new participant joins it. In the first tournament, only one sportsman has participated, in the second there were two sportsmen, and so on. Vasya has been watching the tournament for the last $n$ years. Help him to find the number of possible winners for each of the $n$ tournaments.
|
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. Since for any two vertices there is an edge at least in one direction, condensation is a path. It is clear that the required tree exists if and only if the root lies in the first strongly connected component. We will maintain these strongly connected components. For each of them we will store its size, the greatest power and the smallest power in each kind of sports. What happens when the new sportsman is added? He can defeat the component if in some kind of sports he is stronger than the minimum in this component. Similarly, he can lose to a component if in some kind of sports he is weaker than the maximum in this component. We need to find the weakest of those components that he can lose, and the strongest of those components that he can defeat. If the first component is stronger than the second, the new sportsman forms a new component. Otherwise, all the components between the first and the second merge into one, and the new sportsman joins it. How to do it effectively? We will store the components in a some search tree and use the comparison by minimum in the first kind of sports as a comparator. It's easy to see that if you take any other sport or replace a minimum with a maximum, any two components will be compared in the same way. All we need is binsearch by one of the mentioned comparators: minimum or maximum for one of the kinds of sports. At each step the number of operations with the tree is $O(k)$ + $k \cdot $ number of components merged into one. At each step at most one component can be added, so the amortized time of one step is $O(\log n)$. Overall time complexity is $O(n k\log n)$.
|
[
"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 the maximum of the corresponding characteristics of used creatures. Nikita has a similar spell, but in his spell, each characteristic of the new creature is equal to the minimum of the corresponding characteristics of used creatures. A new creature gets the smallest unused number.
They use their spells and are interested in some characteristics of their new creatures. Help them find out these characteristics.
|
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_{1} \le x_{2} \le ... \le x_{k}$. Let's make $k$ characteristics from it. $i$-th of them is one if and only if the original characteristic is at least $x_{i}$, and zero otherwise. New characteristics behave correctly during our operations, and we can efficiently get old characteristics from them. Number of characteristics has increased, but is doesn't matter for our solution for the special case. This solution works in $O(q2^{k})$.
|
[
"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 numbers and will get the biggest possible number.
Nikita wants to get to the blackboard before Sasha and erase some of the numbers. He has $q$ options, in the option $i$ he erases all numbers to the left of the $l_{i}$-th number and all numbers to the right of $r_{i}$-th number, i. e. all numbers between the $l_{i}$-th and the $r_{i}$-th, inclusive, remain on the blackboard. For each of the options he wants to know how big Sasha's final number is going to be. This number can be very big, so output it modulo $10^{9} + 7$.
|
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 the greatest $i$ such that $k_{i} = 1$. It always exists cause $k_{2} = 1$. By the induction hypothesis we can get $k_{1}, k_{2}... k_{i - 1}$ and $k_{i} - 1, k_{i + 1} - 1... k_{n} - 1$. Do this and merge them with the last move. Now we describe the strategy. Let the last number be negative. Then Sasha wants to minimize $k_{n}$. He always can use $k_{n} = 1$. If tha last number is non-negative, he can use $k_{n} = k_{n - 1} + 1$. In this case, Sasha first merges the last two numbers. Thus, the sequence $k_{i}$ consists of several blocks, in each of which $k_{i + 1} = k_{i} + 1$, and each of the blocks except the first begins with 1. Now we need to answer queries. We will do it offline. On the step $i$ add the number $a_{i}$ and and answer all queries with $r = i$. We will support the blocks for the query $[1, i]$. What happens when we add a number? If it's negative, it simply forms a separate block. Otherwise it becomes the end of some block. It is easy to see that the new block is the union of several old blocks. How to answer queries? $[l, r]$ is the union of some blocks and a suffix of another block. We can see that this is the partition into blocks for our query. How to do it fast? We will store the boundaries of blocks to do binary search on them and find the block in which the $l$ lies. We need to store the results for each block and prefix sums of these results. Also we need to find sums $\sum_{j=1}^{i}a_{j}2^{j}$ to find out results for suffixes. Each step is processed in $O(\log n)$ except for merging blocks. But we create at most one block on each step, so amortized time of each step is $O(\log n)$. Also in this problem we need to be careful with overflows. Although we need to find the result modulo some prime, in some places the sign is important. We can use that if $|y|$ is more than maximum $a_{i}$, then $x + 2y$ is also big and have the same sign.
|
[
"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 get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor $i$ goes to work on the $s_{i}$-th day and works every $d_{i}$ day. So, he works on days $s_{i}, s_{i} + d_{i}, s_{i} + 2d_{i}, ...$.
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
|
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 doctor is working on that day. At the step $i$ we need to go through at most $max(s_{i}, d_{i})$ days. There is a more efficient way. We can find the smallest $x$ that is greater than the current day, such that $x\equiv s_{i}{\bmod{d}}_{i}$, in $O(1)$. If $x \ge s_{i}$, Borya will visit a doctor on day $x$, otherwise on day $s_{i}$. This solution is $O(n)$.
|
[
"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 the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
|
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, this solution is too slow. Let's think what happens if $k$ is large. More precisely, assume that $k \ge n - 1$. The winner need to win at least $n - 1$ games in a row, that is, he need to win against all the other players. Hence, the winner is just the strongest player. So, if $k \ge n - 1$, we can solve the problem in $O(1)$. Otherwise simulation works in $O(n)$.
|
[
"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, she can spend it on reading.
Help Luba to determine the minimum number of day when she finishes reading.
\textbf{It is guaranteed that the answer doesn't exceed $n$.}
\textbf{Remember that there are 86400 seconds in a day.}
|
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$ and the crossword is $111011$, then its encoding is an array ${3, 2}$;
- If $x = 8$ and the crossword is $01101010$, then its encoding is an array ${2, 1, 1}$;
- If $x = 5$ and the crossword is $11111$, then its encoding is an array ${5}$;
- If $x = 5$ and the crossword is $00000$, then its encoding is an empty array.
Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is \textbf{exactly one} crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!
|
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. Its destination station is $p_{i}$, possibly $p_{i} = i$;
- For each station $i$ there exists exactly one station $j$ such that $p_{j} = i$.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs $(x, y)$ such that person can start at station $x$ and, after taking some subway trains (possibly zero), arrive at station $y$ ($1 ≤ x, y ≤ n$).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of $p_{i}$ for \textbf{not more than two subway stations}. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
|
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 joining together. $f(a, b) = (a^{2} + 2ab + b^{2}) - a^{2} - b^{2} = 2ab$. Now its easily seen that the maximum is achived when joining two cycles with the greatest product of lengths. Finally they are the two longest cycles in permutation. Overall complexity: $O(n)$.
|
[
"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. Each turn he does the following:
- Ivan chooses any non-empty box and takes all balls from this box;
- Then Ivan chooses any $k$ empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into $k$ non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either $k = 2$ or $k = 3$.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
|
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 group. If $n$ is even, then we need to add an auxiliary group of size $0$. Then $n$ becomes odd, so we can use the above algorithm to solve this case. Why does it work? This algorithm is exactly the same as the algorithm of building a Huffman code with the alphabet of size $3$. And it can easily be seen that these problems are similar: by separating a group of balls into three groups, we add a new character to the codes of the colours present in that group, and our goal is to obtain a prefix code.
|
[
"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 certain index in the row, we will try to merge it with the element to the left of it and with the element to the top - that's all we have to check here. You also have to handle the fact that we cannot store the whole DSU since the number of components can be up to $\frac{n I T I}{2}$, and it's impossible to store all required information for them. So each time we process a row, we have to renumerate all components in this row to ensure that every time we are operating with indices of components not greater than $2m$.
|
[
"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 beauty of index $i$ as $b_{i}$, and the beauty of $t$ as the sum of $b_{i}$ among all indices $i$ such that $s_{i} = t_{i}$.
Help Ivan to determine maximum possible beauty of $t$ he can get.
|
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 letter in each of these pairs. For each of these pairs let's replace the letter with lower $b_{i}$ with something. Let's analyze the letters we are going to replace. Let $cnt(x)$ be the number of occurences of letter $x$ that we have to replace. There are two cases: There is no letter $x$ such that $2 * cnt(x) > m$. Then we can replace these letters without involving anything else and get an antipalindromic string with minimal possible cost; There is a letter $x$ such that $2 * cnt(x) > m$. It's obvious that there is at most one such letter. Let's replace some occurences of $x$ with other letters that are to be replaced. Then we will still have some occurences of $x$ that need to be replaced. Let's take one letter from each pair such that both of letters in a pair are not equal to $x$. Among these possibilities choose the required number of letters with minimum values of $b_{i}$. Then we can replace remaining occurences of $x$ with these letters.
|
[
"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}$. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question.
|
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 he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.
|
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 are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute $i$, he makes a note in his logbook with number $t_{i}$:
- If Petya has visited this room before, he writes down the minute he was in this room last time;
- Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute $i$.
Initially, Petya was in one of the rooms at minute $0$, he didn't write down number $t_{0}$.
At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?
|
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 of occurrences of $i$ in the journal. From the previous statement we deduce that minimum possible number of rooms is at least $\textstyle\sum_{i=0}^{n-1}\operatorname*{max}(0,c n t_{i}-1)$. Also, it's easy to see that this value can be achieved: we say that first occurrence of each value corresponds to revisiting the previous room and all other correspond to visiting new rooms. So the problem can be solved by calculating values $cnt_{i}$ for each $i$ between $0$ and $n$ and calculating the above sum. Overall complexity - $O(n)$.
|
[
"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. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes).
A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string.
The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.
String $a$ is lexicographically smaller than string $b$, if $a$ is a prefix of $b$, or $a$ has a smaller letter at the first position where $a$ and $b$ differ.
|
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. If there is cycle in such graph then good string doesn't exist. So such graph can be represented as several non-intersecting paths. All strings which correspond to paths must occur in non-empty good string. So if we print them in lexicographical order then we will get the answer.
|
[
"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. Desperate, Petya decided to use a somewhat unexpected optimization using parameter $k$, so now his function contains the following code:
\begin{verbatim}
int fast_max(int n, int a[]) {
int ans = 0;
int offset = 0;
for (int i = 0; i < n; ++i)
if (ans < a[i]) {
ans = a[i];
offset = 0;
} else {
offset = offset + 1;
if (offset == k)
return ans;
}
return ans;
}
\end{verbatim}
That way the function iteratively checks array elements, storing the intermediate maximum, and if after $k$ consecutive iterations that maximum has not changed, it is returned as the answer.
Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from $1$ to $n$ such that the return value of his function on those permutations is not equal to $n$. Since this number could be very big, output the answer modulo $10^{9} + 7$.
|
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 have $p_{n} = n$. Notice that if $k \ge n$, then $D(n) = 0$. Let $w$ be a permutations such that $w_{n} = n$. If index of element $n - 1$ is lesser than $n - k$, then $w$ is good. Otherwise if $n - 1$ index is $j, j \ge n - k$, then because there are less then $k$ elements between $n - 1$ and $n$, $w$ could be good only if $i$ from the definition would be lesser than $j$. In that case permutation $w_{1}, ..., w_{j}$ would form a good permutation of length $j$ of some numbers with $w_{j}$ being the maximum. Therefore the following equation is correct: $D(n)=(n-k-1)\cdot(n-2)!+\sum_{h=n-k}^{n-1}D(h)\cdot{\frac{(n-2)!}{i\,n-1!}}$ $D(n)=(n-k-1)\cdot(n-2)!+(n-2)!\cdot\sum_{h=n-k}^{n-1}{\frac{D(n)}{k-1!!}}$ The answer is than calculated as follows: $\sum_{\quad\quad h=1}^{n}D(h)\cdot{\frac{(n-1)!}{(h-1)!}}$ Complexity: $O(n)$.
|
[
"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$ on the plane such that the multiset is centrally symmetric in respect of 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 center of mass then they will be symmetric under the projection on arbitrary line. So we can throw away these points. Fix arbitrary point from remaining set. Let us take point from set, which will be symmetric to the fixed point. There is only one line, which has property, that two projections of chosen points are symmetric: the line, which is perpendicular to line passing through the center of mass of initial set and center of segment connecting two chosen points. So we have no more then n candidates which can be a good line. It is possible to check, that line is good, in $O(nlogn)$ time. Time: $O(n^{2}\log{n})$
|
[
"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, divisible by 64, in the binary numerical system.
|
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 row. After that, she looks at upper faces of cubes from left to right and reads the number.
The number can't contain leading zeros. It's not required to use all cubes to build a number.
Pay attention: Masha can't make digit 6 from digit 9 and vice-versa using cube rotations.
|
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 of one face of the cube in any direction.
To check her answers she wants to use a program which will for some state of cube tell if it's possible to solve it using one rotation, described above.
Cube is called solved if for each face of cube all squares on it has the same color.
https://en.wikipedia.org/wiki/Rubik's_Cube
|
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). Moreover, sometimes top-models participates in talk shows. After participating in talk show model becomes more popular and increasing of her rating after photo shoots become $c$ and decreasing of her rating after fashion show becomes $d$.
Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will never become negative. Help her to find a suitable moment for participating in the talk show.
Let's assume that model's career begins in moment 0. At that moment Izabella's rating was equal to $start$. If talk show happens in moment $t$ if will affect all events in model's life in interval of time $[t..t + len)$ (including $t$ and not including $t + len$), where $len$ is duration of influence.
Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will not become become negative before talk show or during period of influence of talk show. Help her to find a suitable moment for participating in the talk show.
|
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 participate in the talk show and the other one at the moment of time right after its influence ends. Then we can participate in the talk show if the minimum of prefix sums on values ($c$, $d$) from elements between pointers is not less than the difference of prefix sums on values ($a$, $b$) and ($c$, $d$) from element $V$. Also we must check that Izabella's rating doesn't become negative before participating in the talk show or during its peroid of influence.
|
[
"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 intersect or touch any circle.
Also, no two circles intersect or touch, and there is no pair of circles such that one circle is located inside another.
Moreover, for each circle, Masha drew a square of the minimal area with sides parallel axis such that this circle is located inside the square and noticed that there is no two squares intersect or touch and there is no pair of squares such that one square is located inside other.
Now Masha wants to draw circle of minimal possible radius such that it goes through two points that brother drew and doesn't intersect any other circle, but other circles can touch Masha's circle and can be located inside it.
\textbf{It's guaranteed, that answer won't exceed $10^{12}$. It should be held for hacks as well.}
|
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 to AB the center of the circle is. Every drawn circle blocks a continious interval of allowed values for the requierd circle. The limits of this interval can be found by using binary search. Now we have to find the least allowed value for the radius. It can be done, for example, by using method of scanning line.
|
[
"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. Evaluating beauty of row of models Izabella looks at heights of models. She thinks that row is nice if for each model distance to nearest model with less height (model or fashion designer) to the right of her doesn't exceed $k$ (distance between adjacent people equals 1, the distance between people with exactly one man between them equals 2, etc).
She wants to make row nice, but fashion designer has his own sense of beauty, so she can at most one time select two models from the row and swap their positions if the left model from this pair is higher than the right model from this pair.
Fashion designer (man to the right of rightmost model) has less height than all models and can't be selected for exchange.
You should tell if it's possible to make at most one exchange in such a way that row becomes nice for Izabella.
|
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 there are no "bad" elements in the array then the answer is "YES". Otherwise we should find the leftmost "bad" element in the array bad. $X$ elements after it are not less than itself. All elements before it are also not less than itself because otherwise an element less than bad would be "bad" too. Swapping bad with an element in suffix also makes no sense because its place will be taken by lesser element and the position will remain "bad". Thus, swapping bad with other element of the array makes no sense. The only way to satisfy the conditions is to swap one of $x$ elements after $bad$ with other element in the remaining suffix without considering a segment with length $x$ after bad. Let's try to do it obviously. Then the following conditions must be satisfied. Consider choosing an element $y$ in the remaining suffix. Then the swap can be the answer if $y$ < $bad$. Also suffix after $y$ and the segment between $y$ and the segment with length $x$ after $bad$ must not contain "bad" elements. An element, which we swap $y$ with, from the segment with length $x$ after $bad$ must be less than any adress on $y$. Also we need to check that after the swap on the right side of $y$ we can find an element less than itself no further than $x$. Time: $O(n)$ or $O(nlogn)$.
|
[
"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_{i} > a_{i + 1}$). Since $a_{1}$ and $a_{n}$ have only one neighbour each, they are neither local minima nor local maxima.
An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.
|
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)$ to $(x - 1, y)$;
- R — move from $(x, y)$ to $(x + 1, y)$.
Ivan entered a sequence of $n$ commands, and the robot processed it. After this sequence the robot ended up in the starting cell $(0, 0)$, but Ivan doubts that the sequence is such that after performing it correctly the robot ends up in the same cell. He thinks that some commands were ignored by robot. To acknowledge whether the robot is severely bugged, he needs to calculate the maximum possible number of commands that were performed correctly. Help Ivan to do the calculations!
|
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 final cell of the original path to $(0, 0)$. Overall complexity: $O(n)$.
|
[
"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. Take maximum of these values. Answer will be this maximum + 1. Overall complexity: $O(|Alpha| \cdot n)$.
|
[
"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 permutations for given numbers $n$ and $k$.
|
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 a permutation $q$ for chosen indices such that for every chosen index $q_{i} \neq i$; permutations with this property are called derangements, and the number of derangements of fixed size can be calculated using exhaustive search (since $m \le 4$). So the answer is $\sum_{m=0}^{k}{\binom{n}{m}}d(m)$, where $d(m)$ is the number of derangements of size $m$.
|
[
"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 the maximum possible value of $\sum_{i=1}^{k}a_{b_{i}}\,m o d\,m$.
|
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 the first $\textstyle{\left[\!\!{\frac{n}{2}}\right]\!\!}\$ elements naively and push sums modulo $m$ to some array. After this process the second half with following algorithm. Take sum of the set and find the greatest total sum of current and some sum in the array. As any sum of two numbers less than $m$ can go no greater than $2m$, we can consider just two values: the greatest number in array and the greatest number less than $m - currentSum$ in the array. This can be found by binary search over sorted array. Overall complexity: $O(2^{\lfloor{\frac{n}{2}}\rfloor}\cdot\log(2^{\lfloor{\frac{n}{2}}\rfloor}))$.
|
[
"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 with each other (directly or indirectly).
But there are some restrictions. Firstly, some pairs of points cannot be connected directly and have to be connected undirectly. Secondly, the segments you draw must not intersect in any point apart from the marked points (that is, if any two segments intersect and their intersection is not a marked point, then the picture you have drawn is invalid).
How many ways are there to connect all vertices with $n - 1$ segments? Two ways are considered different iff there exist some pair of points such that a segment is drawn between them in the first way of connection, but it is not drawn between these points in the second one. Since the answer might be large, output it modulo $10^{9} + 7$.
|
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 connect any vertex between $i$ and $j$ to some vertex outside). What $dp$ values should we access if we, for example, try to connect $i$-th vertex to some vertex $x$? To get everything connected, we then have to connect vertices from interval $(i, x)$ to these two, and vertices from $(x, j)$ to $x$, $j$ or $i$ - and connections to $i$ from the second interval are difficult to handle. We need to somehow get rid of them, and the solution is to choose $x$ as the vertex with greatest index that we connect directly to $i$. And vice versa, if we connect something to $j$, then we choose the smallest index of vertex to be connected with $j$ directly. But that's not all we have to handle. Suppose we have four vertices, and $0$ is already connected to $3$. One of the possibilities to finish it is to connect $0$ to $1$ and $2$ to $3$, but if we process current dynamic programming as it is, we will count it twice (if we choose to connect $1$ to $0$ firstly, or if we connect $2$ to $3$). To get rid of this problem, we will use a flag that will denote whether we can connect anything to vertex $i$, and if we choose to pick the first connection from $j$, then we don't connect anything to $i$. So the solution is: $dp[i][j][flag]$ - the number of ways to connect the vertices from interval $(i, j)$ to $i$ and $j$, and $flag$ denotes if we can connect anything to $i$. How to calculate it: If $j = i + 1$, then $dp[i][j][flag] = 1$ (there is nothing left to connect); Otherwise set $dp[i][j][flag] = 0$; If $flag = 1$, then iterate on vertex $x$ we connect to $i$ and add $dp[i][x][flag] \cdot dp[x][j][flag]$; Iterate on vertex $y$ we connect to $j$ and add $dp[i][y][0] \cdot dp[y][j][1]$. The answer is $dp[0][n][0]$ (if vertices are $0$-indexed). Vertex $n$ is actually vertex $0$, so don't forget to update the matrix $a$ for it.
|
[
"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 out of this component. Then we add the edges we found to the MST (but we should be careful to avoid adding edges that form cycles in MST). The number of iterations is at most $\log n$, and each of iterations can be done in $O(m)$. However, in this problem we need to speed up this algorithm. We can do each iteration in $O(n\log(\operatorname*{max}_{i=1}a_{i}))$ time using a binary trie. We can store all values from $a$ in a trie. When we need to find the shortest edge that connects some component with vertices outside of it, we firstly remove all values contained in this component from the trie. After that, for each vertex in the component we can find the closest vertex outside the component in $O(\log(\operatorname*{max}_{i=1}a_{i}))$ by descending the trie. And then we insert the values of $a_{i}$ belonging to the component back into the trie. Since for each vertex we descend the trie three times (to remove it, to find closest vertex and to add it back), each iteration requries $O(n\log(\operatorname*{max}_{i=1}a_{i}))$, and the whole algorithm works in $O(n\log n\log(\operatorname*{max}_{i=1}a_{i}))$ time.
|
[
"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 either $c = a$ or $c<{\frac{a}{2}}$. Explanation of hint 1: let's call $ans_{i} = f(x, 1) - f(x_{i}, i + 1)$, in other words, it's the part of answer we gain from summands from $1$ to $i$. For $i = 1$ the following is true: $x_{1}$ can be any number from $0$ to $a_{1} - 1$, and $ans_{i} = x_{i}$. Suppose for some $i$ we have the following option: $x_{i}$ can be any number from $0$ to $r$, and in this case $ans_{i} = x_{i} * i + k$. We can describe this situation by triple $(i, r, k)$. We will show that this triple will produce at most two such triples for $i + 1$. Indeed, we can have many triples $(i + 1, a_{i + 1} - 1, k_{j})$ with different $k_{j}$ and one triple $(i+1,r\mathrm{~mod~}a_{i+1},k+i\cdot(r-r\mathrm{~mod~}a_{i+1}))$. However, we can note that among triplets of the first type we can leave only one with maximum $k_{j}$, because we're interested in maximum answer. This $k_{j}$ will equal $(k+i\cdot(r-r\,\operatorname*{mod}\,a_{i+1}-a_{i+1}))$. Thus, we have two transitions from each triple, that leads us to $O(2^{n})$ bruteforce solution. Explanation of hint 2: when we have a bruteforce, we (almost) always can think of a dp. Indeed, we have triples, among those with equal $i$ and $r$ let's keep only one with the largest $k$. There are at most $i$ such triples on step $i$: on each step half of the generated triples have $r = a_{i + 1} - 1$, so we can merge them. This leads us to dp in $O(n^{2})$. Explanation of hint 3: Okay, what does the third hint say? It basically says that a number can only be taken by modulo $O(\log(C))$ times until it becomes zero, where $C$ is the bound of its initial value. What do we get from this? We can note that if $r < a_{i + 1}$, we can just leave a triple $(i, r, k)$ untouched except changing $i$ to $i + 1$. Let's then keep pairs $(r, k)$, assuming triples $(i, r, k)$, where $i$ changes in a cycle. On each step we should change all pairs such that $r \ge a_{i + 1}$, possibly adding one more pair with $r = a_{i + 1} - 1$. But when we change a pair, $r$ is get by modulo, so this won't happen with a pair more than $O(log(C))$ times! Overall, the total number of times we touch a pair is bounded by $O(n\log(C))$. Adding $O(\log(n))$ for map in which we keeps the pairs, we obtain the final complexity $O(n\log(C)\log(n))$. Also, map can be replaced with binary search, but the complexity remains the same.
|
[
"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 the elements equal to $1$?
|
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 we know that $D(L, R) = G$ then $D(L, R + 1) = gcd(G, A_{}(R + 1))$. If $D(L, R) = 1$ then you can make all the elements in $(R - L + 1) + (n - 1)$. Answer is minimum possible $D(L, R)$ over all possible segments.
|
[
"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}}\neq\sum_{i=1}^{k}b_{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}}$ $\textstyle\sum_{i=1}^{n-k}b_{y_{i}}>\sum_{i=1}^{n-k}a_{y}$ $\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 jealous. You are given some queries, each query contains a set of edges of graph $G$, and you should determine whether there is a MST containing all these edges or not.
|
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 of this graph as a vertex, the edges given in query with weight X should form a cycle in this new graph. We can check this for all queries offline by sorting edges from minimum weight and do simple dfs for each weight in each query.
|
[
"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 edges or their added edges aren't the same. The removed edge and the added edge can be equal.
A perfect matching is a subset of edges such that each vertex is an endpoint of exactly one of these edges.
|
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 matching if and only if the input tree had prefect matching. If no two bad edges share a vertex, after removing a bad edge (lets call it $X$) we should chose the end points of the edge we want to add (lets call them $v$,$u$) such that the path between $v$ and $u$ in the input tree has alternately bad and good edges, the first and the last edges in the path are bad and $X$ is in this path too. So for any path in the tree that has alternately bad and good edges and the first and final edges in it are bad we should add the $\frac{L e n g t h O f T h i s P a t h+1}$ to the answer. This can be done using dp. If there are bad edges that share vertices, we know that each vertex has odd number of bad edges to its neighbors, and if this number is greater than 3 then the answer is 0. So each vertex has 1 or 3 odd edges to its neighbors. The path between end points of added edge should contain all the vertices with 3 bad edges and also two of their bad edges should be in the path. So if the vertices with 3 bad edges aren't in a path with this condition then the answer is 0 and otherwise we can calculate the answer by checking some conditions in their path and counting the number of paths with some condition at the end points of their path.
|
[
"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) (x).begin(),(x).end()
#define fi first
#define se second
const int maxn = 500005;
vector<int> gr[maxn];
int ansdown[maxn][2];
int ansdownif[maxn][2][3][2][2];
int sz[maxn];
int cntbad[maxn], cntodd[maxn];
int n;
ll answer;
bool isok[maxn];
void calcdown(int cur, int pr)
{
sz[cur] = 1;
for (auto t : gr[cur]) if (t != pr)
{
calcdown(t, cur);
sz[cur] += sz[t];
}
ansdown[cur][0] = 0;
ansdown[cur][1] = 0;
isok[cur] = true;
cntodd[cur] = 0;
cntbad[cur] = 0;
for (auto t : gr[cur]) if (t != pr)
{
isok[cur] &= isok[t];
cntbad[cur] += !isok[t];
cntodd[cur] += sz[t] % 2;
}
isok[cur] &= cntodd[cur] <= 1;
ansdown[cur][0] += (isok[cur] && cntodd[cur] + (n - sz[cur]) % 2 <= 1); // 0
ansdown[cur][1] += (isok[cur] && cntodd[cur] + (n - sz[cur] + 1) % 2 + 1 <= 1); // 1
for (auto t : gr[cur]) if (t != pr)
{
for (int kbad = 0; kbad <= 1; kbad++)
{
for (int kodd = 0; kodd <= 2; kodd++)
{
for (int oddabove = 0; oddabove <= 1; oddabove++)
{
// try 0
if ((kbad == 0 || !isok[t]) && kodd + oddabove == 1) // t has the same parity
{
ansdownif[cur][kbad][kodd][oddabove][0] += ansdown[t][0];
}
// try 1
if ((kbad == 0 || !isok[t]) && kodd - sz[t] % 2 + (sz[t] + 1) % 2 + (oddabove + 1) % 2 == 1) // t has another parity
{
ansdownif[cur][kbad][kodd][oddabove][1] += ansdown[t][1];
}
}
}
}
}
if (cntbad[cur] <= 1 && cntodd[cur] <= 2)
{
ansdown[cur][0] += ansdownif[cur][cntbad[cur]][cntodd[cur]][(n - sz[cur]) % 2][0];
ansdown[cur][1] += ansdownif[cur][cntbad[cur]][cntodd[cur]][(n - sz[cur]) % 2][1];
}
}
void calcup(int cur, int pr, int ansup0, int ansup1, bool isupok)
{
if (pr != -1)
{
if (sz[cur] % 2 == 0)
{
answer += (ll)ansup0 * ansdown[cur][0];
} else
{
answer += (ll)ansup1 * ansdown[cur][1];
}
}
for (auto t : gr[cur]) if (t != pr)
{
int nowcntbad = cntbad[cur] + !isupok - !isok[t];
int nowcntodd = cntodd[cur] + (n - sz[cur]) % 2 - sz[t] % 2;
bool isnewok = isupok && (cntbad[cur] == 0 || (cntbad[cur] == 1 && !isok[t]));
isnewok &= nowcntodd <= 1;
if (nowcntbad > 1 || nowcntodd > 2) continue;
int curansup0 = ansdownif[cur][nowcntbad][nowcntodd][sz[t] % 2][0];
int curansup1 = ansdownif[cur][nowcntbad][nowcntodd][sz[t] % 2][1];
if (isnewok && nowcntodd + sz[t] % 2 <= 1) curansup0++;
if (isnewok && nowcntodd + 1 + (sz[t] + 1) % 2 <= 1) curansup1++;
if ((nowcntbad == 0 || !isupok) && nowcntodd + sz[t] % 2 == 1) curansup0 += ansup0;
if ((nowcntbad == 0 || !isupok) && nowcntodd - (n - sz[cur]) % 2 + (n - sz[cur] + 1) % 2 + (sz[t] + 1) % 2 == 1) curansup1 += ansup1;
// try 0
if ((nowcntbad == 0 || !isok[t]) && nowcntodd + sz[t] % 2 == 1) // t has the same parity
{
curansup0 -= ansdown[t][0];
}
// try 1
if ((nowcntbad == 0 || !isok[t]) && nowcntodd - sz[t] % 2 + (sz[t] + 1) % 2 + (sz[t] + 1) % 2 == 1) // t has another parity
{
curansup1 -= ansdown[t][1];
}
calcup(t, cur, curansup0, curansup1, isnewok);
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n - 1; i++)
{
int a, b;
scanf("%d%d", &a, &b);
a--, b--;
gr[a].pb(b);
gr[b].pb(a);
}
if (n % 2 == 1)
{
cout << 0 << endl;
return 0;
}
calcdown(0, -1);
calcup(0, -1, 0, 0, 1);
cout << answer << endl;
return 0;
}
|
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$, but $i ≠ x$. Then, subtract $a_{x}$ by $1$.
You have to find expected value of $res$ at the end of the process. It can be proved that the expected value of $res$ can be represented as an irreducible fraction $\frac{P}{Q}$. You have to find $P\cdot Q^{-1}\mathrm{~mod~}10000000007$.
|
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_{i}$s (can be proved by induction). So we can see truth of lemma. Define $dp_{mask, k}$ as expected value of multiply of mask's subset after k'th repeat. Now we want to calculate this dp. Fix index of k'th chosen number. If mask's subset contains that fixed number, then expected value of multiply of mask's subset decreases by expected value of $dp_{mask2, k - 1}$ (mask2 is equal to subset of mask minus chosen fixed number). If mask's subset doesn't contains fixed index, then expected value of multiply of mask's subset doesn't change. More formally , for all indices i from 1 to n : $d p_{m a s k,k}+=\operatorname*{i}_{n}*d p_{m a s k,k-1}-{\mathfrak{i}}_{n}*d p_{m a s k-2^{i},k-1}$. (If mask contains i'th element). $d p_{m a s k,k}+={\operatorname*{i}}_{n}^{1}*d p_{m a s k,k-1}$ (If mask dosent contains i'th element) So we can write : $dp_{mask, k} + = dp_{mask, k - 1}$ $d p_{m a s k,k}-\mathrm{=\frac{i}{n}*}d p_{m a s k-2i,k-1}$ (If mask contains i'th element) After calculating this dp, we can find expected value of res, using lemma and $dp_{2^{n} - 1, k}$. This algorithm runs in $O(2^{n} * k * n)$. Now we want to optimize this solution. First of all, we can calculate this dp , using matrix exponential; because $dp_{mask, k}$ updates by a coefficient from $dp_{mask2, k - 1}$. so if we write coefficient of update $dp_{mask, k}$ from $dp_{mask2, k - 1}$ in $matrix_{mask, mask2}$ , and write multiply of mask subset if $e_{mask}$, then $2^{n} - 1$'th element of $matrix^{k} * e$, equals to expected value of $a_{i}$s after k'th repeat process. After his optimization, algorithm runs in $O(2^{3n} * lgk)$. In our second solution, we learned that expected value of multiply of $a_{i}$'s after k'th operation (name it as $s$) equals to $2^{n} - 1$'th element of $matrix^{k} * e$. this element equals to $\sum_{i=0}^{2^{n}}m a t r i x^{k}2^{n}-1.i\star e_{i}$. Now we want to calculate coefficients of $matrix^{k}_{2^{n} - 1}$. by this coefficients, we can calculate value $s$. if we take a look at update of $dp_{mask, k}$, we can define another meaning for this $dp$. imagine directed hypercube $Q_{n}$ and add a self loop for every vertex. now $dp_{mask, k}$, can be this : for every walk that ends in $mask$ in $k$ moves, add $\left(\frac{-1}{n}\right)^{n u m b e r o\hat{f}n o n s e l f l o o p e d g e s}$ to $dp_{mask, k}$. So it's easy to see that all $mask$s that have equal number of elements, have equal $dp_{mask, k}$. (regardless of base of $dp$) So $matrix^{k}_{2^{n} - 1, mask}$ is equals to this value for walks from mask to $2^{n} - 1$. Now, by fixing non self loop edges, we can see that $matrix^{k}_{2^{n} - 1, mask}$ is equal to : $({\frac{-1}{n}})^{n u m b e r o f z e r o s i n m a s k}*k*(k-1)*\ldots*(k-(n u m b e r o f z e r o s i n m a s k+1)$ So this value is equal for all masks with equal ones. name this value by $Z_{numberofonesinmask}$. By our equation : $matrix^{k}_{2^{n} - 1, mask} * e_{mask}$ (for $0 \le mask < 2^{n}$) $Z_{numberofonesinmask} * e_{mask}$ (for $0 \le mask < 2^{n}$) $Z_{W}*\left(\sum_{a l l m a s k s a w i t h W o n e s}{\mathcal{C}}_{m a s k}\right)$(for $0 \le w \le n$) So $Z_{w}$'s can be easily calculated in $O(n)$. Now we want to calculate $\textstyle\sum e_{m a s k}$ (for all masks with w ones). (for $0 \le w \le n$). This value can be calculated by $dp_{i, j}$ (sigma of j_tuples multiplies in first i elements) in $O(n^{2})$. So, finally, this algorithm runs if $O(n^{2} + lg(k))$
|
[
"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 - L_{i}$.
You are given lengths of the claws. You need to find the total number of alive people after the bell rings.
|
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:
- Alex and Bob play the first game, and Carl is spectating;
- When the game ends, the one who lost the game becomes the spectator in the next game, and the one who was spectating plays against the winner.
Alex, Bob and Carl play in such a way that there are no draws.
Today they have played $n$ games, and for each of these games they remember who was the winner. They decided to make up a log of games describing who won each game. But now they doubt if the information in the log is correct, and they want to know if the situation described in the log they made up was possible (that is, no game is won by someone who is spectating if Alex, Bob and Carl play according to the rules). Help them to check it!
|
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}$ ($120_{10}$);
- $111110000_{2}$ ($496_{10}$).
More formally, the number is beautiful iff there exists some positive integer $k$ such that the number is equal to $(2^{k} - 1) * (2^{k - 1})$.
Luba has got an integer number $n$, and she wants to find its greatest beautiful divisor. Help her to find it!
|
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 Overcity and spread a rumor in it.
Vova knows that there are $n$ characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; $i$-th character wants $c_{i}$ gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.
The quest is finished when all $n$ characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?
Take a look at the notes if you think you haven't understood the problem completely.
|
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$, then $a_{i}$ bourles are withdrawn. And if $a_{i} = 0$, then the amount of money on Luba's account is checked.
In the \textbf{morning} of any of $n$ days Luba can go to the bank and deposit any \textbf{positive} integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed $d$.
\textbf{It can happen that the amount of money goes greater than $d$ by some transaction in the evening. In this case answer will be «-1».}
Luba must not exceed this limit, and also she wants that \textbf{every day her account is checked} (the days when $a_{i} = 0$) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
|
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 limit. We can only add money to the balance. Adding zero money in those days won't make invalid states if all were valid previously. Finally, if it's possible to get valid state in every day then it's possible to get it by refilling the same day the check happens. For example, you can make $max(0, currentBalance)$ balance in those days. Then you will never have negative balance there. Though it's not the most optimal way. Let $delta$ be some value you deposite in some day with $a_{i} = 0$ to pass all conditions till the next day with $a_{j} = 0$. I state that function of number of game's moves dependancy on $delta$ is monotonious. Let's check it for some fixed $x$. Define minimum balance you will get on any suffix from now as $minBal$. Obviously, taking $x - 1$ will make it $minBal - 1$. If it goes negative then you will need an extra move to finish the game. Thus taking maximal $delta$ will lead to the lowest score possible. And last but not least - realization part. What will be the maximum possible value to deposite? Actually, it's such a value that optimal game after this will lead to maximum balance of $d$ in some day. Thus, you want to check what will be the maximum balance $maxBal$ if you add zero money and take $delta$ as $d - maxBal$. Obviously, if it's negative then output $- 1$. Naively this still works on $O(n)$ per day and lead to $O(n^{2})$ overall. Notice that by depositing $delta$ you increase maximums on each suffix for now by $delta$. So, you can calculate it as you will do nothing and add sum $deltaSum$ of your $delta$'s to get actual value. You store prefix sum of $a_{j}$ up to $i$ in $pr_{i}$. Then take maximum on suffix for every $i$ ($su_{i}$ is the maxumum $pr_{j}$ for $j$ from $i$ to $n$). $delta = d - (deltaSum + su_{i})$. I hope I made it clear enough. :D Overall comlpexity: $O(n)$.
|
[
"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$-factorizations of $x$. Two arrays $A$ and $B$ are considered different iff there exists at least one index $i$ ($1 ≤ i ≤ y$) such that $A_{i} ≠ B_{i}$. Since the answer can be very large, print it modulo $10^{9} + 7$.
|
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$. Take product of this values for every prime $i$. This will be the answer if there were no negative numbers. But we should also multiply it by number of ways to select even number of position to put unary minuses - $2^{y - 1}$ (like you can fill in $y - 1$ position anyhow and the final one will be determined by parity of current count). To process many queries you should factorize numbers in $O(\log n)$ (by precalcing the smallest prime divisor of every number up to $10^{6}$ with sieve of Eratosthenes), get $\textstyle{\binom{n}{k}}$ in $O(1)$ (by precalcing factorials and inverse factorials) and get $2^{k}$ in $O(\log n)$ (binary exponentiation). Overall complexity: $O(M A X N\cdot\log M A X\,\textstyle N+n\cdot\log M A X\,\textstyle A X\,\textstyle N\,)$.
|
[
"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 subtree of vertex $x$ as the set of vertices $y$ such that both these conditions are met:
- $x$ is an ancestor of $y$ (every vertex is an ancestor of itself);
- $d(x, y) ≤ k$.
You are given $m$ queries to the tree. $i$-th query is represented by two numbers $x_{i}$ and $k_{i}$, and the answer to this query is the minimum value of $a_{j}$ among such vertices $j$ such that $j$ belongs to $k_{i}$-blocked subtree of $x_{i}$.
Write a program that would process these queries quickly!
\textbf{Note that the queries are given in a modified way}.
|
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 sort the vertices by their depth (and if depths are equal, by time we entered them in DFS). Then we renumerate vertices in this sorted order. We need to denote some functions in order to continue: $D(x)$ - depth of vertex $x$ in the tree; $tin(x)$ - the time we entered $x$ during DFS; $tout(x)$ - the time we left $x$ during DFS. For each depth we can store a sorted array of vertices belonging do this depth. This will allow us to build an auxiliary sparse table $lf$, where $lf[i][x]$ is such vertex $j$ that: $D(j) = D(x) + 2^{i}$; $tin(j) > tin(x)$; $tin(j)$ is minimal among all vertices that meet first two conditions. We also need a second sparse table $rg$, where $rg[i][x]$ is $j$ iff: $D(j) = D(x) + 2^{i}$; $tout(j) > tout(x)$; $tout(j)$ is minimal among all vertices that meet first two conditions. These sparse tables can be built using binary search in arrays we created for depths. Okay, why do we need them? To create a third sparse table that will process the queries themselves: $table[i][j][x]$ - the minimum value of $a_{y}$ among vertices $y$ such that $y$ belongs to $2^{j}$-blocked subtree of some vertex with index included in $[x, x + 2^{i})$. This table can be built backwards with the help of auxiliary tables. So, how do we answer the queries? We need to look at the binary representation of $k + 1$ and do something like binary lifting (but descending the tree instead of ascending) and maintain the leftmost and the rightmost vertices on current depth which belong to the subtree we are interested in (and make queries to $table$ on the segment between these two vertices). This solution works in $O(n\log^{2}n+m\log n)$, but, unfortunately (or fortunately to some participants), we made the time limit too high so the structures that require $O(\log^{2}n)$ time to process each query, such as two-dimensional segment trees, might also get AC.
|
[
"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://twitter.com/nekoyaliu}
\end{center}
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
|
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 either 1 or -1.
Now Ralph wants you to figure out the number of ways to put numbers in each block in such a way that the magic field works properly. Two ways are considered different if and only if there exists at least one block where the numbers in the first way and in the second way are different. You are asked to output the answer modulo $1000000007 = 10^{9} + 7$.
Note that there is no range of the numbers to put in the blocks, but we can prove that the answer is not infinity.
|
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 it's obvious that the remaining numbers are uniquely determined because the product of each row and each column is known already. So in this case the answer is $pow(2, [(n - 1) * (m - 1)])$ .
|
[
"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 be $a_{1}, a_{2}, ..., a_{n}$. He remembered that he calculated $gcd(a_{i}, a_{i + 1}, ..., a_{j})$ for every $1 ≤ i ≤ j ≤ n$ and put it into a set $S$. $gcd$ here means the greatest common divisor.
Note that even if a number is put into the set $S$ twice or more, it only appears once in the set.
Now Marco gives you the set $S$ and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set $S$, in this case print -1.
|
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 the nearest integer) and the city labeled $(i + 1)$, and the length of the $i$-th road is $L_{i}$.
Now Ralph gives you $m$ queries. In each query he tells you some city $A_{i}$ and an integer $H_{i}$. He wants to make some tours starting from this city. He can choose any city in the Binary Country (including $A_{i}$) as the terminal city for a tour. He gains happiness $(H_{i} - L)$ during a tour, where $L$ is the distance between the city $A_{i}$ and the terminal city.
Ralph is interested in tours from $A_{i}$ in which he can gain positive happiness. For each query, compute the sum of happiness gains for all such tours.
Ralph will never take the same tour twice or more (in one query), he will never pass the same city twice or more in one tour.
|
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 won't be able to fit in the time limit. Because the tree is an almost complete binary tree, one vertex will appear at most $[log(n)]$ times in all $n$ sorted arrays,so the memory complexity is $O(nlog(n))$. To answer each query, we can iterate on the highest vertex on the tour and do binary search on the sorted array to get the answer. We'll do at most $[log(n)]$ times of iteration and the binary search is $O(log(n))$ per iteration, so we can answer each query in $O((log(n))^{2})$ time. Overall, the time complexity is $O(nlog(n) + m(log(n))^{2})$ and the memory complexity is $O(nlog(n))$. If you use std::sort, the time complexity will be $O((n + m)(log(n))^{2})$ and the memory complexity is the same.
|
[
"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 fantastic speed. New mushrooms regrow as soon as Ralph finishes mushroom collection on a path. More specifically, after Ralph passes a path the $i$-th time, there regrow $i$ mushrooms less than there was before this pass. That is, if there is initially $x$ mushrooms on a path, then Ralph will collect $x$ mushrooms for the first time, $x - 1$ mushrooms the second time, $x - 1 - 2$ mushrooms the third time, and so on. However, the number of mushrooms can never be less than $0$.
For example, let there be $9$ mushrooms on a path initially. The number of mushrooms that can be collected from the path is $9$, $8$, $6$ and $3$ when Ralph passes by from first to fourth time. From the fifth time and later Ralph can't collect any mushrooms from the path (but still can pass it).
Ralph decided to start from the tree $s$. How many mushrooms can he collect using only described paths?
|
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 maths knowledge in $O(m)$ time. Then we can regard each SCC as a new vertex and get a DAG, and the remaining work is just to find the longest path on the DAG from a given vertex, where the length of an edge is the number of mushrooms in it initially, since we can only pass through it once. We can use topological sort and apply dynamic programming on the DAG in $O(n + m)$ time. Overall, the time complexity is $O(n + m)$.
|
[
"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 all pieces of pizza into two continuous sectors in such way that the difference between angles of these sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors can be empty.
|
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 count it's angle and update answer. Time complexity $O(n^{2})$ or $O(n)$.
|
[
"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));\n\t\t\tsum -= a[l];\n\t\t\tl++;\n\t\t}\n\t\tans = min(ans, 2 * abs(180 - sum));\n\t\tr++;\n\t}\n\tcout << ans << endl;\n}"
|
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 there are exactly $k$ integers $y$ such that $a_{i} ≤ y ≤ a_{j}$ and $y$ is divisible by $x$.
In this problem it is meant that pair $(i, j)$ is equal to $(j, i)$ only if $i$ is equal to $j$. For example pair $(1, 2)$ is not the same as $(2, 1)$.
|
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 boundaries $r = a[j]$ should satisfy the following condition $a[j] / x-(a[i] - 1) / x = k$. We already know $(a[i] - 1) / x$, $a[j] / x$ is increasing while $a[j]$ increases. So we can do binary search on sorted array to find minimal/maximal index of good right boundaries and that mean we can find the number of good right boundaries. Time complexity $O(n * log(n))$.
|
[
"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 (a[m] >= le)\n\t\t\tr = m;\n\t\telse\n\t\t\tl = m;\n\t}\n\tif (a[l] >= le)\n\t\tm = l;\n\telse\n\t\tm = r;\n\tres = m;\n\tl = 0;\n\tr = n - 1;\n\twhile (r - l > 1)\n\t{\n\t\tm = (l + r) / 2;\n\t\tif (a[m] <= ri)\n\t\t\tl = m;\n\t\telse\n\t\t\tr = m;\n\t}\n\tif (a[r] <= ri)\n\t\tm = r;\n\telse\n\t\tm = l;\n\treturn m - res + 1;\n}\n\nint main()\n{\n\tcin >> n >> x >> k;\n\tfor (int i = 0; i < n; i++)\n\t\tcin >> a[i];\n\tsort(a, a + n);\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tll y = a[i] - 1;\n\t\ty /= x;\n\t\tll le = max(x*(k + y), a[i]);\n\t\tll ri = x*(k + y + 1) - 1;\n\t\tans += solve(le, ri);\n\t}\n\tcout << ans << endl;\n}"
|
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 elements chosen by these ways are different.
Since the answer can be very large, you should find the answer modulo $10^{9} + 7$.
|
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 of mask in $k$-th place if $k$-th prime number enters decomposition of that number odd times. Else there is $0$. For each integer between $1$ and $70$ we need to find the number of ways we can take odd and even amount of it from $a$. Let $f1[i]$, $f0[i]$ be that number of ways relatively. Let $dp[i][j]$ be the number of ways to choose some elements which are <= $i$ from $a$, and their product has only those prime numbers in odd degree on whose index number $j$ has $1$ in binary representation. Initially $dp[0][0] = 1$. $d p[i+1][j\oplus m a s k[i+1]]+=d p[i][j]*f][i+1]$ $dp[i + 1][j] + = dp[i][j] * f0[i + 1]$ The answer is $dp[70][0]$. Time complexity is $O$($max$*2^cnt(max)), where $max$ is maximal integer $a[i]$, and $cnt(max)$ is the number of prime numbers less than $max$.
|
[
"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_pair\n#define inf 1000000000\n#define MOD 1000000007\n#define eps 1e-7\n\nusing namespace std;\ntypedef long long ll;\n\nint n;\nint mask[72];\nll f[2][72];\nll dp[2][1 << 20];\n\nbool prime(int x)\n{\n\tfor (int i = 2; i*i <= x; i++)\n\t\tif (x%i == 0)\n\t\t\treturn 0;\n\treturn 1;\n}\n\nvoid init()\n{\n\tfor (int i = 0; i < 72; i++)\n\t\tf[0][i] = 1;\n\tint cnt = 0;\n\tfor (int i = 2; i < 72; i++)\n\t{\n\t\tif (!prime(i))\n\t\t\tcontinue;\n\t\tfor (int j = 1; j < 72; j++)\n\t\t{\n\t\t\tint x = j;\n\t\t\twhile (x%i == 0)\n\t\t\t{\n\t\t\t\tx /= i;\n\t\t\t\tmask[j] ^= (1 << cnt);\n\t\t\t}\n\t\t}\n\t\tcnt++;\n\t}\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0);\n\tinit();\n\tcin >> n;\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tint x;\n\t\tcin >> x;\n\t\tf[0][x] = f[1][x] = (f[0][x] + f[1][x]) % MOD;\n\t}\n\tdp[0][0] = 1;\n\tfor (int i = 0; i <= 70; i++)\n\t{\n\t\tint nxt = (i + 1) % 2;\n\t\tint cur = i % 2;\n\t\tfor (int msk = 0; msk < (1<<20); msk++)\n\t\t{\n\t\t\tdp[nxt][msk^mask[i]] = dp[nxt][msk^mask[i]] + dp[cur][msk] * f[1][i];\n\t\t\tdp[nxt][msk] = dp[nxt][msk] + dp[cur][msk] * f[0][i];\n\t\t\tif (dp[nxt][msk^mask[i]] >= MOD)\n\t\t\t\tdp[nxt][msk^mask[i]] %= MOD;\n\t\t\tif (dp[nxt][msk] >= MOD)\n\t\t\t\tdp[nxt][msk] %= MOD;\n\t\t}\n\t\tfor (int msk = 0; msk < (1<<20); msk++)\n\t\t\tdp[cur][msk] = 0;\n\t}\n\tcout << (dp[1][0] - 1 + MOD)%MOD << endl;\n}"
|
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 student, but he knows the mark $b$, such that every student recieved mark strictly smaller than $b$.
Vasya isn't satisfied with his mark so he decided to improve it. He can swap characters in the string corresponding to his mark as many times as he like. Now he want to know only the number of different ways to improve his mark so that his teacher didn't notice something suspicious.
More formally: you are given two strings $a$, $b$ of the same length and you need to figure out the number of different strings $c$ such that:
1) $c$ can be obtained from $a$ by swapping some characters, in other words $c$ is a permutation of $a$.
2) String $a$ is lexicographically smaller than $c$.
3) String $c$ is lexicographically smaller than $b$.
For two strings $x$ and $y$ of the same length it is true that $x$ is lexicographically smaller than $y$ if there exists such $i$, that $x_{1} = y_{1}, x_{2} = y_{2}, ..., x_{i - 1} = y_{i - 1}, x_{i} < y_{i}$.
Since the answer can be very large, you need to find answer modulo $10^{9} + 7$.
|
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 iterate through the position of the first different symbol in the permutation $a$ and the string $s$ and update the number of remaining symbols $cnt[26]$. For each such position, we need to iterate through the symbol in the permutation of $a$ which will stand in this position. It must be less than the character at this position in the $s$ string. For each such situation we can calculate and add to the answer the number of different permutations that can be obtained using symbols not currently involved. Their number is stored in $cnt[26]$. In its simplest form, this solution works in $O(n * k^{2})$, where $k$ is the size of the alphabet. Such a solution can't pass the tests, but it can be optimized to $O(n * k)$, and that is enough to solve the problem. Time complexity $O(n * k)$, where $k$ is the size of alphabet.
|
[
"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])
cur = (ll) cur * rfac[ c[i] ] % mod;
int ans = 0;
for(int i = 0; i < n; i++){
for(int x = 0; x < s[i] - 'a'; x++)
if(c[x]){
int now = cur;
now = (ll) now * save_rev[n - i] % mod;
now = (ll) now * c[x] % mod;
ans = (ans + now) % mod;
}
if(c[ s[i] - 'a' ]){
cur = (ll) cur * save_rev[n - i] % mod;
cur = (ll) cur * c[ s[i] - 'a' ] % mod;
c[ s[i] - 'a' ]--;
}
else
break;
}
return ans;
}
int rev(int a){
int ret = 1;
for(int b = mod - 2; b; b >>= 1, a = (ll) a * a % mod)
if(b & 1)
ret = (ll) ret * a % mod;
return ret;
}
int main(){
ios::sync_with_stdio(0), cin.tie(0);
fac[0] = rfac[0] = 1;
for(int i = 1; i < maxn; i++){
fac[i] = (ll) i * fac[i - 1] % mod;
save_rev[i] = rev(i);
rfac[i] = (ll) save_rev[i] * rfac[i - 1] % mod;
}
cin >> a >> b;
n = a.size();
for(auto c : a)
cnt[c - 'a']++;
cout << ((solve(b) + mod - solve(a)) % mod + mod - 1) % mod << '\n';
}
|
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, r2$ — boundaries of two non-intersecting segments. After that he swaps one random element from the $[l1, r1]$ segment with another random element from the $[l2, r2]$ segment.
$2)$ Petya asks Vasya the sum of the elements of $a$ in the $[l, r]$ segment.
Vasya is a mathematician so he answers Petya the mathematical expectation of the sum of the elements in the segment.
Your task is to write a program which will answer the second type questions as Vasya would do it. In other words your program should print the mathematical expectation of the sum of the elements of $a$ in the $[l, r]$ segment for every second type query.
|
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 a number from $[l2, r2]$ is $1 / (r1 - l1 + 1)$. The mathematical expectation of the number to which it will be replaced is the arithmetic mean of sum of the mathematical expectation of numbers in $[l2, r2]$, let it be $x$. Then, to update the expectation of a number from $[l1, r1]$, we need to multiply it by $(r1 - l1) / (r1 - l1 + 1)$ and add $x / (r1 - l1 + 1)$ to it. That is, the query of the first type is reduced to the query multiplying all the numbers in a segment and adding to them a number. To process the second type query, you must find the sum of the numbers in the segment. All these queries can be processed with the help of segment tree. Time complexity $O(x + q * log(n))$
|
[
"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;
return a;
}
void arpa(int l = 0, int r = n, int id = 1){
if(l + 1 == r){
int x;
cin >> x;
iman[id] = x;
return ;
}
int mid = l + r >> 1;
arpa(l, mid, id << 1);
arpa(mid, r, id << 1 | 1);
iman[id] = iman[id << 1] + iman[id << 1 | 1];
}
void sadra(int id, int l, int r){
int mid = l + r >> 1;
lz &x = sina[id];
iman[id << 1] = iman[id << 1] * x.a + x.b * (mid - l);
iman[id << 1 | 1] = iman[id << 1 | 1] * x.a + x.b * (r - mid);
sina[id << 1] += sina[id];
sina[id << 1 | 1] += sina[id];
sina[id] = lz();
}
void majid(int s, int e, lz x, int l = 0, int r = n, int id = 1){
if(s <= l && r <= e){
iman[id] = iman[id] * x.a + x.b * (r - l);
sina[id] += x;
return ;
}
if(e <= l || r <= s)
return ;
int mid = l + r >> 1;
sadra(id, l, r);
majid(s, e, x, l, mid, id << 1);
majid(s, e, x, mid, r, id << 1 | 1);
iman[id] = iman[id << 1] + iman[id << 1 | 1];
}
double hamid(int s, int e, int l = 0, int r = n, int id = 1){
if(s <= l && r <= e)
return iman[id];
if(e <= l || r <= s)
return 0;
int mid = l + r >> 1;
sadra(id, l, r);
return hamid(s, e, l, mid, id << 1) + hamid(s, e, mid, r, id << 1 | 1);
}
int main(){
ios::sync_with_stdio(0), cin.tie(0);
cout << fixed << setprecision(5);
cin >> n >> q;
arpa();
while(q--){
int t, l, r, x, y;
cin >> t >> l >> r;
l--;
if(t == 1){
cin >> x >> y;
x--;
double a = hamid(l, r) / (r - l), b = hamid(x, y) / (y - x);
majid(l, r, lz({(double) (r - l - 1) / (r - l), b / (r - l)}));
majid(x, y, lz({(double) (y - x - 1) / (y - x), a / (y - x)}));
}
else
cout << hamid(l, r) << '\n';
}
}
|
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 let more people know about it, so she defines $f_{i} = $ "What are you doing while sending "$f_{i - 1}$"? Are you busy? Will you send "$f_{i - 1}$"?" for all $i ≥ 1$.
For example, $f_{1}$ is
"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of $f_{1}$.
It can be seen that the characters in $f_{i}$ are letters, question marks, (possibly) quotation marks and spaces.
Nephren will ask the little leprechauns $q$ times. Each time she will let them find the $k$-th character of $f_{n}$. The characters are indexed starting from $1$. If $f_{n}$ consists of less than $k$ characters, output '.' (without quotes).
Can you answer her queries?
|
$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)$, which is sufficient to pass all tests. Obviously, $length(f(n)) \ge length(f(n - 1)) \cdot 2$, so $length(f(60)) \ge k_{max}$. It means that for all $n > 60$, the $k$-th character of $f(n)$ can only be in $str_{1}$ or the first $f(n - 1)$. Then we can answer a query in $O(\log k)$ time.
|
[
"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 will go on for $m$ rounds. In each round, Ithea will give Chtholly an integer between $1$ and $c$, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).
Chtholly wins if, at any time, all the sheets are filled with a number and the $n$ numbers are in non-decreasing order looking from left to right from sheet $1$ to sheet $n$, and if after $m$ rounds she still doesn't win, she loses the game.
Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number.
|
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 round, we either replace an existing number with a strictly smaller one, or fill in an empty sheet. The first case will happen at most $c - 1$ times for each sheet, and the second case will happen only once for each sheet. Thus in total, we will modify a sheet for at most $c$ times. Thus, the total rounds won't be more than $n \times c$. To pass all the tests, we only need to maintain 2 similar sequences, one non-decreasing from the first and one non-increasing from the last, which makes a total round of $(n-1)\times\lceil{\frac{c}{2}}\rceil+1$, precisely, and use binary search or brute force to complete the "finding" process.
|
[
"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.
Seniorious has $n$ pieces of talisman. Willem puts them in a line, the $i$-th of which is an integer $a_{i}$.
In order to maintain it, Willem needs to perform $m$ operations.
There are four types of operations:
- $1 l r x$: For each $i$ such that $l ≤ i ≤ r$, assign $a_{i} + x$ to $a_{i}$.
- $2 l r x$: For each $i$ such that $l ≤ i ≤ r$, assign $x$ to $a_{i}$.
- $3 l r x$: Print the $x$-th smallest number in the index range $[l, r]$, i.e. the element at the $x$-th position if all the elements $a_{i}$ such that $l ≤ i ≤ r$ are taken and sorted into an array of non-decreasing integers. It's guaranteed that $1 ≤ x ≤ r - l + 1$.
- $4 l r x y$: Print the sum of the $x$-th power of $a_{i}$ such that $l ≤ i ≤ r$, modulo $y$, i.e. $(\sum_{i=l}^{r}a_{i}^{~x})\operatorname{mod}~y$.
|
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 interval tree (std::set is enough) to maintain every interval that consists of the same number. And for operation $2$, we destory all the intervals in range $[l, r]$ , and put in a new interval $[l, r]$ into the interval tree. For operations $1$, $3$, $4$, we can brute-forcely walk on the tree, find every interval in range $[l, r]$, and do the required operation on it. Proof of time complexity: We suppose that we have a randomly selected range $[l, r]$ now, and we randomly choose which operation it is, suppose that there are $x$ intervals in this range. 1/4 possibility we use $O(x)$ time to erase $O(x)$ nodes. 2/4 possibility we use $O(x)$ time to erase nothing. 1/4 possibility we use $O(x)$ time to erase nothing and add 2 new nodes into the tree. So we are expected to use $O(x)$ time to erase $O(x)$ nodes. By using interval tree to maintain, the time complexity of this problem is $O(m\log n)$. If operation $3$ and $4$ are changed into output the sum of $a_{i}$ for every $i$ range $[l, r]$, it seems that the time complexity may change into $O(m\log\log n)$ , but I do not know how to prove it... Solution using map
|
[
"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) += ch & 15;
while (ch = getchar(), is_digit(ch));
return *this;
}
IO_Tp& operator>>(int64& res)
{
res = 0;
static char ch;
while (ch = getchar(), !is_digit(ch))
;
do
(res *= 10) += ch & 15;
while (ch = getchar(), is_digit(ch));
return *this;
}
} IO;
int64 Power(int64 Base, int64 Exp, int64 Mod)
{
Base %= Mod;
int64 res(1);
do
{
if (Exp & 1)
(res *= Base) %= Mod;
(Base *= Base) %= Mod;
}
while (Exp >>= 1);
return res;
}
int64 seed;
int rnd()
{
int res(seed);
seed = (seed * 7 + 13) % 1000000007;
return res;
}
int N, M, V_Max;
map<int, int64> A;
int main(int argc, char** argv)
{
IO >> N >> M >> seed >> V_Max;
for (int i(1); i <= N; ++i)
A.insert(A.end(), make_pair(i, rnd() % V_Max + 1));
A.insert(A.end(), make_pair(N + 1, 0));
while (M--)
{
int op((rnd() % 4) + 1);
int l((rnd() % N) + 1);
int r((rnd() % N) + 1);
int x, y;
if (l > r)
swap(l, r);
if (op == 3)
x = (rnd() % (r - l + 1)) + 1;
else
x = (rnd() % V_Max) + 1;
if (op == 4)
y = (rnd() % V_Max) + 1;
auto it_l(--A.upper_bound(l));
if (it_l->first != l)
A[l] = it_l->second, ++it_l;
auto it_r(--A.upper_bound(r + 1));
if (it_r->first != r + 1)
A[r + 1] = it_r->second, ++it_r;
switch (op)
{
static vector<pair<int64, int>> v;
static int64 res;
case 1:
while (it_l != it_r)
(--it_r)->second += x;
break;
case 2:
while (it_l != it_r)
A.erase(it_l++);
A[l] = x;
break;
case 3:
v.clear();
for (int ub; it_l != it_r; )
ub = (it_r--)->first, v.push_back(make_pair(it_r->second, ub - it_r->first));
sort(v.begin(), v.end());
for (int i(0), cnt(0); ; ++i)
if (x <= (cnt += v[i].second))
{
printf("%I64d\n", v[i].first);
break;
}
break;
case 4:
res = 0;
for (int ub; it_l != it_r; )
ub = (it_r--)->first, (res += Power(it_r->second, x, y) * (ub - it_r->first)) %= y;
printf("%I64d\n", res);
break;
}
}
return 0;
}
|
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 types of customers: some of them bring exactly a 50-yuan note; some of them bring a 100-yuan note and Nephren needs to give a 50-yuan note back to him/her; some of them bring VIP cards so that they don't need to pay for the ticket.
Now $n$ customers are waiting outside in queue. Nephren wants to know how many possible queues are there that they are able to run smoothly (i.e. every customer can receive his/her change), and that the number of 50-yuan notes they have after selling tickets to all these customers is between $l$ and $r$, inclusive. Two queues are considered different if there exists a customer whose type is different in two queues. As the number can be large, please output the answer modulo $p$.
|
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 2d-plane, the answer to our second question is the ways of drawing lines from (0,0) to (n,0), such that two adjacent points' y-axis have a difference of 1, and that all the points are above the x-axis. The total routes will be $C_{n}^{n / 2}$, but some of them are invalid. Consider another route starting from (0,-2). For each invalid way in the previous route, consider the first point (x,y) that y<0 (y=-1). By creating a symmetry route with y=-1 for the route before this point, this route will become exactly one route starting from (0,-2), and every route starting from (0,-2) will become an invalid route in a similar way. So the number of invalid routes is $C_{n}^{n / 2 - 1}$ (that is the number of routes from (0,-2) to (n,0)). Thus the answer will be $C_{n}^{n / 2} - C_{n}^{n / 2 - 1}$. Similarly if there are [l,r] 50-$yuan$ notes left, the answer will be $C_{n}^{n / 2 - r / 2} - C_{n}^{n / 2 - l / 2 - 1}$. Now let's enumerate how many customers are there with VIP cards. If there are $i$ of them, the answer will time a factor $C_{n}^{i}$. One last question is about the modulo number. First separate it into forms like $(p_{1}^{a1}) * (p_{2}^{a2})$... where $p_{1}...$ are primes. We can calculate how many factor $p_{i}$ are there in $(j!)$, and the modulo value of the remaining ones. Each time we take out a facter $p_{i}$ in $(j!)$, and it becomes some product of numbers that are not divisble by $p_{i}$ as well as a remaining part $(j / p_{i})!$. For example, we want to calculate the number of factor 3 in (16!), and the product of numbers that are not divisble by 3 in (16!) mod (3^2). Then we have: 16! = (1 * 2 * 4 * 5 * 7 * 8 * 10 * 11 * 13 * 14 * 16) * (1 * 2 * 3 * 4 * 5) * (3^5) The first part are not divisble by 3, so we can calculate their value (mod 3^2) in advance, the second part is a smaller problem (5!), so we can solve it recursively. For the number of factor 3, just add 5 in this case and solve it recursively. After calculating how many factor $p_{i}$ in $(j!)$ and the modulo value of the remaining ones, we can calculate the combnation numbers correctly. Finally use Chinese Remainder Algorithm to combine them.
|
[
"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 skilled in making dessert, he rarely bakes butter cake.
This time, Willem made a big mistake — he accidentally broke the oven!
Fortunately, Chtholly decided to help him.
Willem puts $n$ cakes on a roll, cakes are numbered from $1$ to $n$, the $i$-th cake needs $a_{i}$ seconds of baking.
Willem needs Chtholly to do $m$ operations to bake the cakes.
Operation 1: $1 l r x$
Willem asks Chtholly to check each cake in the range $[l, r]$, if the cake needs to be baked for more than $x$ seconds, he would bake it for $x$ seconds and put it back in its place. More precisely, for every $i$ in range $[l, r]$, if $a_{i}$ is strictly more than $x$, $a_{i}$ becomes equal $a_{i} - x$.
Operation 2: $2 l r x$
Willem asks Chtholly to count the number of cakes in the range $[l, r]$ that needs to be cooked for exactly $x$ seconds. More formally you should find number of such $i$ in range $[l, r]$, that $a_{i} = x$.
|
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 block. This can be maintained by using DSU or linked list. By maintaining this, we can get the value of every number in a block in $O({\sqrt{n}})$ time. Notice that this two operations are the same: $1.$For every number that is bigger than $x$, decrease it by $x$ $2.$Decrease every number by $x$, and for every number that is less than $1$, increase it by $x$ For operation $1$: We get the value of each number in block $belong[l]$ and $belong[r]$ using the DSU or linked list, then for every number that should change, we change them. Then we build block $belong[l]$ and $belong[r]$ up again. For blocks numbered from $belong[l] + 1$ to $belong[r] - 1$: If $x \times 2$ $ \le $ max value in block $p$ We merge all the numbers in range $[1, x]$ to $[x + 1, x \times 2]$, and add $x$ to $tag[p]$ , $tag[p]$ means that all the numbers in block $p$ has decreased by $tag[p]$. If $x \times 2$ ${}_{\sim}\geq$ max value in block $p$ We merge all the numbers in range $[x + 1, maxvalue]$ to $[1, maxvalue - x]$. For operation $2$: We get the value of each number in block $belong[l]$ and $belong[r]$ using the DSU or linked list. We only need to traverse all the numbers in blocks $belong[l]$ and $belong[r]$, and traverse all the blocks between $belong[l]$ and $belong[r]$. For block $i$ in range $[l, r]$, $f[i][x + tag[i]]$ is the number of $x$ in block $i$, so we just need to add this into the answer Proof of time complexity: There are $O({\sqrt{n}})$ blocks. The difference between the max number and the min number in each block is initially $n$. So the sum of this in every block is $O(n{\sqrt{n}})$. For each operation $1$, we use $O(x)$ time or $O(max - x)$ time to make the difference of max and min element $O(x)$ or $O(max - x)$ smaller. For each operation $2$, we traverse $O({\sqrt{n}})$ numbers and $O({\sqrt{n}})$ blocks. So the total time complexity if $O(n{\sqrt{n}}+m{\sqrt{n}})$ There seems to be another algorithm with the same time complexity, and has a smaller constant, but I couldn't prove its complexity so I used this algorithm instead.
|
[
"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[ MAXN ] , pos[ MAXN ] , L[ MAXN ] , R[ MAXN ];
struct point
{
unsigned char num , root;
} V[ MAXD ][ MAXN ];
inline void merge( int p , int a , int b )
{
register point x = V[p][a] , y = V[p][b];
y.root ? pre[ x.root + l( p ) - 1 ] = y.root + l( p ) - 1 : ( y.root = x.root , pos[ y.root + l( p ) - 1 ] = b );
y.num += x.num , * ( short * ) & x = 0;
V[p][a] = x , V[p][b] = y;
}
inline int find( int x )
{
while( x != pre[x] )
x = pre[x] = pre[ pre[x] ];
return x;
}
inline void pushdown( int v )
{
for( register int i = l( v ) ; i <= r( v ) ; i++ )
a[i] = pos[ find( i ) ] , V[v][ a[i] ].root = 0 , V[v][ a[i] ].num = 0 , a[i] -= L[v];
for( register int i = l( v ) ; i <= r( v ) ; i++ )
pre[i] = 0;
L[v] = 0;
}
inline void update( int v )
{
R[v] = 0;
for( register int i = l( v ) ; i <= r( v ) ; i++ )
{
if( a[i] > R[v] ) R[v] = a[i];
if( !V[v][ a[i] ].root ) pre[i] = i , V[v][ a[i] ].root = i - l( v ) + 1 , pos[i] = a[i];
else pre[i] = V[v][ a[i] ].root + l( v ) - 1;
V[v][ a[i] ].num++;
}
}
inline void modify( int x , int v )
{
int & p = L[x] , & q = R[x];
if( v * 2 <= q - p )
{
for( register int i = p + 1 ; i <= p + v ; i++ )
Merge( x , i , i + v );
p += v;
}
else
{
for( register int i = q ; i > p + v ; i-- )
Merge( x , i , i - v );
q = min( q , p + v );
}
}
inline void modify( int x , int y , int v )
{
int p = belong[x] , q = belong[y];
if( p == q )
{
pushdown( p );
for( register int i = x ; i <= y ; i++ )
if( a[i] > v )
a[i] -= v;
update( p );
}
else
{
pushdown( p ) , pushdown( q );
for( register int i = x ; i <= r( p ) ; i++ )
if( a[i] > v )
a[i] -= v;
for( register int i = l( q ) ; i <= y ; i++ )
if( a[i] > v )
a[i] -= v;
for( int i = p + 1 ; i <= q - 1 ; i++ )
modify( i , v );
update( p ) , update( q );
}
}
inline int find( int x , int y , int v )
{
int ans = 0 , p = belong[x] , q = belong[y];
if( p == q )
for( register int i = x ; i <= y ; i++ )
if( pos[ find( i ) ] - L[ p ] == v )
ans++;
else;
else
{
for( register int i = x ; i <= r( p ) ; i++ )
if( pos[ find( i ) ] - L[ p ] == v )
ans++;
else;
for( register int i = l( q ) ; i <= y ; i++ )
if( pos[ find( i ) ] - L[ q ] == v )
ans++;
for( register int i = p + 1 ; i <= q - 1 ; i++ )
if( v + L[i] <= 100000 )
ans += V[i][ v + L[i] ].num;
}
return ans;
}
struct io
{
char ibuf[1 << 22] , * s , obuf[1 << 20] , * t;
int a[24];
io() : t( obuf )
{
ibuf[ fread( s = ibuf , 1 , 1 << 22 , stdin ) ] = 0;
}
~io()
{
fwrite( obuf , 1 , t - obuf , stdout );
}
inline int read()
{
register int u = 0;
while( * s < 48 )
s++;
while( * s > 32 )
u = u * 10 + * s++ - 48;
return u;
}
template < class T >
inline void print( T u , int v )
{
print( u );
* t++ = v;
}
template< class T >
inline void print( register T u )
{
static int * q = a;
if( !u ) * t++ = 48;
else
{
if( u < 0 )
* t++ = 45 , u *= -1;
while( u ) * q++ = u % 10 + 48 , u /= 10;
while( q != a )
* t++ = * --q;
}
}
} ip;
#define read ip.read
#define print ip.print
int main()
{
n = read() , m = read();
for( register int i = 1 ; i <= n ; i++ ) a[i] = read() , belong[i] = ( i - 1 ) / block + 1;
for( int i = 1 ; i <= belong[n] ; i++ )
update( i );
while( m-- )
{
int opt = read() , l = read() , r = read() , v = read();
if( opt == 1 ) modify( l , r , v );
else print( find( l , r , v ) , 10 );
}
return 0;
}
|
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 directions, Grick helped them, and gave them a task.
Although the girl wants to help, Willem insists on doing it by himself.
Grick gave Willem a string of length $n$.
Willem needs to do $m$ operations, each operation has four parameters $l, r, c_{1}, c_{2}$, which means that all symbols $c_{1}$ in range $[l, r]$ (from $l$-th to $r$-th, including $l$ and $r$) are changed into $c_{2}$. String is 1-indexed.
Grick wants to know the final string after all the $m$ operations.
|
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 palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.
Given integers $k$ and $p$, calculate the sum of the $k$ smallest zcy numbers and output this sum modulo $p$.
Unfortunately, Willem isn't good at solving this kind of problems, so he asks you for help!
|
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 which integer will Vasya round it.
|
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{exactly} $n$ burles.
In other words, you should find two non-negative integers $x$ and $y$ such that Vasya can buy $x$ bottles of Ber-Cola and $y$ Bars bars and $x·a + y·b = n$ or tell that it's impossible.
|
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 there is no answer and we should print "NO".
|
[
"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 friend's name. Then follows the number of phone numbers in the current entry, and then the phone numbers themselves. It is possible that several identical phones are recorded in the same record.
Vasya also believes that if the phone number $a$ is a suffix of the phone number $b$ (that is, the number $b$ ends up with $a$), and both numbers are written by Vasya as the phone numbers of the same person, then $a$ is recorded without the city code and it should not be taken into account.
The task is to print organized information about the phone numbers of Vasya's friends. It is possible that two different people have the same number. If one person has two numbers $x$ and $y$, and $x$ is a suffix of $y$ (that is, $y$ ends in $x$), then you shouldn't print number $x$. If the number of a friend in the Vasya's phone books is recorded several times in the same format, it is necessary to take it into account exactly once.
Read the examples to understand statement and format of the output better.
|
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 check it with help of set). After that we need only to remove for each friend the numbers which are the suffixes of other number of that friend. The time limit allows to make it in time equals to square of phone number count for a current friend. Now we need to iterate through map key set (it will be names of all Vasya's friends) and print all remaining phone numbers for each friend.
|
[
"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 definitely wake up if during some $m$ consecutive minutes at least $k$ alarm clocks will begin ringing. Pay attention that Vitalya considers only alarm clocks which begin ringing during given period of time. He doesn't consider alarm clocks which started ringing before given period of time and continues ringing during given period of time.
Vitalya is so tired that he wants to sleep all day long and not to wake up. Find out minimal number of alarm clocks Vitalya should turn off to sleep all next day. Now all alarm clocks are turned on.
|
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 first set element. After that only alarm with times not before $m - 1$ minutes relatively $x$ will be in set. If after that the set size less than $k - 1$ we should insert $x$ in the set (we will not turn off this alarm). In the other case, we should turn off this alarm, so we increase the answer on one and do not insert $x$ in the set.
|
[
"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 candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile).
Find out minimal number of moves that is required to make exactly $n / 2$ piles contain number of candies that is a square of some integer and exactly $n / 2$ piles contain number of candies that is not a square of any integer.
|
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 are not integer squares. If $cnt_{1} = = cnt_{2}$, then we should not to change anything and the answer is $0$. If $cnt_{1} > cnt_{2}$, then we should to make $(cnt_{1} - cnt_{2}) / 2$ numbers-squares not to be squares. To make it we need to take $(cnt_{1} - cnt_{2}) / 2$ numbers-squares, which do not equal to $0$ and increase them by $1$. If such numbers do not enough we should take needed number of $0$ and increase them by $2$. If $cnt_{1} < cnt_{2}$, then we should to make $(cnt_{2} - cnt_{1}) / 2$ numbers, which do not squares, to be squares. Let's calculate for each such number the number of operations to make this number square-number and put this value in separate vector. After than we should sort vector in increasing order and print the sum of first $(cnt_{2} - cnt_{1}) / 2$ vector elements.
|
[
"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 so that:
- character'+' is placed on the left of character '=',
- characters '+' and '=' split the sequence into three non-empty subsequences consisting of digits (let's call the left part a, the middle part — b and the right part — c),
- all the three parts a, b and c do not contain leading zeros,
- it is true that a+b=c.
It is guaranteed that in given tests answer always exists.
|
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 summation, let this value is $len_{3}$. Because when two numbers are added the result may have the same length as the larger term, or may have a length one greater than the length of the larger term it is enough to check the following cases ($len_{1}$ - the length of the first term, $len_{2}$ - the length of the second term): $len_{1} = len_{3}$, $len_{2} = n - len_{1} - len_{3}$ $len_{1} = len_{3} - 1$, $len_{2} = n - len_{1} - len_{3}$ $len_{2} = len_{3}$, $len_{1} = n - len_{2} - len_{3}$ $len_{2} = len_{3} - 1$, $len_{1} = n - len_{2} - len_{3}$ For each case the check algorithm is the same. At first we should check that all parts have positive length, that the length $len_{3}$ satisfies the conditions described at the beginning of the tutorial and that it part has no trailing spaces. Now we should divide each part on $10$ in the needed power, to bring the value of the calculated "hash" to the desired degree. To make it we can multiply each part on element, which is reverse to $10$ by the used module, in the desired power. To find $r$ which is reverse to $10$ be the prime module $MOD$ we should raising $10$ to the power $(MOD - 2)$ with help of binary power raising. If after the described operations the sum of first to parts by used module equals to the value of third part, we found the answer and we should print corresponding parts. You could also perform calculations on several smaller modules.
|
[
"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 teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.
|
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}$ - the answer is $cnt_{2} + (cnt_{1} - cnt_{2}) / 3$. In the other case, the answer is $cnt_{1}$.
|
[
"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 November, $31$ in December.
A year is leap in one of two cases: either its number is divisible by $4$, but not divisible by $100$, or is divisible by $400$. For example, the following years are leap: $2000$, $2004$, but years $1900$ and $2018$ are not leap.
In this problem you are given $n$ ($1 ≤ n ≤ 24$) integers $a_{1}, a_{2}, ..., a_{n}$, and you have to check if these integers could be durations in days of $n$ consecutive months, according to Gregorian calendar. Note that these months could belong to several consecutive years. In other words, check if there is a month in some year, such that its duration is $a_{1}$ days, duration of the next month is $a_{2}$ days, and so on.
|
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 sequence can be found in the generated array. For example, we can brute the beginning of the sequence in the array and check the correspondence of the elements of the given sequence to the corresponding elements of the generated array.
|
[
"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 which give a remainder $0$ or $1$ when dividing by $4$. If $n$ gives a remainder $2$ when dividing by $4$ than the sum of all numbers from $1$ to $n$ is odd. Then we can divide numbers on two groups in such a way that absolute difference between sum of numbers in each part is $1$ (because the sum of all numbers is odd, then we can not improve the answer). To make this, we need to take the same numbers in the same group as in the previous case. If $n$ gives a remainder $3$ when dividing by $4$ 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 this, we need to take in one group all numbers from $1$ to $n / 4$, inclusively, and all last $(n / 4 + 1)$ numbers (i.e. numbers from $(n - n / 4)$ to $n$, inclusively). If $n$ gives a remainder $1$ when dividing by $4$ than the sum of all numbers from $1$ to $n$ is odd. Then we can divide numbers on two groups in such a way that absolute difference between sum of numbers in each part is $1$ (because the sum of all numbers is odd, then we can not improve the answer). To make this, we need to take in one group all numbers from $1$ to $(n / 4 + 1)$, inclusively, and all last $n / 4$ numbers (i.e. numbers from $(n - n / 4 + 1)$ to $n$, inclusively).
|
[
"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 with several $9$s. Because of this, Polycarp wants to choose a pair of shovels to sell in such a way that the sum of their costs ends with maximum possible number of nines. For example, if he chooses shovels with costs $12345$ and $37454$, their total cost is $49799$, it ends with two nines.
You are to compute the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Two pairs are considered different if there is a shovel presented in one pair, but not in the other.
|
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 that we should try to write each digit from $0$ to $8$ to the beginning of $cur$. Let we wrote next digit $c$ and $cur$ became equal to $p$ (i.e. the first digit is $c$ and other digits are nines). So we need to add to the answer the number of ways to take two different digits from $1$ to $n$ in such a way that their sum equals to $p$. If $p \le (n + 1)$, we should add to the answer $p / 2$. If $p > n + (n - 1)$ we should to add to the answer nothing. Else we should add to the answer the value $(n + (n - 1) - sum) / 2$.
|
[
"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 operation it becomes $[13, 13, 2, 2, 2]$.
Compute the number of operations Vasya should make until the array becomes empty, i.e. Vasya removes all elements from it.
|
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 numbers in a format - the position of the beginning of the segment and the length of the segment. Initially we will put in the sets all segments from the given array consisting of the same numbers. After that we will repeat the following algorithm until in sets there are non-deleted segments: increase answer on $1$; take from $lens$ the longest and the leftmost segment (it will be in the beginning of the $lens$, because we store here all length multiplied on $- 1$) and remove it from $lens$. Let this segment beginning in the position $st$ and has length $len$; with help of $lower_{bound}$ we can find in $segments$ the left and the right segments relatively the segment from the previous article. After that we should remove from the segments the segment $(st, len)$; if both left and right relatively of the current longest segment there are non-deleted segments and they consisting of the same numbers, we should to unite them in one segment. To do this, we should remove the left and right segments from $lens$ and $segments$ and put the new merged segment in $lens$ and $segments$ in the described format.
|
[
"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 length of the string remains the same or decreases after each operation.
Find how the string will look like after Petya performs all $m$ operations.
|
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 help of segments tree or sqrt-decomposition. After we transformed $l$ and $r$ we should find the first position in set for character $c$ (with help of lower_bound) which is in range $[l, r]$ and remove positions from the corresponding set until they are in range $[l, r]$. Also we need to update information in data structure which we use to transform the given in the query $l$ and $r$ to the positions in the initial string. This algorithm will fit into the time limit, because we will delete each position no more than once. After we process all queries we should iterate through all sets, find all non-deleted positions and print characters, which are in that positions in the initial string (do not forget before that to sort all non-deleted positions in increasing order).
|
[
"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 records after removal the $i$-th element and initial number of records. Let's think of how does removal of $a_{i}$ influence the array $r_{i}$. First of all, $r_{i}$ becomes $0$. $r_{j}$ ($j < i$) do not change in this case. Some of $r_{j}$ ($j > i$), change from $0$ to $1$. These elements are not records initially, but become records after the removal. These elements are elements which have only one greater element in front of them - $a_{i}$. Here follows an $O(n^{2})$ solution. Let's fix $a_{i}$ - the element we are going to remove. Let $x_{i}$ = $- r_{i}$ $+$ the number of such $j$ that $j > i$, $a_{i} > a_{j}$, and for all $k$ ($k \neq i, k < j$) $a_{k} < a_{j}$. We can compute this just looping through all j and keeping the maximum over all elements but the $i$-th. Now note that it's not required to fix $a_{i}$. $r_{j}$ can become $1$ from $0$ only when a certain element from the left is removed. Let's loop through all $a_{j}$ and determine if there is an element to the left such that it is greater than $a_{j}$, but all other elements are less than $a_{j}$. We can check this using ordered set. If there is such a $a_{i}$, then increase $x_{i}$ by $1$. After the loop the array $x_{i}$ is fully computed, so we can just find the element which brings the maximum number of records, and minimum among such.
|
[
"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(t)$. Then $g(t)$ is $2^{(t - 1)}$: represent all integers in the sequence in unary system with zeros, and split them with $t - 1$ ones. Note that $g(t)=\sum_{i=1}^{|t_{i}|}f({\frac{t}{t}})$, where ${t_{i}}$ are divisors of $t$. Then $f(t)=g(t)-\sum_{i=2}^{s_{z}}f({\frac{t}{t_{i}}})=2^{(t-1)}-\sum_{i=2}^{|t_{i}|}f({\frac{t}{t_{i}}})$. What's the complexity?. We know that the number of divisors of $t$ is not greater than $O(\lambda^{\prime}t)$. We can also note than every divisor of divisor of $t$ is a divisor of $t$. Thus we need for compute only $f(t_{i})$ for every $t_{i}|t$. Thus computing $f(t_{i})$ takes $O(\lambda^{\sqrt{t}})=O(\lambda^{\sqrt{t}})$ steps when all $f(t_{j})$, $t_{j} < t_{i}$ are already computed. The total complexity is $O(\lambda^{\widehat{2}})$, but on practice it works much faster than one can expect. Also, we can use Möbius function to solve this problem. This solution has a better complexity, but we will leave this solution as an exercise for readers.
|
[
"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 his string. Some letters of the string $s$ were replaced by character '?'.
Let's call a sequence of positions $i, i + 1, ..., i + m - 1$ as occurrence of string $t$ in $s$, if $1 ≤ i ≤ n - m + 1$ and $t_{1} = s_{i}, t_{2} = s_{i + 1}, ..., t_{m} = s_{i + m - 1}$.
The boy defines the beauty of the string $s$ as maximum number of disjoint occurrences of string $t$ in $s$. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string $s$ is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
|
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 + m - 2)}$ should be equal to '?' or 'b'. Let's calculate $f[i][c]$ - how many consecutive letters $s_{i}, s_{i + 2}, ..., s_{(f[i][c] - 1) \cdot 2}$ are equal to '?' or $c$. Than it is left to verify for position $i$ or $f[i][a] \ge cell(n / 2)$ and $f[i][b] \ge floor(n / 2)$. We found all positions where occurrence of $t$ can start. Remaining task can be solved using dynamic programming. Let $dp[i][j]$ - the minimum number of replacements should be done that the number of occurrences in prefix $i$ is exactly maximum possible minus $j$. How to calculate this dp? If from position $i + 1$ can be started occurrence than $dp[i + m][MaxOccur_{i + m} - (MaxOccur_{i} - j)] = best(dp[i + m][MaxOccur_{i + m} - (MaxOccur_{i} - j)], dp[i][j] + CountQuestions_{i + 1, }_{i + m})$. Where $CountQuestions_{i, }_{j}$ means the number of letter '?' in substring from position $i$ to $j$ and $MaxOccur_{i}$ means the maximum number of occurrences in prefix from position $1$ to $i$, that can be calculated greedily. Actually considering $j > 1$ is redundant. Really, if we consider such set of occurrences that exists prefix for which the number of occurrences at least two less than maximum possible than we always can find the larger set of occurrences taking the maximum possible in this prefix and maybe deleting one that intersects with the prefix. The answer is $dp[n][0]$. Time complexity $O(n)$.
|
[
"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 trees. Sasha wants to match each tree with a sequence $a_{0}, a_{1}, ..., a_{h}$, where $h$ is the height of the tree, and $a_{i}$ equals to the number of vertices that are at distance of $i$ edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence $a_{i}$, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
|
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 different vertices from previous levels during construction to make it different from first tree. This is always possible if there are two consecutive $a_{i} > 1$. Otherwise the tree is determined uniquely by $a_{i}$ sequence.
|
[
"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 degree of polynomial $P(x)$. $R(x)$ is called the remainder of division of polynomial $A(x)$ by polynomial $B(x)$, it is also denoted as $A\bmod B$.
Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials $(A,B)$. If the polynomial $B(x)$ is zero, the result is $A(x)$, otherwise the result is the value the algorithm returns for pair $(B,A{\mathrm{~mod~}}B)$. On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question.
You are given an integer $n$. You have to build two polynomials with degrees not greater than $n$, such that their coefficients are integers not exceeding $1$ by their absolute value, the leading coefficients (ones with the greatest power of $x$) are equal to one, and the described Euclid's algorithm performs exactly $n$ steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair $(A,B)$ to pair $(B,A{\mathrm{~mod~}}B)$.
|
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}$ Gives us the family of solutions, we just have to output $p_{n}$ and $p_{n - 1}$. It can be directly checked for given constraints that you can always choose $+$ or $-$ to satisfy coefficients constraints. The other solution is the same sequence but you use $+$ instead of $ \pm $ and take coefficients modulo $2$. That's true because if remainders sequence has $k$ steps while you consider numbers by some modulo it will have at least $k$ steps in rational numbers. So the second intended solution is $p_{0} = 1, p_{1} = x,$ $p_{n+1}=x\cdot p_{n}+p_{n-1}\,\,{\mathrm{mod}}\,\,2$
|
[
"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 vertices $[l; r]$, and you have to count the number of its subsegments $[x; y]$ ($l ≤ x ≤ y ≤ r$), such that if we delete all vertices except the segment of vertices $[x; y]$ (including $x$ and $y$) and edges between them, the resulting graph is bipartite.
|
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 on this segment and the vertex with the maximum number from this cycle is present on this segment. Then we can select all the cycles, and now we work with the segments. Let us find for each vertex a maximal right boundary such that the interval $[i$..$mx_{i}]$ is a bipartite graph. Then $mx_{i}$ is equal to the minimal right boundary of the segment, which was opened later $i$. This can be considered a minimum on the suffix, initially setting for all cycles $mx$[minimum on the cycle] = maximum on the cycle To answer the query, we need to take the sum over $mx_{i} - i + 1$ for those who have $mx_{i} \ge r$ and the sum over $r - i + 1$ for those who have $mx_{i} \ge r$ then we note that $mx_{i}$ increases and we simply need to find the first moment when $mx_{i}$ becomes $ \ge r$ (we can do it with binary search) And take two prefix sums - sum of ($mx_{i} - i + 1$) and sum of $i$.
|
[
"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$. The degree of a vertex is the number of edges connected to it.
You are to write a weight between $ - 2·n^{2}$ and $2·n^{2}$ (inclusive) on each edge in such a way, that for each vertex $v$ the sum of weights on edges connected to this vertex is equal to $c_{v}$, or determine that this is impossible.
|
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 is unique (take the edges entering the leafs, their weights are uniquely determined, subtract weights from weights of the second ends of this edges, delete the leafs, recursively) this solution can be found with dfs, then in the end, the root will has weight 0 (because sum of weights of the left part equal to the sum of weights of the right part) Thus, the answer exists when the sum of the weights of the left part is equal to the sum of the weights of the right part. Second case when graph has the odd cycle. We find an odd cycle, root the tree for any of its vertices, solve the tree. Then, we add to the weights of the edges of the cycle adjacent to the root minus its weight divided by 2 (it is even, because it is the sum of the weights of all vertices (with different signs) equal to the sum of the degrees of vertices by modulo 2). , and for all others we alternate the signs with which we add this value, then for all vertices except the root the sum does not change, but for the root we get the required value.
|
[
"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 <bitset>\n\nusing namespace std;\n\ntypedef long long ll;\n\nmt19937 rnd(228);\n\nconst int N = 1e5 + 7;\n\nvector <pair <int, int> > g[N];\n\nll c[N];\nll cur[N];\nll ans[N];\nbool u[N];\nint col[N];\nint par[N];\nint d[N];\nint par_ind[N];\n\nint s = -1, t = -1;\nint edge_ind = -1;\n\nvoid dfs(int v)\n{\n u[v] = true;\n for (auto x : g[v])\n {\n int to = x.first, ind = x.second;\n if (!u[to])\n {\n d[to] = d[v] + 1;\n col[to] = (col[v] ^ 1);\n par[to] = v;\n par_ind[to] = ind;\n dfs(to);\n ans[ind] = cur[to];\n cur[v] -= cur[to];\n }\n else if (d[to] < d[v])\n {\n if (col[to] == col[v])\n {\n s = v, t = to;\n edge_ind = ind;\n }\n }\n }\n}\n\nvoid solve_tree(int v)\n{\n u[v] = true;\n for (auto x : g[v])\n {\n int to = x.first, ind = x.second;\n if (ind != edge_ind && !u[to])\n {\n solve_tree(to);\n ans[ind] = c[to];\n c[v] -= c[to];\n }\n }\n}\n\n\nint main()\n{\n#ifdef ONPC\n freopen(\"a.in\", \"r\", stdin);\n#endif\n int n, m;\n scanf(\"%d%d\", &n, &m);\n for (int i = 0; i < n; i++)\n {\n scanf(\"%lld\", &c[i]);\n cur[i] = c[i];\n }\n for (int i = 0; i < m; i++)\n {\n int a, b;\n scanf(\"%d%d\", &a, &b);\n a--, b--;\n g[a].push_back({b, i});\n g[b].push_back({a, i});\n }\n dfs(0);\n if (cur[0] == 0)\n {\n puts(\"YES\");\n for (int i = 0; i < m; i++)\n {\n printf(\"%lld\\n\", ans[i]);\n }\n return 0;\n }\n if (edge_ind != -1)\n {\n for (int i = 0; i < m; i++)\n {\n ans[i] = 0;\n }\n for (int i = 0; i < n; i++)\n {\n u[i] = 0;\n }\n solve_tree(s);\n ll get = c[s] / 2;\n int cur = s;\n int sign = 1;\n while (cur != t)\n {\n ans[par_ind[cur]] += sign * get;\n sign *= -1;\n cur = par[cur];\n }\n ans[edge_ind] += sign * get;\n puts(\"YES\");\n for (int i = 0; i < m; i++)\n {\n printf(\"%lld\\n\", ans[i]);\n }\n }\n else\n {\n puts(\"NO\");\n return 0;\n }\n}"
|
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 independent, that is, there is no non-zero set of coefficients $x_{0}, x_{1}, ..., x_{n - 1}$, such that $\sum_{i=0}^{n-1}x_{i}b_{k-i\,\mathrm{mod}\,n}=0$ for all $k$ at the same time.
After that for a sequence $\{a_{i}\}_{i=0}^{n-1}$ you should build the following cipher:
\[
c_{i}=\sum_{k=0}^{n-1}\left(b_{k-i\,\mathrm{mod}\,n}-a_{k}\right)^{2}
\]
In other words, you are to compute the quadratic deviation between each cyclic shift of $b_{i}$ and the sequence $a_{i}$. The resulting sequence is the Kickass's cipher. The cipher is in development right now and Vorpal wants to decipher a sequence after it has been encrypted. You are to solve this problem for him. You are given sequences $c_{i}$ and $b_{i}$. You are to find all suitable sequences $a_{i}$.
|
$(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 corresponds to cyclic convolution of polynomials $B=\sum_{k=0}^{n-1}b_{k}x^{k}$ and $A=\sum_{k=0}^{n-1}a_{k}x^{n-k}$. These polynomials uniquely determined by values in roots of unity of degree $n$. Thus we can divide values of $C$ by values of $B$ in this points and return to polynomials from values in roots of unity. To do this one should compute discrete Fourier Transform in arbitrary length polynomial which can be done by Bluestein's algorithm. Note that you can't use complex fft here because real values can be very close to zero leading to great precision issues. Thus you should find some mod having root of unity of degree $2n$ and compute discrete transform over it. Thus we will find $d_{k} = a_{k} - a_{0}$ for each $k$, which will allow us to recover $a_{0}$, because $c_{0}=\sum_{i=0}^{n-1}(b_{i}-a_{i})^{2}=\sum_{i=1}^{n-1}(b_{i}-d_{i}-a_{0})^{2}=\sum_{i=1}^{n-1}(b_{i}-d_{i})^{2}-2a_{0}\sum_{i=1}^{n-1}(b_{i}-d_{i})+n a_{0}^{2}$. It can be proven that values of polynomial in roots of unity are eigenvalues of matrix of linear system thus cyclic shifts are linearly independent iff there is such mod which has root of unity of degree $n$ and values of polynomial in all such roots doesn't equal zero. If it's true for polynomial in field of real numbers there will be only finite number of mods in which this may not be true (it only true if $\operatorname{gcd}$ of polynomial and $x^{n} - 1$ isn't equal $1$ in such mod).
|
[
"fft",
"math"
] | 3,300
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.