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
747
B
Mammoth's Genome Decoding
The process of mammoth's genome decoding in Berland comes to its end! One of the few remaining tasks is to restore unrecognized nucleotides in a found chain $s$. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, $s$ is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'. It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal. Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.
Let $n$ is the length of the given string. The number of each letter in the resulting string must be equals to $n / 4$. If $n mod 4$ does not equal to 0 - there is no solution. If some letter meets in the given string more than $n / 4$ times - there is no solution. After that we always can build the answer. We need to iterate through the given string and change question symbols on any letter, which meets in the current string less than $n / 4$ times.
[ "implementation", "strings" ]
900
null
747
C
Servers
There are $n$ servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from $1$ to $n$. It is known that during the day $q$ tasks will come, the $i$-th of them is characterized with three integers: $t_{i}$ — the moment in seconds in which the task will come, $k_{i}$ — the number of servers needed to perform it, and $d_{i}$ — the time needed to perform this task in seconds. All $t_{i}$ are distinct. To perform the $i$-th task you need $k_{i}$ servers which are unoccupied in the second $t_{i}$. After the servers begin to perform the task, each of them will be busy over the next $d_{i}$ seconds. Thus, they will be busy in seconds $t_{i}, t_{i} + 1, ..., t_{i} + d_{i} - 1$. For performing the task, $k_{i}$ servers with the smallest ids will be chosen from all the unoccupied servers. If in the second $t_{i}$ there are not enough unoccupied servers, the task is ignored. Write the program that determines which tasks will be performed and which will be ignored.
The given constraints allow to simply modulate described process. Let's use array $server$, where $server[i]$ is equals to the time when $i$-th server will become free. Than for each query let's find the number of servers which free in moment when this query came. We can do it in $O(n)$, where $n$ is the number of servers. If the number of free servers is less than $k$ we need to print -1. In the other case, we can iterate through all free servers and find the sum of $k$ servers with smallest numbers and store in array $server$ for this servers time of release equals to $t + d$.
[ "implementation" ]
1,300
null
747
D
Winter Is Coming
The winter in Berland lasts $n$ days. For each day we know the forecast for the average air temperature that day. Vasya has a new set of winter tires which allows him to drive safely no more than $k$ days at any average air temperature. After $k$ days of using it (regardless of the temperature of these days) the set of winter tires wears down and cannot be used more. It is not necessary that these $k$ days form a continuous segment of days. Before the first winter day Vasya still uses \textbf{summer tires}. It is possible to drive safely on summer tires any number of days when the average air temperature is \textbf{non-negative}. It is impossible to drive on summer tires at days when the average air temperature is negative. Vasya can change summer tires to winter tires and vice versa at the beginning of any day. Find the minimum number of times Vasya needs to change summer tires to winter tires and vice versa to drive safely during the winter. At the end of the winter the car can be with any set of tires.
At first let's process the case when there is no solution - when the number of days with negative temperature $cnt$ more than $k$. Now we need to subtract from $k$ the number of days $cnt$. If we will use winter rubber only in days with negative temperature we will get the maximum value of answer: it is the number of segments where all days have negative temperature multiply by 2. Between the segments with negative temperatures there are segments which we ride on the summer rubber. Let's put in $set$ the lengths of this segments (not include the segments with first and last days if they have non-negative temperatures, this cases we need to process separately from the main solution). After that we need to delete from the $set$ smallest lengths of segments one by one, decrease $k$ on this value and decrease answer on 2. We can make it until $k > = 0$ and the $set$ is not empty. Now we only need to check if we can ride on winter rubber the last segment of days with non-negative temperature. If it is possible we need decrease the answer on 1, in the other case the answer remains unchanged.
[ "dp", "greedy", "sortings" ]
1,800
null
747
E
Comments
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed. Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment. When Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format: - at first, the text of the comment is written; - after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments); - after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm). All elements in this format are separated by single comma. Similarly, the comments of the first level are separated by comma.For example, if the comments look like: then the first comment is written as "hello,2,ok,0,bye,0", the second is written as "test,0", the third comment is written as "one,1,two,2,a,0,b,0". The whole comments feed is written as: "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0". For a given comments feed in the format specified above print the comments in a different format: - at first, print a integer $d$ — the maximum depth of nesting comments; - after that print $d$ lines, the $i$-th of them corresponds to nesting level $i$; - for the $i$-th row print comments of nesting level $i$ in the order of their appearance in the Policarp's comments feed, separated by space.
Let $pos$ is a global variable equals to the current position in the given string. To solve we can use recursive function $rec(lvl, cnt)$, means that in the current moment we are on the level of replies $lvl$ and there is $cnt$ comments on this level. Than we need iterate by $i$ from 1 to $cnt$ and on each iteration we will make the following: read from the position $pos$ comment, add this comment to the answer for level $lvl$ and than read the number of it children $nxt_{cnt}$. After that $pos$ will in the beginning of the first child of this comment and we need to run $rec(lvl + 1, nxt_{cnt})$. For the higher level we can put in $cnt$ big number and return from the function $rec$ in the moment when $pos$ will become equals to the length of the given string.
[ "dfs and similar", "expression parsing", "implementation", "strings" ]
1,700
null
747
F
Igor and Interesting Numbers
Igor likes hexadecimal notation and considers \textbf{positive} integer in the hexadecimal notation interesting if each digit and each letter in it appears no more than $t$ times. For example, if $t = 3$, then integers 13a13322, aaa, abcdef0123456789 are interesting, but numbers aaaa, abababab and 1000000 are not interesting. Your task is to find the $k$-th smallest interesting for Igor integer in the hexadecimal notation. The integer should not contain leading zeros.
Let's use dynamic programming and $dp[i][j]$ - the number of valid numbers with length $i$ and maximal digit in this numbers is $j$. Let iterate by $n_{j}$ from $j + 1$ and brute $len$ (how many times we will take digit $n_{j}$). Than new length $n_{i} - i + len$, number will ends to $n_{j}$ repeated $len$ times. Then $dp[ni][nj] = dp[i][j] * (n_{i}! / (i! * len!))$. After that we need to find the length of the answer number $lenAns$. Let iterate by $lenAns$ from 1 and calculate the number of numbers with length $lenAns$. It can be done with help of $dp$ (brute maximum digit and calculate $dp$ for $len - 1$).
[ "brute force", "combinatorics", "dp", "math" ]
2,500
null
748
A
Santa Claus and a Place in a Class
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are $n$ lanes of $m$ desks each, and there are two working places at each of the desks. The lanes are numbered from $1$ to $n$ from the left to the right, the desks in a lane are numbered from $1$ to $m$ starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture). The organizers numbered all the working places from $1$ to $2nm$. The places are numbered by lanes (i. e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i. e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right. \begin{center} {\small The picture illustrates the first and the second samples.} \end{center} Santa Clause knows that his place has number $k$. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right!
It can be easily seen that the side on which Santa should sit depends only on the parity of $k$, while the number of desk and the number of lane depend only on a value $p=\lfloor{\frac{k-1}{2}}\rfloor$. We can see that in such numeration the number of lane equals $\left|{\frac{p}{m}}\right|+1$, while the number of desk equals $p\bmod m+1$.
[ "implementation", "math" ]
800
null
748
B
Santa Claus and Keyboard Check
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard. You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs \textbf{at most once}.
Denote the two strings from the input by $s$ and $t$. It's enough to find all pairs of distinct $s_{i}$ and $t_{i}$ and then do the following: Ensure that each symbol is in no more than one different pair, Ensure that if symbol $c$ is in a pair with another symbol $d$, then each occurrence of $c$ in $s$ on the $i$-th place takes place iff $t_{i} = d$, and vice versa. If at least one of these conditions fails, there is no answer, otherwise, it's enough to print the obtained pairs.
[ "implementation", "strings" ]
1,500
null
748
C
Santa Claus and Robot
Santa Claus has Robot which lives on the infinite grid and can move \textbf{along its lines}. He can also, having a sequence of $m$ points $p_{1}, p_{2}, ..., p_{m}$ with integer coordinates, do the following: denote its initial location by $p_{0}$. First, the robot will move from $p_{0}$ to $p_{1}$ along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches $p_{1}$, it'll move to $p_{2}$, again, choosing one of the shortest ways, then to $p_{3}$, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order. While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.
Solution #1: denote by $dp_{i}$ the least possible number of points if the robot passed only $i$ unit segments, and we assume that $dp_{0} = 0$. Thus, the answer to the problem is $dp_{n}$. It's clear that $dp_{k + 1} \ge dp_{k}$ for every $k$, so for every $i \le n$ one can obtain that $dp_{i} = dp_{j} + 1$, where $j$ is the minimal of such indices that $s[j + 1... i]$ can be a path from one point to another. That means two constraints: either $s[j + 1... i]$ doesn't contain any L, or it doesn't contain any R; either $s[j + 1... i]$ doesn't contain any U, or it doesn't contain any D. This fact is offered to the reader. Such $j$ can be found in $O(1)$ if we iterate over all $i$-s from $1$ to $n$ and keep the last occurence of L, R, U and D. So one can, storing these occurences and $dp$ itself, implement the algorithm above and pass each test for $O(n)$ time. Solution #2: since we know the way to determine whether the path is valid or not (from the first solution), let's find the longest prefix of $s$ and say that that's a path to the first point of the required collection. Then we find the longest prefix of the remaining string and state that this is the shortest path from $p_{1}$ to $p_{2}$, and so on. This greedy algorithm works (obviously, in linear time), since the first solution is in fact the same greedy algorithm applied to the reversed string.
[ "constructive algorithms", "math" ]
1,400
null
748
D
Santa Claus and a Palindrome
Santa Claus likes palindromes very much. There was his birthday recently. $k$ of his friends came to him to congratulate him, and each of them presented to him a string $s_{i}$ having the same length $n$. We denote the beauty of the $i$-th string by $a_{i}$. It can happen that $a_{i}$ is negative — that means that Santa doesn't find this string beautiful at all. Santa Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have \textbf{the same length} $n$. Recall that a palindrome is a string that doesn't change after one reverses it. Since the empty string is a palindrome too, the answer can't be negative. Even if all $a_{i}$'s are negative, Santa can obtain the empty string.
Imagine a palindrome split into substrings of equal size (say, $n$). Here is how it may look like: ABC DEF XYX FED CBA We may notice a regular structure: each block, except the middle one, has its pair, which is the same string, but reversed. Here, the first block (ABC) is paired with the last (CBA), the second - with the first-but-last. For now, let's assume that we take an even number of strings, so each string has its pair. Let's split given strings into groups; strings $S$ and $rev(S)$ belong to one group. Clearly, if $S$ is not a palindrome, we must make a pair with the string $S$ with maximum value and the string $rev(S)$ with maximum value, until both strings exist and the sum of their values is nonnegative. If $S$ is a palindrome, we will take two its occurrences with maximum value at a time (of course, again, if there are still at least two occurrences and the sum of values is nonnegative). The trickiest part is the central block. Clearly, only the palindromic strings may be at the central block. However, there may be many of them, and we should select the one which gives the maximum value overall. There are several cases. Consider the point when you've taken the last pair from the list of $S$-s and stopped. If the value of the next element is nonnegative (say, $x$), we may simply take it and say that $x$ is our possible score for $S$ being in the center. We wouldn't make a valuable pair of it anyway. Otherwise we need to split the last taken pair. Denote the values of last taken strings as $a$ and $b$ ($a \ge b$). Note that $b < 0$, because otherwise it makes no sense to use $a$ separately. If we take a pair, we get score $a + b$. If we take just the first element, we get score $a$. So, in this case our possible score is $- b$ (while $a + b$ is already added to the main answer!) Now, the central string will be the one with the maximum possible score, and its value should be added to the answer.
[ "constructive algorithms", "data structures", "greedy" ]
2,100
null
748
E
Santa Claus and Tangerines
Santa Claus has $n$ tangerines, and the $i$-th of them consists of exactly $a_{i}$ slices. Santa Claus came to a school which has $k$ pupils. Santa decided to treat them with tangerines. However, there can be too few tangerines to present at least one tangerine to each pupil. So Santa decided to divide tangerines into parts so that no one will be offended. In order to do this, he can divide a tangerine or any existing part into two smaller equal parts. If the number of slices in the part he wants to split is odd, then one of the resulting parts will have one slice more than the other. It's forbidden to divide a part consisting of only one slice. \textbf{Santa Claus wants to present to everyone either a whole tangerine or exactly one part of it} (that also means that everyone must get a positive number of slices). One or several tangerines or their parts may stay with Santa. Let $b_{i}$ be the number of slices the $i$-th pupil has in the end. Let Santa's joy be the minimum among all $b_{i}$'s. Your task is to find the maximum possible joy Santa can have after he treats everyone with tangerines (or their parts).
It is obvious that if the total number of slices is less than $k$, then the answer is $- 1$. Otherwise it's at least $1$. Let's find the answer in this case. Let's divide tangerines and parts in halves one by one in order to find the best answer. It's easy to see that it makes no sense to divide a part of size $x$ if there is an undivided part of size $y > x$. So we are going to proceed dividing the largest part on each step. Let's also maintain current answer, i. e. the size of the $k$-th biggest current part, and a set of parts which we are going to present to the pupils. When we divide the largest part, there are two possible cases: If the size of any part is less then the current answer, then it's obvious that the answer will never be greater if we proceed further, so we can stop the process. If the sizes of both parts are greater than or equal to the current answer, then we should delete the initial part and add the resulting parts to those we present to the pupils in the current answer, and then delete the smallest part from the set making it of size $k$ again. We can see that in the second case the answer never decreases so we can just proceed until the first case happens. To emulate this process in a fast way, we can keep an array from $1$ to $A$, where $A = 10^{7}$ is the maximum possible number of slices in a part, where each cell contain the current number of parts of that size. Thus, we can maintain two pointers: one to the current answer and one to the current maximum size, so the whole process can be done in $O(n)$. The overall complexity is $O(n + A)$.
[ "binary search", "data structures", "greedy", "two pointers" ]
2,100
null
748
F
Santa Clauses and a Soccer Championship
The country Treeland consists of $n$ cities connected with $n - 1$ bidirectional roads in such a way that it's possible to reach every city starting from any other city using these roads. There will be a soccer championship next year, and all participants are Santa Clauses. There are exactly $2k$ teams from $2k$ different cities. During the first stage all teams are divided into $k$ pairs. Teams of each pair play two games against each other: one in the hometown of the first team, and the other in the hometown of the other team. Thus, each of the $2k$ cities holds exactly one soccer game. However, it's not decided yet how to divide teams into pairs. It's also necessary to choose several cities to settle players in. Organizers tend to use \textbf{as few cities as possible} to settle the teams. Nobody wants to travel too much during the championship, so if a team plays in cities $u$ and $v$, it wants to live in one of the cities on the shortest path between $u$ and $v$ (maybe, in $u$ or in $v$). There is another constraint also: the teams from one pair must live in the same city. Summarizing, the organizers want to divide $2k$ teams into pairs and settle them in the minimum possible number of cities $m$ in such a way that teams from each pair live in the same city which lies between their hometowns.
Firstly, let's prove that there exists a vertex $v$ in the tree such that if we make it a root, all subtrees of its neighbours (which does not contain $v$) contain no more than $k$ vertices in which some games are played (we call these vertices chosen further). We root the tree in some vertex $root$ and denote $f(u)$ the number of chosen vertices in the subtree of $u$. Now we need to prove that there exists vertex $v$ such that $f(v) \ge k$ (then no more than $k$ vertices outside subtree of $v$ are chosen), but for all children $to$ of $v f(to) \le k$ holds. Assume there is no such vertex $v$, then each vertex $u$ such that $f(u) > k$ has some child $u'$ such that $f(u') > k$. So we can build a sequence $u_{0}, u_{1}, ...$ such that $u_{0} = root, u_{i + 1}$ is a child of $u_{i}$ and $f(u_{i}) > k$. But obviously, at some point we will go to the leaf, which clearly has $f(u) \le 1$. This leads us to a contradiction. This argument also gives us an easy way to find the desired vertex $v$: just calculate $f(u)$ for all subtrees of the rooted tree and then go from the root down, always going to the child with $f(u_{i + 1}) > k$, at some point we will find that such vertex does not exist - then current vertex is the one we were looking for. We claim that the answer to the original problem is always 1, i.e. we can always choose one vertex, where all teams will live. Consider vertex $v$ having $f(to) \le k$ for all its children. We create a list of all chosen vertices, firstly we write all chosen vertices of the first child's subtree of $v$, then all chosen vertices of the second child's subtree, and so on. In the end, if $v$ is chosen too, we add it to the end of the list. Now we have a list of $2k$ vertices $a$. Let's create $k$ pairs of the form $(a_{i}, a_{i + k})$. Since for all children of $v f(to) \le k$ holds, the vertices which numbers in the list differ by $k$ can not belong to the same subtrees, and thus the shortest path between $a_{i}$ and $a_{i + k}$ passes through the vertex $v$.
[ "constructive algorithms", "dfs and similar", "graphs", "trees" ]
2,300
null
749
A
Bachgold Problem
Bachgold problem is very easy to formulate. Given a positive integer $n$ represent it as a sum of \textbf{maximum possible} number of prime numbers. One can prove that such representation exists for any integer greater than $1$. Recall that integer $k$ is called \underline{prime} if it is greater than $1$ and has exactly two positive integer divisors — $1$ and $k$.
We need represent integer number $N$ ($1 < N$) as a sum of maximum possible number of prime numbers, they don't have to be different. If $N$ is even number, we can represent it as sum of only $2$ - minimal prime number. It is minimal prime number, so number of primes in sum is maximal in this case. If $N$ is odd number, we can use representing of $N - 1$ as sum with only $2$ and replace last summand from $2$ to $3$. Using of any prime $P > 3$ as summand is not optimal, because it can be replaced by more than one $2$ and $3$.
[ "greedy", "implementation", "math", "number theory" ]
800
null
749
B
Parallelogram is Back
Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwise traversal. Alex had very nice test for this problem, but is somehow happened that the last line of the input was lost and now he has only three out of four points of the original parallelogram. He remembers that test was so good that he asks you to restore it given only these three points.
Denote the input points as $A$, $B$, $C$, and the point we need to find as $D$. Consider the case when the segments $AD$ and $BC$ are the diagonals of parallelogram. Vector AD is equal to the sum of two vectors AB + BD = AC + CD. As in the parallelogram the opposite sides are equal and parallel, BD = AC, AB = CD, and we can conclude that AD = AB + AC. So, the coordinates of the point D can be calculated as $A$ + AB + AC = ($A_{x} + B_{x} - A_{x} + C_{x} - A_{x}, A_{y} + B_{y} - A_{y} + C_{y} - A_{y}$) = ($B_{x} + C_{x} - A_{x}, B_{y} + C_{y} - A_{y}$). The cases where the diagonals are $BD$ and $AC$, $CD$ and $AB$ are processed in the same way. Prove that all three given points are different. Let's suppose it's wrong. Without losing of generality suppose that the points got in cases $AD$ and $BD$ are equal. Consider the system of two equations for the equality of these points: $B_{x} + C_{x} - A_{x} = A_{x} + C_{x} - B_{x}$ $B_{y} + C_{y} - A_{y} = A_{y} + C_{y} - B_{y}$ We can see that in can be simplified as $A_{x} = B_{x}$ $A_{y} = B_{y}$ And we got a contradiction, as all the points $A$, $B$, $C$ are distinct.
[ "brute force", "constructive algorithms", "geometry" ]
1,200
null
749
C
Voting
There are $n$ employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote. Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated: - Each of $n$ employees makes a statement. They make statements one by one starting from employees $1$ and finishing with employee $n$. If at the moment when it's time for the $i$-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting). - When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end. - When all employees are done with their statements, the procedure repeats: again, each employees starting from $1$ and finishing with $n$ who are still eligible to vote make their statements. - The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction. You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
We will emulate the process with two queues. Let's store in the first queue the moments of time when D-people will vote, and in the second queue - the moments of time of R-people. For every man where will be only one element in the queue. Now compare the first elements in the queues. The man whose moment of time is less votes first. It's obvious that it's always profitable to vote against the first opponent. So we will remove the first element from the opponent's queue, and move ourselves to the back of our queue, increasing the current time by $n$ - next time this man will vote after $n$ turns. When one of the queues becomes empty, the corresponding party loses.
[ "greedy", "implementation", "two pointers" ]
1,500
null
749
D
Leaving Auction
There are $n$ people taking part in auction today. The rules of auction are classical. There were $n$ bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all. Each bid is define by two integers $(a_{i}, b_{i})$, where $a_{i}$ is the index of the person, who made this bid and $b_{i}$ is its size. Bids are given in chronological order, meaning $b_{i} < b_{i + 1}$ for all $i < n$. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. $a_{i} ≠ a_{i + 1}$ for all $i < n$. Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added. Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples. You have several questions in your mind, compute the answer for each of them.
For every man at the auction we will save two values: his maximum bid and the list of all his bids. Then save all men in the set sorted by the maximal bid. Now, when the query comes, we will remove from the set all men who left the auction, then answer the query, and then add the men back. The total number of deletions and insertions will not exceed 200000. How to answer the query. Now our set contains only men who has not left. If the set is empty, the answer is 0 0. Otherwise, the maximal man in the set is the winner. Now we have to determine the winning bid. Let's look at the second maximal man in the set. If it doesn't exist, the winner takes part solo and wins with his minimal bid. Otherwise he should bid the minimal value that is greater than the maximal bid of the second man in the set. This is where we need a list of bids of the first maximal man. We can apply binary search and find the maximal bid of the second man there.
[ "binary search", "data structures" ]
2,000
null
749
E
Inversions After Shuffle
You are given a permutation of integers from $1$ to $n$. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: - Pick a random segment (continuous subsequence) from $l$ to $r$. All $\textstyle{\frac{n(n+1)}{2}}$ segments are equiprobable. - Let $k = r - l + 1$, i.e. the length of the chosen segment. Pick a random permutation of integers from $1$ to $k$, $p_{1}, p_{2}, ..., p_{k}$. All $k!$ permutation are equiprobable. - This permutation is applied to elements of the chosen segment, i.e. permutation $a_{1}, a_{2}, ..., a_{l - 1}, a_{l}, a_{l + 1}, ..., a_{r - 1}, a_{r}, a_{r + 1}, ..., a_{n}$ is transformed to $a_{1}, a_{2}, ..., a_{l - 1}, a_{l - 1 + p1}, a_{l - 1 + p2}, ..., a_{l - 1 + pk - 1}, a_{l - 1 + pk}, a_{r + 1}, ..., a_{n}$. \underline{Inversion} if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs $(i, j)$ such that $i < j$ and $a_{i} > a_{j}$. Find the expected number of inversions after we apply exactly one operation mentioned above.
Lets calculate all available segments count - $\frac{l e n s(l e n+1)}{2}$. It will be a denominator of answer fraction. Also, necessary to understand, that expected value of inversion count in shuffled permutation with length len equal $\frac{l e n s(l e n-1)}{4}$ (It can be prooved by fact, that for each permutation there are mirrored permutation (or biection $i - > n - i + 1$) and sum of inversion count his permutations are equal $\frac{I_{\mathrm{e}^{-}\hbar\left(I e n-1\right)}}{2}$ inversions). Next, we will find expected value of difference between expected value of inversion count after operation and inversion count in the source array. And add it to the inversion count in the source array. Naive solution: For every segment we will calculate the count of inversions in it, and also the expected value of the inversion count in it after shuffle. Take the difference and divide by a denominator. Sum these values for all segments. This solution has quadratic asympthotics, try to improve it. Optimized solution: We will go through the permutation from right to left and for each position count the sum of inversions in the initial permutation for all segments that start in the current position (denote that the largest segment which ends at the position $n$ has the length $len$), also we will maintain the sum of expected values of the inversion counts on the segments of lengths $1..len$. Knowing these two numbers, increase the answer by their difference divided by the denominator. To calculate the first value we will use the data structure that can get the sum of numbers on the prefix and modify the value at the single position (e.g. Fenwick tree). For the position $i$ we need to know how many numbers are less than $a_{i}$, and every number should be taken $t$ times, where $t$ is number of segments where it is contained. Suppose we have calculated answers for some suffix and are now standing at the position $i$. For every position to the left it will be added $n - i + 1$ times (the number of positions $j > = i$ as the candidates for the right bound, in 1-indexation). Perform fenwick add(a[i], n - i + 1).
[ "data structures", "probabilities" ]
2,400
null
750
A
New Year and Hurry
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be $n$ problems, sorted by difficulty, i.e. problem $1$ is the easiest and problem $n$ is the hardest. Limak knows it will take him $5·i$ minutes to solve the $i$-th problem. Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs $k$ minutes to get there from his house, where he will participate in the contest first. How many problems can Limak solve if he wants to make it to the party?
Do you see what is produced by the following piece of code? We iterate over problems (a variable i denotes the index of problem) and in a variable total we store the total time needed to solve them. The code above would print numbers $5, 15, 30, 50, ...$ - the $i$-th of these numbers is the number of minutes the hero would spend to solve easiest $i$ problems. Inside the loop you should also check if there is enough time to make it to the party, i.e. check if total + k <= 240.
[ "binary search", "brute force", "implementation", "math" ]
800
null
750
B
New Year and North Pole
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly $40 000$ kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly $20 000$ kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of $n$ parts. In the $i$-th part of his journey, Limak should move $t_{i}$ kilometers in the direction represented by a string $dir_{i}$ that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: - If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. - If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. - The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line.
Our goal is to simulate Limak's journey and to check if he doesn't make any forbidden moves. To track his position, it's enough to store one variable denoting his current distance from the North Pole. To solve this problem, you should implement checking three conditions given in the statement. Updating dist_from_north variable is an easy part. Moving $t_{i}$ kilometers to the North increases the distance from the North Pole by $t_{i}$, while moving South decreases that distance by $t_{i}$. Moving to the West or East doesn't affect the distance from Poles, though you should still check if it doesn't happen when Limak is on one of two Poles - you must print "NO" in this case. Let's proceed to checking the three conditions. First, Limak can't move further to the North if he is already on the North Pole "at any moment of time (before any of the instructions or while performing one of them)". So you should print "NO" if direction == "North" and either dist_from_north == 0 or dist_from_north < t[i]. The latter case happens e.g. if Limak is $150$ kilometers from the North Pole and is supposed to move $170$ kilometers to the North - after $150$ kilometers he would reach the North Pole and couldn't move further to the North. In the intended solution below you will see an alternative implementation: after updating the value of dist_from_north we can check if dist_from_north < 0 - it would mean that Limak tried to move North from the North Pole. Also, you should print "NO" if dist_from_north == 0 (i.e. Limak is on the North Pole) and the direction is West or East. You should deal with the South Pole case in a similar way. Limak is on the South Pole when dist_from_north == M. Finally, you must check if Limak finished on the North Pole, i.e. dist_from_north == 0. There were two common doubts about this problem: 1) "Limak is allowed to move $40 000$ kilometers to the South from the North Pole and will be again on the North Pole." 2) "Moving West/East may change the latitude (equivalently: the distance from Poles) and this problem is hard 3d geometry problem." Both doubts make sense because they come from misinterpreting a problem as: Limak looks in the direction represented by the given string (e.g. to the North) and just goes straight in that direction (maybe after some time he will start moving to the South but he doesn't care about it). What organizers meant is that Limak should be directed in the given direction at any moment of time, i.e. he should continuously move in that direction. It's a sad thing that many participants struggled with that. I should have written the statement better and I'm sorry about it.
[ "geometry", "implementation" ]
1,300
null
750
C
New Year and Rating
Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating $1900$ or higher. Those with rating $1899$ or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero. Limak competed in $n$ contests in the year 2016. He remembers that in the $i$-th contest he competed in the division $d_{i}$ (i.e. he belonged to this division \textbf{just before} the start of this contest) and his rating changed by $c_{i}$ \textbf{just after the contest}. Note that negative $c_{i}$ denotes the loss of rating. What is the maximum possible rating Limak can have right now, after all $n$ contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible".
We don't know the initial or final rating but we can use the given rating changes to draw a plot of function representing Limak's rating. For each contest we also know in which division Limak was. Red and blue points denote contests in div1 and div2. Note that we still don't know exact rating at any moment. Let's say that a border is a horizontal line at height $1900$. Points above the border and exactly on it should be red, while points below should be blue. Fixing the placement of the border will give us the answer (because then we will know height of all points). Let's find the highest blue point and the lowest red point - the border can lie anywhere between them, i.e. anywhere between these two horizontal lines: Small detail: the border can lie exactly on the upper line (because rating $1900$ belongs to div1) but it can't lie exactly on the lower line (because $1900$ doesn't belong to div2). The last step is to decide where exactly it's best to put the border. The answer will be $1900 + d$ where $d$ is the difference between the height of the border and the height of the last point (representing the last contest), so we should place the border as low as possible: just over the lower of two horizontal lines we found. It means that the highest blue point should be at height $1899$. There is an alternative explanation. If Limak never had rating exactly $1899$, we could increase his rating at the beginning by $1$ (thus moving up the whole plot of the function by $1$) and everything would still be fine, while the answer increased. To implement this solution, you should find prefix sums of rating changes (what represents the height of points on drawings above, for a moment assuming that the first point has height $0$) and compute two values: the smallest prefix sum ending in a div1 contest and the greatest prefix sum ending in a div2 contest. If the first value is less than or equal to the second value, you should print "Impossible" - it means that the highest blue point isn't lower that the lowest red point. If all contests were in div1, we should print "Infinity" because there is no upper limit for Limak's rating at any time (and there is no upper limit for the placement of the border). Otherwise we say that the highest blue point (a div2 contest with the greatest prefix sum) is a contest when Limak had rating $1899$ and we easily compute the final rating.
[ "binary search", "greedy", "math" ]
1,600
null
750
D
New Year and Fireworks
One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth $n$ and a duration for each level of recursion $t_{1}, t_{2}, ..., t_{n}$. Once Limak launches the firework in some cell, the firework starts moving upward. After covering $t_{1}$ cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by $45$ degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering $t_{2}$ cells, splitting into two parts moving in directions again changed by $45$ degrees. The process continues till the $n$-th level of recursion, when all $2^{n - 1}$ existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time — it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells?
A trivial $O(2^{n})$ solution is to simulate the whole process and mark visited cells. Thanks to a low constraint for $t_{i}$, a backtrack with memoization has much better complexity. Let's understand the reason. Parts of the firework move by $t_{i}$ in the $i$-th level of recursion so they can't reach cells further than $\textstyle\sum t_{i}$ from the starting cell. That sum can't exceed $n \cdot max_t = 150$. We can't visit cells with bigger coordinates so there are only $O((n \cdot max_t)^{2})$ cells we can visit. As usually in backtracks with memoization, for every state we can do computations only once - let's think what that "state" is. We can't say that a state is defined by the current cell only, because maybe before we visited it going in a different direction and now we would reach new cells. It also isn't correct to say that we can skip further simulation if we've already been in this cell going in the same direction, because maybe it was the different level of recursion (so now next step will in in a different direction, what can allow us to visit new cells). It turns out that a state must be defined by four values: two coordinates, a direction and a level of recursion (there are $8$ possible directions). One way to implement this approach is to create set<vector<int>> visitedStates where each vector contains four values that represent a state. The complexity is $\begin{array}{c}{{\O((n\cdot m u x\ }\ t)^{2}\cdot\S\circ n\cdot\bigcup_{\mathrm{GP}}n)}\end{array}$ what is enough to get AC. It isn't hard to get rid of the logarithm factor what you can see in the last code below. If implementing the simulation part is hard for you, see the first code below with too slow exponential solution. It shows an easy way to deal with $8$ directions and changing the direction by $45$ degrees - you can spend a moment to hardcode changes of $x$ and $y$ for each direction and clockwise or counter-clockwise order and then keep an integer variable and change its value by $1$ modulo $8$. You can add memoization to this slow code yourself and try to get AC.
[ "brute force", "data structures", "dfs and similar", "dp", "implementation" ]
1,900
null
750
E
New Year and Old Subsequence
A string $t$ is called nice if a string "2017" occurs in $t$ as a \textbf{subsequence} but a string "2016" doesn't occur in $t$ as a \textbf{subsequence}. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice. The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is $ - 1$. Limak has a string $s$ of length $n$, with characters indexed $1$ through $n$. He asks you $q$ queries. In the $i$-th query you should compute and print the ugliness of a \textbf{substring} (continuous subsequence) of $s$ starting at the index $a_{i}$ and ending at the index $b_{i}$ (inclusive).
It's often helpful to think about an algorithm to solve some easier problem. To check if a string has a subsequence "2017", we can find the find the first '2', then to the right from that place find the first '0', then first '1', then first '7'. If in some of these $4$ steps we can't find the needed digit on the right, the string doesn't have "2017" as a subsequence. To additionally check if there is a subsequence "2016", after finding '1' (before finding '7') we should check if there is any '6' on the right. Let's refer to this algorithm as Algo. It turns out that the problem can be solved with a segment tree (btw. the solution will also allow for queries changing some digits). The difficulty is to choose what we want to store in its nodes. Let's first use the Algo to answer simpler queries: "for the given segment check if it's nice". There is only one thing that matters for segments represented by nodes. For a segment we want to know for every prefix of "2017" (e.g. for "20"): assuming that the Algo already got this prefix as a subsequence, what is the prefix we have after the Algo processes this segment. Let's see an example.
[ "data structures", "divide and conquer", "dp", "matrices" ]
2,600
null
750
F
New Year and Finding Roots
\textbf{This is an interactive problem. In the interaction section below you will find the information about flushing the output.} The New Year tree of height $h$ is a perfect binary tree with vertices numbered $1$ through $2^{h} - 1$ in some order. In this problem we assume that $h$ is at least $2$. The drawing below shows one example New Year tree of height $3$: Polar bears love decorating the New Year tree and Limak is no exception. To decorate the tree, he must first find its root, i.e. a vertex with exactly two neighbours (assuming that $h ≥ 2$). It won't be easy because Limak is a little bear and he doesn't even see the whole tree. Can you help him? There are $t$ testcases. In each testcase, you should first read $h$ from the input. Then you can ask at most $16$ questions of format "? x" (without quotes), where $x$ is an integer between $1$ and $2^{h} - 1$, inclusive. As a reply you will get the list of neighbours of vertex $x$ (more details in the "Interaction" section below). For example, for a tree on the drawing above after asking "? 1" you would get a response with $3$ neighbours: $4$, $5$ and $7$. Your goal is to find the index of the root $y$ and print it in the format "! y". You will be able to read $h$ for a next testcase only after printing the answer in a previous testcase and flushing the output. Each tree is fixed from the beginning and it doesn't change during your questions.
The goal is to find a vertex with exactly two neighbours - this will be the root. Also, let's notice that for a leaf we would get a list of exactly one neighbour. So we will know if we asked about the root or a leaf. The solution is deterministic. Any randomized solution would likely fail - there are 500 test cases per test file, and usually there are 30-100 tests for a problem, so you must pass around 25,000 test cases. That's bad if you ask too many queries even with a small probability. You can ask about a vertex (say, $A$), then ask about one of its neighbours (say, $B$), then ask about one of neighbours of $B$, and so on, until you get a leaf. The sequence of visited vertices $(A, B, ...)$ is a path in the tree. How can this path look like in the whole tree? Do we know the distance from $A$ to the root of the tree? To be able to say where exactly the path is in the tree, we should do one extra step. From the initial vertex $A$, choose some other neighbour $B_{2}$ and go from there again until you get a leaf. Now we have path between two leaves. The middle vertex on the path is the LCA and we know its distance from the leaves, so we also know its distance from the root. In this case, vertex $B_{1}$ turned out to be the middle of the path: Where should you go now to find the root? Let's call that "middle vertex of the path" as $P$. We asked a query about $P$ already, so we know its neighbours. Two neighbours are on the path, and the third one (the one not yet asked/visited) must be the parent of $P$. Let's go to that parent (so, ask a query about it) and then again continue until you find a leaf. Where should we go now? We know that we went from $P$ to its parent, then maybe again to a parent, but eventually we started going down. If we know the numbers of steps it took us to get to a leaf (so, the length of the blue path), we can calculate the number of steps we went up. So we know what is the current LCA of asked/visited vertices and we can go up from there. Alternatively, we can notice that we have a new longer path between two leaves (marked green below). Let $P_{2}$ be the midddle of the path. $P_{2}$ must be the vertex closest to the root (so, LCA of everything we asked/visited so far). We repeat the process, until we get the root of the tree (so, a vertex with two neighbours). What is the number of queries we can ask up to that moment? In the worst case, we start from $P_{0}$ being a leaf, and then the $i$-th new path will have $i + 1$ vertices. The following drawing shows the visited (asked) vertices in the worst case for $h = 5$. The not-yet-visited neighbour of $P_{3}$ must be the root. For height $h$, we can ask up to $1 + 2 + 3 + ... + (h - 1)$ queries, which is $O(\log^{2}n)$. The limit from the statement is $16$, while for $h = 7$ we get up to $21$ queries. We are close to the solution. Do you see how to get rid of a few queries? If the parent of a current $P_{i}$ is within distance $2$ from the root, we can just check all vertices within distance $2$ (red vertices on the drawing) and we will find the root there. The number of queries needed now is $1 + 2 + 3 + 4 + (1 + 6) = 17$, where "1+6" represents the "PARENT" and the red vertices. We exceed the limit just by $1$ now. How to get rid of one query? If you already asked about all red vertices but one, the last one must be the answer. We don't have to ask a query about it. That's it, we use at most $16$ queries.
[ "constructive algorithms", "implementation", "interactive", "trees" ]
2,800
null
750
G
New Year and Binary Tree Paths
The New Year tree is an infinite perfect binary tree rooted in the node $1$. Each node $v$ has two children: nodes indexed $(2·v)$ and $(2·v + 1)$. Polar bears love decorating the New Year tree and Limak is no exception. As he is only a little bear, he was told to decorate only one simple path between some pair of nodes. Though he was given an opportunity to pick the pair himself! Now he wants to know the number of unordered pairs of indices $(u, v)$ ($u ≤ v$), such that the sum of indices of all nodes along the simple path between $u$ and $v$ (including endpoints) is equal to $s$. Can you help him and count this value?
Iterate over $L$ and $R$ - the length of sides of a path. A "side" is a part from LCA (the highest point of a path) to one of the ends of a path. For fixed LCA and length of sides, let the "minimal" path denote a path with the minimum possible sum of values. In each of the sides, this path goes to the left child all the time: If the LCA is $x$, the smallest possible sum of vertices on the left side of the minimal path has the sum of vertices: $S_{L} = 2 \cdot x + 4 \cdot x + ... + 2^{L} \cdot x = (2^{L + 1} - 2) \cdot x$ We can find a similar formula for the minimum possible sum of the right side $S_{R}$. For fixed $L, R, x$, the total sum of any path (also counting LCA itself) is at least: $S_{L} + LCA + S_{R} = (2^{L + 1} - 2) \cdot x + x + ((2^{R + 1} - 2) \cdot x + 2^{R} - 1)$ From this, with binary search or just a division, we can compute the largest $x$ where this formula doesn't exceed the given $s$. This is the only possible value of LCA. Larger $x$ would result with the sum exceeding $s$. Smaller $x$ would result in too small sum, even if a path goes to the right child all the time (so, the sum is maximized). Proof: every vertex is strictly smaller than the corresponding vertex in the "minimal" path for the computed largest possible $x$: So, from $L$ and $R$ we can get the value of LCA. Let's assume that the computed value of LCA is $1$. For any other value we know that the value of vertex on depth $k$ would be greater by $(x - 1) \cdot 2^{k}$ compared to LCA equal to $1$, and we know depths of all vertices on a path, so we can subtract the sum of those differences from $s$, and assume the LCA is $1$. The sum of vertices from $1$ to $a$ is $2 \cdot a - popcount(a)$. Proof: if the binary representation of $a$ has $1$ on the $i$-th position from the right, there will be $1$ on the $(i - 1)$-th position in the index of the parent of $a$ and so on. So this bit adds $2^{i} + 2^{i - 1} + ... + 1 = 2^{i + 1} - 1 = 2 \cdot 2^{i} - 1$, so everything is doubled, and we get "-1" the number of times equal to the number of 1's in the binary representation of $a$. Thus, the formula is $2 \cdot a - popcount(a)$. If endpoints are $a$ and $b$, the sum of vertices will be $2 \cdot a - popcount(a) + 2 \cdot b - popcount(b) - 1$ (we subtract the LCA that was counted twice). Since popcounts are small, we can iterate over each of them and we know the left value of equation: $s' + popcount(a) + popcount(b) + 1 = 2 \cdot (a + b)$ Here, $s'$ is equal to the initial $s$ minus whatever we subtracted when changing LCA from the binary-searched $x$ to $1$. The remaining problem is: Given binary lengths $L$ and $R$ of numbers $a$ and $b$, their popcounts, and the sum $a + b$, find the number of such pairs $(a, b)$. This can be solved in standard dynamic programming on digits. To slightly improve the complexity, we can iterate over the sum $popcount(a) + popcount(b)$ instead of the two popcounts separately. The required complexity is $O(\log^{5}(s))$ or better.
[ "bitmasks", "brute force", "combinatorics", "dp" ]
3,200
null
750
H
New Year and Snowy Grid
\textbf{Pay attention to the output section below, where you will see the information about flushing the output.} Bearland is a grid with $h$ rows and $w$ columns. Rows are numbered $1$ through $h$ from top to bottom. Columns are numbered $1$ through $w$ from left to right. Every cell is either allowed (denoted by '.' in the input) or permanently blocked (denoted by '#'). Bearland is a cold land, where heavy snow often makes travelling harder. Every day a few allowed cells are \textbf{temporarily} blocked by snow. Note, that this block works only on this particular day and next day any of these cells might be allowed again (unless there is another temporarily block). It's possible to move directly between two cells only if they share a side and none of them is permanently or temporarily blocked. Limak is a little polar bear who lives in Bearland. His house is at the top left cell, while his school is at the bottom right cell. Every day Limak should first go from his house to the school and then return back to his house. Since he gets bored easily, he doesn't want to \textbf{visit the same cell twice} on one day, except for the cell with his house, where he starts and ends. If Limak can reach a school and return home avoiding revisiting cells, he calls a day interesting. There are $q$ days you must process, one after another. For each of these days you should check if it's interesting and print "YES" or "NO" on a separate line. In order to be able to read the description of the next day you should print the answer for the previous one and flush the output. It's guaranteed that a day with no cells temporarily blocked by snow would be interesting. It's also guaranteed that cells with Limak's house and school are never blocked (neither permanently or temporarily).
Let's solve an easier problem first. For every query, we just want to say if Limak can get from one corner to the other. He can't do that if and only if blocked cells connect the top-right side with the bottom-left side - this is called a dual problem. On the drawing above, the top-right side and bottom-left side are marked with blue, and blocked cells are black. There is a path of blocked cells between the two sides what means that Limak can't get from top-left to bottom-right corner. The duality in graphs changes the definition of adjacency from "sharing a side" to "touching by a corner or side" - the black cells on the drawing aren't side-adjacent but they still block Limak from passing through. Similarly, if Limak was allowed to move to any of 8 corner/side-adjacent cells, black cells would have to touch by sides to block Limak from passing through. The idea of a solution is to find CC's (connected components) of blocked cells before reading queries, and then for every query see what CC's are connected with each other by temporarily blocked cells. To make our life easier, let's treat the blue sides as blocked cells too by expanding the grid by 1 in every direction. Then for every query, we want to check if new blocked cells connect the bottom-left CC and top-right CC. Before reading queries, we can find CC's of blocked cells (remember that a cell has 8 adjacent cells now!). Let's name those initial CC's as regions. When a temporarily blocked cell appears, we iterate through the adjacent cells and if some of them belong to initial regions, we apply find&union to mark some regions as connected to each other (and connected to this new cell that is a temporary region of size 1). This can be done in $O(k\cdot\log k)$ where $k$ is the number of temporarily blocked cells. This solves the easier version of a problem, where we just check if Limak can get from one corner to the other - if the two special regions are connected at the end then the answer is "NO", and it's "YES" otherwise. What about the full problem? Limak wants to move to the opposite corner and back, not using the same cell twice. If you treat a grid as a graph, this means checking if there is a cycle passing through the two corners (a cycle without repeated vertices). It's reasonable to then think about bridges and articulation points. An articulation point here would be such a cell that making it blocked would disconnect the two corners from each other - it's a cell that Limak must go through on both parts of his journey. Our dual problem becomes: check if the two sides are almost connected i.e. it's enough to add one more blocked cell to make the connection (that cell must be an articulation point). The previously described solution needs some modification. We did F&U on regions adjacent to temporarily blocked cells. If some region was connected with some other region in the current query, let's call it an interesting region - there are $O(k)$ of them. If we preprocess the set of pairs of regions that are initially almost connected (it's enough to add one more blocked cell to make them connected), we can then for a query iterate over pairs: a region connected to the bottom-right side and a region connected to the other side, and check if this pair is in the set of almost-connected regions. There are $O(k^{2})$ pairs and if any of them is almost-connected, we have an almost-connection between the two sides and we print "NO", because Limak can't avoid revisiting cells.
[ "dfs and similar", "dsu", "graphs", "interactive" ]
3,500
#include <bits/stdc++.h> using namespace std; #define SIDE1 cc[3][0] #define SIDE2 cc[0][3] const int N = 1005; int h, w; char sl[N]; bool allow[N][N]; int cc_cnt, cc[N][N]; // which connected component set<pair<int,int>> edges; // pairs of almost connected CC's // find & union namespace FU { int group[N*N]; vector<int> inv[N*N]; set<int> affected; void init(int i) { if(affected.count(i)) return; affected.insert(i); group[i] = i; inv[i].push_back(i); } void uni(int a, int b) { init(a), init(b); a = group[a], b = group[b]; if(a == b) return; for(int x : inv[a]) { group[x] = b; inv[b].push_back(x); } inv[a].clear(); } bool areConnected(int a, int b) { init(a), init(b); return group[a] == group[b]; } void clear() { for(int i : affected) { group[i] = 0; inv[i].clear(); } affected.clear(); } bool almostConnectedPair() { init(SIDE1), init(SIDE2); for(int x : affected) if(areConnected(SIDE1, x)) for(int y : affected) if(areConnected(SIDE2, y)) if(edges.count({x, y})) return true; return false; } } bool inRange(int row, int col) { return 0 <= row && row <= h + 1 && 0 <= col && col <= w + 1; } bool duality(vector<pair<int,int>> snow) { FU :: clear(); for(pair<int,int> p : snow) { int row = p.first, col = p.second; cc[row][col] = ++cc_cnt; for(int r2 = row - 1; r2 <= row + 1; ++r2) for(int c2 = col - 1; c2 <= col + 1; ++c2) if(cc[r2][c2]) FU :: uni(cc[r2][c2], cc[row][col]); } if(FU :: almostConnectedPair()) return true; for(pair<int,int> p : snow) { int row = p.first, col = p.second; for(int r2 = row - 2; r2 <= row + 2; ++r2) for(int c2 = col - 2; c2 <= col + 2; ++c2) if(inRange(r2, c2) && cc[r2][c2]) { if(FU :: areConnected(cc[row][col], SIDE1) && FU :: areConnected(cc[r2][c2], SIDE2)) return true; if(FU :: areConnected(cc[row][col], SIDE2) && FU :: areConnected(cc[r2][c2], SIDE1)) return true; } } return false; } void dfs(int row, int col) { for(int r2 = row - 1; r2 <= row + 1; ++r2) for(int c2 = col - 1; c2 <= col + 1; ++c2) if(inRange(r2, c2) && allow[r2][c2] && !cc[r2][c2]) { cc[r2][c2] = cc[row][col]; dfs(r2, c2); } } int main() { int q; scanf("%d%d%d", &h, &w, &q); for(int row = 0; row < h; ++row) { scanf("%s", sl); for(int col = 0; col < w; ++col) allow[row+1][col+1] = (sl[col] == '#'); } for(int row = 3; row <= h + 1; ++row) allow[row][0] = true; for(int col = 1; col <= w - 2; ++col) allow[h+1][col] = true; for(int col = 3; col <= w + 1; ++col) allow[0][col] = true; for(int row = 1; row <= h - 2; ++row) allow[row][w+1] = true; for(int row = 0; row <= h + 1; ++row) for(int col = 0; col <= w + 1; ++col) if(allow[row][col] && !cc[row][col]) { cc[row][col] = ++cc_cnt; dfs(row, col); } for(int row = 0; row <= h + 1; ++row) for(int col = 0; col <= w + 1; ++col) if(cc[row][col]) for(int r2 = row - 2; r2 <= row + 2; ++r2) for(int c2 = col - 2; c2 <= col + 2; ++c2) if(inRange(r2, c2) && cc[r2][c2] && cc[row][col] != cc[r2][c2]) edges.insert({cc[row][col], cc[r2][c2]}); assert(SIDE1 != SIDE2); assert(!duality(vector<pair<int,int>>{})); while(q--) { int k; scanf("%d", &k); vector<pair<int,int>> snow(k); for(pair<int,int> & p : snow) scanf("%d%d", &p.first, &p.second); puts(duality(snow) ? "NO" : "YES"); fflush(stdout); // clear for(pair<int,int> p : snow) cc[p.first][p.second] = 0; cc_cnt -= snow.size(); } }
754
A
Lesha and array splitting
One spring day on his way to university Lesha found an array $A$. Lesha likes to split arrays into several parts. This time Lesha decided to split the array $A$ into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array $A$. Lesha is tired now so he asked you to split the array. Help Lesha!
Only in one case there is no answer. When array consists entirely of zeros. Because all subarrays of such array has zero sum. Otherwise there are two cases: Array sum is not zero. In this case we can divide array into one subarray $A[1... n]$. Array sum is zero. But we know that array has non-zero elements. Then there is exists such prefix $A[1... p]$, which sum is $s$ and $s \neq 0$. If sum of array is zero and sum of prefix is $s$, then sum of remaining suffix is equals to $0 - s = - s$ ($- s \neq 0$). Therefore array can be divided into two parts $A[1... p]$ and $A[p + 1... n]$. Time complexity - $O(n)$.
[ "constructive algorithms", "greedy", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); vector<int> a(n); long long sum = 0; for (int & x : a) { scanf("%d", &x); sum += x; } if (sum != 0) { puts("YES"); puts("1"); printf("%d %d\n", 1, n); exit(0); } sum = 0; for (int i = 0; i < n; i++) { sum += a[i]; if (sum != 0) { puts("YES"); puts("2"); printf("%d %d\n", 1, i + 1); printf("%d %d\n", i + 2, n); exit(0); } } puts("NO"); }
754
B
Ilya and tic-tac-toe game
Ilya is an experienced player in tic-tac-toe on the $4 × 4$ field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not. The rules of tic-tac-toe on the $4 × 4$ field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets \textbf{three of his signs in a row next to each other} (horizontal, vertical or diagonal).
This problem can be solved by simple bruteforce. Let's brute cell in which Ilya put X. Let's put X in this cell. Next step is to check if there is three consecutive Xs on field. This is done as follows. Let's brute cell which is first of three consecutive Xs. Next let's brute direction of three consecutive Xs. If we know first cell and direction, we should check that there is three consecutive cells from first cell towards fixed direction.
[ "brute force", "implementation" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { char str[4][4 + 1]; // cells are '.', 'o', 'x' for (int i = 0; i < 4; i++) { cin >> str[i]; } auto check = [&]() { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) continue; if (i + dx * 3 > 4 || j + dy * 3 > 4 || i + dx * 3 < -1 || j + dy * 3 < -1) continue; bool ok = true; for (int p = 0; p < 3; p++) { ok &= str[i + p * dx][j + p * dy] == 'x'; } if (ok) return true; } } } } return false; }; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (str[i][j] == '.') { str[i][j] = 'x'; if (check()) { puts("YES"); exit(0); } str[i][j] = '.'; } } } puts("NO"); }
754
C
Vladik and chat
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them. At first, he need to download $t$ chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that \textbf{there could not be two or more messages in a row with the same sender}. Moreover, \textbf{a sender never mention himself in his messages}. Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages. He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!
Let's number users from $1$ to $n$. Let's us know for every message users mentioned in message. Let's define arrays $A$ and $S$. $A_{i} =$ index of sender of $i$-th message, if sender of $i$-th message is unknown, then $A_{i} = - 1$. $S_{i} =$ set of mentioned users in $i$-th message. Now for every message where sender is unknown we need to restore sender. In other words for every $i$, such that $A_{i} = - 1$, we need to find number from $1$ to $n$, such that for every $j$, that $1 \le j < n$, condition $A_{j} \neq A_{j + 1}$ satisfied. This can be solved using Dynamic Programming: $DP(pref, last) = true$, if over first $pref$ messages we can restore all unknown senders, and $pref$-th message has sender number $last$, otherwise $false$. There next transitions in DP: $(p r e f,l a s t)\rightarrow(p r e f+1,n e w)$, where $new$ - index of user, who send $(pref + 1)$-th message. $new$ should be not equals to $last$ and $new$ should be not equals to every number from set $S_{pref + 1}$. Also if for $(pref + 1)$-th message we know sender then $new$ should be equals to $A_{pref + 1}$. Time complexity of this DP is $O(N^{2} * M)$. Also there is exist another solution. Greedy: While we have messages with unknown sender, for every of which there is only one possible user, which can be put as sender not violating conditions described in statement, then put this user as sender. If in one moment we will have a message with zero possible users, which can be put as sender not violating conditions in statement, then we can't restore senders of messages in chat. Otherwise if every message has two or more possible users which can be senders, then we should choose any such message and put as sender any user, which is possible for this message.
[ "brute force", "constructive algorithms", "dp", "implementation", "strings" ]
2,200
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(), (x).end() void solve() { int n; cin >> n; vector<string> names(n); for (string& name : names) { cin >> name; } sort(all(names)); auto getIdx = [&](const string& s) { int pos = lower_bound(all(names), s) - names.begin(); if (pos == (int)names.size() || names[pos] != s) return -1; return pos; }; auto splitIntoUserMessage = [](const string& s) { size_t pos = s.find(':'); assert(pos != string::npos); return make_pair(s.substr(0, pos), s.substr(pos + 1)); }; auto splitIntoTokensOfLatinLetters = [](const string& s) { vector<string> result; string token; for (char c : s) { if (isalpha(c) || isdigit(c)) { token += c; } else { if (!token.empty()) { result.push_back(token); } token.clear(); } } if (!token.empty()) { result.push_back(token); } return result; }; int m; cin >> m; vector<int> who(m); vector<vector<char>> can(m, vector<char>(n, true)); vector<string> messages(m); string tmp; getline(cin, tmp); for (int i = 0; i < m; i++) { string cur; getline(cin, cur); pair<string, string> p = splitIntoUserMessage(cur); const string& user = p.first; const string& message = p.second; who[i] = getIdx(user); if (who[i] != -1) { fill(all(can[i]), false); can[i][who[i]] = true; } messages[i] = message; vector<string> tokens = splitIntoTokensOfLatinLetters(message); for (const string& z : tokens) { int idx = getIdx(z); if (idx != -1) { can[i][idx] = false; } } } vector<vector<int>> par(m, vector<int>(n, -1)); for (int i = 0; i < n; i++) { if (can[0][i]) par[0][i] = 0; } for (int msg = 0; msg + 1 < m; msg++) { for (int i = 0; i < n; i++) { if (par[msg][i] == -1) continue; for (int j = 0; j < n; j++) { if (i == j) continue; if (can[msg + 1][j]) { par[msg + 1][j] = i; } } } } int msg = m - 1, pos = -1; for (int i = 0; i < n; i++) { if (par[msg][i] != -1) { pos = i; break; } } if (pos == -1) { cout << "Impossible\n"; return; } while (msg >= 0) { who[msg] = pos; pos = par[msg][pos]; msg--; } for (int i = 0; i < m; i++) { cout << names[who[i]] << ":" << messages[i] << "\n"; } return; } int main() { //freopen("input.txt", "r", stdin); int t; cin >> t; // number of tests while (t--) { solve(); } }
754
D
Fedor and coupons
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket. The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has $n$ discount coupons, the $i$-th of them can be used with products with ids ranging from $l_{i}$ to $r_{i}$, inclusive. Today Fedor wants to take exactly $k$ coupons with him. Fedor wants to choose the $k$ coupons in such a way that the number of such products $x$ that all coupons can be used with this product $x$ is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!
Formalized version of this problem: Given $n$ segments, we need to choose $k$ of them, such that intersection of chosen segments has maximum possible length. Let's use binary search to find maximum possible length of intersection. Let's this length equals to $len$. If exist $k$ segments, which have length of intersection greater or equals to $len$, then if we decrease right border of this segments by $(len - 1)$, then length of intersection will be greater than of equal to $1$. So solution is: Fix $len$ - length of intersection by binary search. Now we should check if there is exist $k$ such segments, that their intersection length greater than or equal to $len$. This can be done as follows. Decrease right border of every segment by $(len - 1)$. Now we should check if there is exist $k$ such segments, which have intersection length greater or equals to $1$. This can be done by different ways. For example using method of events - segment starts, segment ends. And we should find such point, which covered by $k$ segments. Time complexity - $O(N\log N\log R)$, where $R \approx 10^{9}$.
[ "binary search", "data structures", "greedy", "sortings" ]
2,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; int nextInt() { int x = 0, p = 1; char c; do { c = getchar(); } while (c <= 32); if (c == '-') { p = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); } return x * p; } #define all(x) (x).begin(), (x).end() const int N = (int)3e5 + 5; const int MAX_VAL = (int)1e9; int n; ll l[N], r[N]; struct event { ll x; int c; event() {} event(ll x, int c) : x(x), c(c) {} }; pair<ll, int> check(ll len) { if (len == 0) return make_pair(0LL, n); static vector<event> evs; evs.resize(0); for (int i = 1; i <= n; i++) { if (r[i] - len > l[i]) { evs.push_back(event(l[i], 1)); evs.push_back(event(r[i] - len, -1)); } } sort(all(evs), [](const event & a, const event & b) { return a.x < b.x; }); reverse(all(evs)); int cnt = 0, maxiCnt = 0; ll bestPos = 0; while (evs.size() > 0) { ll x = evs.back().x; while (evs.size() > 0 && evs.back().x == x) { cnt += evs.back().c; evs.pop_back(); } if (cnt > maxiCnt) { maxiCnt = cnt; bestPos = x; } } return make_pair(bestPos, maxiCnt); } vector<int> getAns(ll len) { if (len == 0) { vector<int> res(n); iota(all(res), 1); return res; } ll pos = check(len).first; vector<int> res; for (int i = 1; i <= n; i++) { if (pos >= l[i] && pos < r[i] - len) { res.push_back(i); } } return res; } int main() { n = nextInt(); int k = nextInt(); for (int i = 1; i <= n; i++) { l[i] = nextInt(); r[i] = nextInt() + 2; } ll l = 0, r = MAX_VAL + MAX_VAL + 5; while (r - l > 1) { ll mid = (l + r) >> 1; if (check(mid).second >= k) l = mid; else r = mid; } vector<int> ans = getAns(l); cout << l << endl; assert((int)ans.size() >= k); ans.resize(k); for (int i : ans) { printf("%d ", i); } puts(""); }
754
E
Dasha and cyclic table
Dasha is fond of challenging puzzles: Rubik's Cube $3 × 3 × 3$, $4 × 4 × 4$, $5 × 5 × 5$ and so on. This time she has a cyclic table of size $n × m$, and each cell of the table contains a lowercase English letter. Each cell has coordinates $(i, j)$ ($0 ≤ i < n$, $0 ≤ j < m$). The table is cyclic means that to the right of cell $(i, j)$ there is the cell $(i,(j+1)\bmod m)$, and to the down there is the cell $((i+1)\operatorname{mod}\,n,j)$. Dasha has a pattern as well. A pattern is a non-cyclic table of size $r × c$. Each cell is either a lowercase English letter or a question mark. Each cell has coordinates $(i, j)$ ($0 ≤ i < r$, $0 ≤ j < c$). The goal of the puzzle is to find all the appearance positions of the pattern in the cyclic table. We say that the cell $(i, j)$ of cyclic table is an appearance position, if for every pair $(x, y)$ such that $0 ≤ x < r$ and $0 ≤ y < c$ one of the following conditions holds: - There is a question mark in the cell $(x, y)$ of the pattern, or - The cell $((i+x)\operatorname{mod}\,n,(j+y)\operatorname{mod}\,m)$ of the cyclic table equals to the cell $(x, y)$ of the pattern. Dasha solved this puzzle in no time, as well as all the others she ever tried. Can you solve it?.
Let's consider simple bruteforce. Let's $T$ - cyclic table, $P$ - pattern, $R$ - result. Then simple bruteforces looks like that: Let's rewrite bruteforce: Let's define $G$. $G_{c, i, j} = true$, if $T_{i, j} = c$, otherwise $false$. It's easy to understand, that (T[i][j] == c) is equivalent $G[c][i][j]$. Then line of code R[(i - x) mod n][(j - y) mod m] := R[(i - x) mod n][(j - y) mod m] and (T[i][j] == c) is equivalent to R[(i - x) mod n][(j - y) mod m] := R[(i - x) mod n][(j - y) mod m] and G[c][i][j] Let's write shift of matrix $H$ of size $n \times m$ by $i$ to the up and by $j$ to the left as $shift(H, i, j)$. Also let's write element-wise $and$ of two matrix $A$ and $B$, as $A$ $and$ $B$. Then bruteforce looks like that: Operations $shift$ and $and$ on boolean matrices of size $n \times m$ have time complexity $\frac{\eta\cdot\eta\dot{1}}{\mathcal{3}\dot{2}}$ operations using std::bitset. As result, we improved simple bruteforces which gives accepted. Improved bruteforce works in $\scriptstyle{\frac{\mu-\mu_{1}r c}{32}}$ operations.
[ "bitmasks", "brute force", "fft", "strings", "trees" ]
2,600
import java.io.*; import java.util.*; public class Main { static class InputReader { BufferedReader bufferedReader; StringTokenizer stringTokenizer; InputReader(InputStream inputStream) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream), 32768); stringTokenizer = null; } String next() { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } return stringTokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } static int[] newBitSet(int n) { return new int[(n + 31) / 32]; } static void setBit(int[] a, int pos) { a[pos >>> 5] |= (1 << (pos & 31)); } static boolean getBit(int[] a, int pos) { return ((a[pos >>> 5]) & (1 << (pos & 31))) != 0; } static void setAll(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = ~0; } } static void resetAll(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = 0; } } static void andXYtoX(int[] x, int[] y) { for (int i = 0; i < x.length; i++) { x[i] &= y[i]; } } static void leftShiftAndOr(int ch, int shift, int x, int[][][][] shl, int[] to) { int[] z = shl[ch][shift & 31][x]; int delta = (shift >>> 5); for (int i = delta; i < to.length; i++) { to[i - delta] |= z[i]; } } static void rightShiftAndOr(int ch, int shift, int x, int[][][][] shr, int[] to) { int[] z = shr[ch][shift & 31][x]; int delta = (shift >>> 5); for (int i = 0; i + delta < to.length; i++) { to[i + delta] |= z[i]; } } static void printBitset(int a[], int l, int r) { for (int i = l; i <= r; i++) { System.err.print(getBit(a, i) ? '1' : '0'); } System.err.println(); } static final int ALPHA = 26; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int[][][][] shl = new int[ALPHA][32][n][]; int[][][][] shr = new int[ALPHA][32][n][]; for (int c = 0; c < ALPHA; c++) { for (int sh = 0; sh < 32; sh++) { for (int i = 0; i < n; i++) { shl[c][sh][i] = newBitSet(m); shr[c][sh][i] = newBitSet(m); } } } String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = in.next(); for (int j = 0; j < m; j++) { int c = s[i].charAt(j) - 'a'; for (int sh = 0; sh < 32; sh++) { if (j - sh >= 0) { setBit(shl[c][sh][i], j - sh); } if (j + sh < m) { setBit(shr[c][sh][i], j + sh); } } } } int r = in.nextInt(); int c = in.nextInt(); String[] patt = new String[r]; int[][] res = new int[n][]; for (int i = 0; i < n; i++) { res[i] = newBitSet(m); setAll(res[i]); } int[] tmp = newBitSet(m); for (int i = 0; i < r; i++) { patt[i] = in.next(); for (int j = 0; j < c; j++) { if (patt[i].charAt(j) == '?') continue; int cur = patt[i].charAt(j) - 'a'; int shiftByX = (((-i) % n) + n) % n; int shiftByY = (((j) % m) + m) % m; for (int x = 0; x < n; x++) { int nx = x + shiftByX; if (nx >= n) nx -= n; resetAll(tmp); leftShiftAndOr(cur, shiftByY, x, shl, tmp); rightShiftAndOr(cur, m - shiftByY, x, shr, tmp); andXYtoX(res[nx], tmp); } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(getBit(res[i], j) ? '1' : '0'); } out.println(); } out.close(); } }
755
A
PolandBall and Hypothesis
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer $n$ that for each positive integer $m$ number $n·m + 1$ is a prime number". Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Could you prove it wrong? Write a program that finds a counterexample for any $n$.
There are many ways to solve the problem. There can't be many primes in a row, so we can just bruteforce until we find a composite number. Note that it is not neccesarily true for huge numbers. More general, there is a prime arithmetic progression of length $k$ for any $k$, but there is no infinitely-long sequence! Another way to solve the problem is noticing that $n \cdot (n - 2) + 1 = (n - 1) \cdot (n - 1)$, so we can just output $n - 2$. However, we can't do that when $n \le 2$. This is a special case.
[ "brute force", "graphs", "math", "number theory" ]
800
null
755
B
PolandBall and Game
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses. You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?
Let PolandBall know $n$ words, EnemyBall $m$ words. Let $k$ be set of words which both Balls know. It's easy to see that Balls should process words from $k$ first. If $k$ contains even number of words, PolandBall will have an advantage of one additional word. Then, if $n \le m$, PolandBall loses. Otherwise - he wins.
[ "binary search", "data structures", "games", "greedy", "sortings", "strings" ]
1,100
null
755
C
PolandBall and Forest
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with $k$ vertices and $k - 1$ edges, where $k$ is some integer. Note that one vertex \textbf{is} a valid tree. There is exactly one relative living in each vertex of each tree, they have unique ids from $1$ to $n$. For each Ball $i$ we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those. How many trees are there in the forest?
Property: Look at one tree and take its diameter. Name its endpoints A and B. For each vertex u from this component, $p[u] = A$ or $p[u] = B$. It's easy to prove that. We can just count number of different elements in P and divide it by two. Special case : Isolated vertices (those with $p[i] = i$).
[ "dfs and similar", "dsu", "graphs", "interactive", "trees" ]
1,300
null
755
D
PolandBall and Polygon
PolandBall has such a convex polygon with $n$ veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number $k$ such that $gcd(n, k) = 1$. Vertices of the polygon are numbered from $1$ to $n$ in a clockwise way. PolandBall repeats the following process $n$ times, starting from the vertex $1$: Assume you've ended last operation in vertex $x$ (consider $x = 1$ if it is the first operation). Draw a new segment from vertex $x$ to $k$-th next vertex in clockwise direction. This is a vertex $x + k$ or $x + k - n$ depending on which of these is a valid index of polygon's vertex. Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.
First, we can set $k = min(k, n - k)$. This changes nothing right now, but we'll use it later. Our diagonals correspond to intervals [$L_{i}$, $R_{i}$], each intersection of two diagonals: A) adds one to result B) is equivalent to intersection of their intervals We will use segment or fenwick tree to store beginnings and ends of intervals. Because of the fact that all the segments have equal length (length = K) we know exactly what their intersection looks like. Also, in order to maintain edges like (7, 3) we'll insert some intervals twice. Because of changes we did to $k$ in the very beginning, we'll never count anything more than once. Complexity : $O(NlogN)$
[ "data structures" ]
2,000
null
755
E
PolandBall and White-Red graph
PolandBall has an undirected simple graph consisting of $n$ vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: white and red. Colorfulness of the graph is a value $min(d_{r}, d_{w})$, where $d_{r}$ is the diameter of the red subgraph and $d_{w}$ is the diameter of white subgraph. The diameter of a graph is a largest value $d$ such that shortest path between some pair of vertices in it is equal to $d$. If the graph is not connected, we consider its diameter to be -1. PolandBall wants the final graph to be as neat as possible. He wants the final colorfulness to be equal to $k$. Can you help him and find any graph which satisfies PolandBall's requests?
We should definitely start with estimating how big can be $k$. It turns out that we can't obtain diameter greater than $3$. You can prove this fact by yourself or try here: Proof. We can also easily show that answer is $- 1$ for $k = 1$. So, the problem is to solve K = 2 and K = 3. Constructing K = 3: Let's start with graph G, which is the smallest possible graph: 1 - 2 2 - 3 3 - 4 We will add vertices <$5$..$N$> one by one, when vertex $i$ will be joint with vertices 1 and 3, and if $i > 5$, with vertices <$5$; $i - 1$>. It's easy to see that ShortestPath(1, 4) is exactly 3. Also, ShortestPath(1, 4) in the complement graph is 3. Because of the property, this is a valid solution for $k = 3$. Constructing K = 2: When $N = 4$, answer is $- 1$. Graph G : path from 1 to N. G has diameter N - 1, but it does not matter. The smaller one is from complement graph. It is easy to see that for $N > 4$ the diameter of the second graph is exactly $2$. Of course there are many other ways to construct both graphs. Note that both red and white graphs have to be connected and we should pay some attention to it. Someone in the comments before the round said: "Give him a hat, and he will become IndonesiaBall. " Indeed, it's true. Country Balls usually have colours the same as flags of countries they represent. However, when PolandBall originated the creator mistakenly drew it as red-white instead of white-red. PolandBall was mad, but decided to stay this way =) This is a picture of a PolandBall dressed as husar. The husars were a Polish military formation from XVII century, a very powerful one. Usually recognizable because of the special wings.
[ "constructive algorithms", "graphs", "shortest paths" ]
2,400
null
755
F
PolandBall and Gifts
It's Christmas time! PolandBall and his friends will be giving themselves gifts. There are $n$ Balls overall. Each Ball has someone for whom he should bring a present according to some permutation $p$, $p_{i} ≠ i$ for all $i$. Unfortunately, Balls are quite clumsy. We know earlier that exactly $k$ of them will forget to bring their gift. A Ball number $i$ will get his present if the following two constraints will hold: - Ball number $i$ will bring the present he should give. - Ball $x$ such that $p_{x} = i$ will bring his present. What is minimum and maximum possible number of kids who will \textbf{not} get their present if exactly $k$ Balls will forget theirs?
Every permutation can be represented as a set of cycles. Maximum: This is the easier case. Greedy works, some careful implementation and it's ok. Answer is usually $2k$ in this case, but not always. Minimum: If there are such cycles $c_{1}$, $c_{2}$, ... $c_{m}$ of length $a_{1}$, $a_{2}$, ..., $a_{n}$ that $a_{1} + a_{2} + ... + a_{n} = K$, then K it's enough. Otherwise the result can be $K + 1$. We would like to use knapsack to check it. However, the constraints are too big in this case for a normal knapsack. We will choose some parameter $T$ and process all numbers bigger than $T$ normally. If there are $w$ such elements, then complexity of this step is $O({\frac{w,k}{32}})$. There can be at most $\ _{T}^{\frac{N}{T}}$ numbers bigger than $T$, so it's $O({\frac{n\,k}{32\cdot T}})$. What should we do with numbers smaller than $T$? We'll process all numbers of the same type at once. When processing number of type $x$, we will maintain array $c[]$ which denotes "how many numbers of type $x$ are neccessary to have a certain number knapsack-possible. This step works in O($k \cdot T$). Complexity : O($k \cdot T$ + $\frac{p_{2}\cdot k}{3/2\ast T}$). We should choose such $T$ that this value is minimum possible. $T = 100$ seems reasonable.
[ "bitmasks", "dp", "greedy" ]
2,600
null
755
G
PolandBall and Many Other Balls
PolandBall is standing in a row with Many Other Balls. More precisely, there are exactly $n$ Balls. Balls are proud of their home land — and they want to prove that it's strong. The Balls decided to start with selecting exactly $m$ groups of Balls, each consisting either of single Ball or two neighboring Balls. Each Ball can join no more than one group. The Balls really want to impress their Enemies. They kindly asked you to calculate number of such divisions for all $m$ where $1 ≤ m ≤ k$. Output all these values modulo $998244353$, the Enemies will be impressed anyway.
The modulo instantly suggests an FFT-like approach. First, let's solve this problem using simple dynamic programming. DP[N][K] = DP[N-1][K] + DP[N-1][K-1] + DP[N-2][K-1], because we can either do nothing or add one interval of length 1 or 2. As for start, this works fine. We can calculate DP[1], DP[2], DP[3] and DP[4] using this simple formula. Calculating DP[x] means calculating DP[x][k] for all values k in range <1, K>, where K is the number from statement. We will perform binary exponentation of DPs. In order to do so, we should be able to count DP[x + 1] and DP[2 * x]. If we could do this operations, then we can obtain the result in O(logN). Important property: DP[a + b] can be counted using DP[a] * DP[b] and DP[a - 1] * DP[b - 1], when we treat DP[x] as polynomial with coefficients DP[x][0], DP[x][1], .... It is based by the fact that we can divide the sequence of length (a + b) in two parts of length a and b. If there is no segment of length 2 starting from position a, then we can choose some segments from the first part, and the remaining segments from the second part. For fixed number of intervals k, this is a sum of DP[a][i] * DP[b][k - i]. So, this is convolution of polynomials DP[A] and DP[B]. However, there may also be such a segment. In this case, everything stays the same, but we have k - 1 intervals instead of k and convolution of DP[a - 1] and DP[b - 1]. So, with some calculations we can count DP[a + b] using those DPs. Assume we have DP[n], DP[n - 1] and DP[n - 2]. Now we are trying to count DP[2 * n], DP[2 * n - 1], DP[2 * n - 2]. DP[2 * n] = DP[n + n], which can be counted using multiplication of DP[n] and DP[n-1]. DP[2*n-1] = DP[n + (n-1)], which can be counted using multiplication of DP[n], DP[n-1] and DP[n-2]. DP[2*n-2] = DP[(n-1) + (n-1)], which can be counted using multiplication of DP[n-1] and DP[n-2]. Therefore, we can obtain another, two times bigger, triplet of DPs. Of course, having DP[n], DP[n-1] and DP[n-2] in memory we can also easily count DP[n + 1] in O(K). We can also calculate DP[2*n], DP[2*n-1] and DP[2*n-2] in O(K log K). This is enough to perform the binary exponentation. Overall solution works in O(K log N log K).
[ "combinatorics", "divide and conquer", "dp", "fft", "math", "number theory" ]
3,200
null
756
A
Pavel and barbecue
Pavel cooks barbecue. There are $n$ skewers, they lay on a brazier in a row, each on one of $n$ positions. Pavel wants each skewer to be cooked some time in every of $n$ positions in two directions: in the one it was directed originally and in the reversed direction. Pavel has a plan: a permutation $p$ and a sequence $b_{1}, b_{2}, ..., b_{n}$, consisting of zeros and ones. Each second Pavel move skewer on position $i$ to position $p_{i}$, and if $b_{i}$ equals $1$ then he reverses it. So he hope that every skewer will visit every position in both directions. Unfortunately, not every pair of permutation $p$ and sequence $b$ suits Pavel. What is the minimum total number of elements in the given permutation $p$ and the given sequence $b$ he needs to change so that every skewer will visit each of $2n$ placements? Note that after changing the permutation should remain a permutation as well. There is no problem for Pavel, if some skewer visits some of the placements several times before he ends to cook. In other words, a permutation $p$ and a sequence $b$ suit him if there is an integer $k$ ($k ≥ 2n$), so that after $k$ seconds each skewer visits each of the $2n$ placements. It can be shown that some suitable pair of permutation $p$ and sequence $b$ exists for any $n$.
At first, let's deal with the permutation. We can see that $p$ should have exactly one cycle to suit Pavel. The minimum number of changes is $0$ if there is only one cycle, and the number of cycles if there is more than one cycle. What should we do with $b$? We can see that the skewers visit a particular position $x$ in the same direction again and again if and only if the total number of ones in $b$ is even. If the total number of ones in $b$ is odd, then each time a skewer visits a particular position $x$, it has direction different from the previous time. Thus, the condition is satisfied if and only if the number of ones in $b$ is odd. We should add $1$ to the answer if it isn't.
[ "constructive algorithms", "dfs and similar" ]
1,700
null
756
B
Travel Card
A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare. The fare is constructed in the following manner. There are three types of tickets: - a ticket for one trip costs $20$ byteland rubles, - a ticket for $90$ minutes costs $50$ byteland rubles, - a ticket for one day ($1440$ minutes) costs $120$ byteland rubles. Note that a ticket for $x$ minutes activated at time $t$ can be used for trips started in time range from $t$ to $t + x - 1$, inclusive. Assume that all trips take exactly one minute. To simplify the choice for the passenger, the system automatically chooses the optimal tickets. After each trip starts, the system analyses all the previous trips and the current trip and chooses a set of tickets for these trips with a minimum total cost. Let the minimum total cost of tickets to cover all trips from the first to the current is $a$, and the total sum charged before is $b$. Then the system charges the passenger the sum $a - b$. You have to write a program that, for given trips made by a passenger, calculates the sum the passenger is charged after each trip.
Hint: the problem looks difficult because tickets can change, however, it's can be solved with simple dynamic programming. You are asked the difference between neighboring dp's subtasks. More detailed editorial will be added soon.
[ "binary search", "dp" ]
1,600
null
756
C
Nikita and stack
Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer $x$ on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing. Nikita made $m$ operations with the stack but forgot them. Now Nikita wants to remember them. He remembers them one by one, on the $i$-th step he remembers an operation he made $p_{i}$-th. In other words, he remembers the operations in order of some permutation $p_{1}, p_{2}, ..., p_{m}$. After each step Nikita wants to know what is the integer on the top of the stack after performing the operations he have already remembered, in the corresponding order. Help him!
Hint 1: look at the operations in the reverse order. Let's count the balance for each prefix, i.e. the difference between the number of push(x) operations and the number of pop() operations. Hint 2: Now we have to find the first operation that makes balance positive. This can be done using segment tree. Solution: Let's reverse the order of operations. Now we can see that on the top of the stack will be the first integer added with push(x) such that the number of pop() operations and the number of push(x) operations before this operation is equal, if there is one. Let's keep for each position a value called balance: the number of push(x) operations minus the number of pop() operations before and including this position. To find the answer, we should find the first position with posivive balance. When we add an operation, we should add -1 or 1 to all posisions starting with the position of the operation, depending on the type of the operation. To cope with the operations quickly, we can store the balance in a segment tree. The addition is done with lazy propogation, finding the first position with positive balance can be done in two ways. First way is to perform binary search on the answer and then query the segment tree for maximim on some prefix. The compexity is $O(\log^{2}m)$ per query then. The other way is to walk down the tree always moving to the leftmost son with positive maximum. When we reach the leaf, the position of this leaf is the answer. The complexity is $O(\log m)$ per query. The overall complexity is $O(m\log m)$ or $O(m\log^{2}m)$ depending on the realization.
[ "data structures" ]
2,200
null
756
D
Bacterial Melee
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z". The testtube is divided into $n$ consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of $n$ Latin characters. Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place. For example, consider a testtube with population "babb". There are six options for an attack that may happen next: - the first colony attacks the second colony ($1 → 2$), the resulting population is "bbbb"; - $2 → 1$, the result is "aabb"; - $2 → 3$, the result is "baab"; - $3 → 2$, the result is "bbbb" (note that the result is the same as the first option); - $3 → 4$ or $4 → 3$, the population does not change. The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo $10^{9} + 7$.
Hint: find a condition when a string is reachable from another string in terms of subsequences, then apply DP for counting suitable subsequences. Solution: How to determine if a string can be obtained from another string after a number of operations? It helps to consider (maximal) blocks of adjacent characters. Let us define $comp(s)$ as a "compressed" version of $s$ that keeps a single character from each block of $s$ in the same order, for example, $c o m p(\mathrm{aaabbca})=\mathrm{abca}$. It is not hard to see that each operation either preserves the sequence of blocks (if we ignore their lengths) or erases a single block (when it consists of a single character and is overwritten by an adjacent character). This is the same as saying that each operation applied to $s$ either doesn't change $comp(s)$ or erases a single character from it. Therefore, if $t$ can be obtained from $s$ after a number of operations, then $comp(t)$ must be a subsequence of $comp(s)$. In fact, this is an "if and only if" condition. Indeed, suppose that $comp(t)$ is a subsequence of $comp(s)$. We start our process of making $t$ from $s$ by eliminating the blocks not present in $t$, effectively making $comp(s) = comp(t)$. After that, it can be seen that the borders of the blocks can be moved rather freely (but carefully enough not to murder any block) so that $s$ can be indeed made equal to $t$. We can see from the last argument that from the reachability point of view the two strings $s$ and $t$ are essentially different if $comp(s) \neq comp(t)$. If $s$ is the given string, and a string $u$ is a subsequence of $comp(s)$ that doesn't have equal adjacent characters, then there are $\textstyle{\binom{n-1}{\left|u_{1}-1\right\rangle}}$ reachable strings with $comp(...) = u$; indeed, this is exactly the number of ways to split $n$ characters into $|u|$ non-empty blocks. Now, for each $l$ we have to count the number of subsequences of $s$ with length $l$ that do not have equal adjacent characters. There are several ways to do that. One way is storing $dp_{c, l}$ - the number of valid subsequences of length $l$ that end in character $c$. We now process characters one by one and recompute values of $dp_{c, l}$. If the new character is $c_{i}$, then clearly values of $dp_{c, l}$ with $c \neq c_{i}$ do not change. We can also see that we can find the new values of $dp_{ci, l}$ with the formula $d p_{c,l}=1+\sum_{c\cap c_{i}}d p_{c,l-1}$
[ "brute force", "combinatorics", "dp", "string suffix structures" ]
2,400
null
756
E
Byteland coins
There are $n$ types of coins in Byteland. Conveniently, the denomination of the coin type $k$ divides the denomination of the coin type $k + 1$, the denomination of the coin type $1$ equals $1$ tugrick. The ratio of the denominations of coin types $k + 1$ and $k$ equals $a_{k}$. It is known that for each $x$ there are at most \textbf{20} coin types of denomination $x$. Byteasar has $b_{k}$ coins of type $k$ with him, and he needs to pay exactly $m$ tugricks. It is known that Byteasar never has more than $3·10^{5}$ coins with him. Byteasar want to know how many ways there are to pay exactly $m$ tugricks. Two ways are different if there is an integer $k$ such that the amount of coins of type $k$ differs in these two ways. As all Byteland citizens, Byteasar wants to know the number of ways modulo $10^{9} + 7$.
Let's calculate DP[pref][x] - number of ways to pay $x$ tugriks using only $pref$ first types. Of course, $x$ can be very big, but we will store DP only for those $x$ which are not bigger than the sum of all the coins of first $pref$ types and can lead to answer: $x = k \cdot D + (m%D)$ where $D$ is the last coin denomination. Every next layer of this DP can be calculated in $O(sz_{i})$ time using prefix sums where $sz$ is the size of the new layer. $s z_{i}\leq\Sigma_{j=1}^{i}b_{j}\cdot{\frac{D_{i}}{D_{i}}}$. $\begin{array}{c}{{\Sigma_{i=1}^{n}s z_{i}\le\Sigma_{i=1}^{n}\Sigma_{j=1}^{i}b_{j}\cdot\frac{D_{i}}{D_{i}}=\Sigma_{j=1}^{n}\Sigma_{i=j}^{n}b_{j}\cdot\frac{D_{j}}{D_{i}}\le\Sigma_{j=1}^{n}b_{j}\left(\frac{k}{1}+\frac{k}{2}+\frac{k}{2^{2}}+\ldots\right)=}}\end{array}$ Now all that remains is to calculate some info about $m%D$ to know what DP elemnts we are interested in. We should represent $m$ in a form of $ \Sigma _{i = 1}^{n}c_{i} \cdot D_{i}$. To find $c_{i}$ we should successively divide $m$ by all $a_{i}$, $c_{i}$ will be the reminders. All the divisions can be done in $O(\log^{2}m)$ time if we will not divide by $1$. Total complexity - $\left(\log^{2}m+k\cdot\Sigma_{i=1}^{n}b_{i}\right)$
[ "combinatorics", "dp", "math" ]
3,200
null
756
F
Long number
Consider the following grammar: - <expression> ::= <term> | <expression> '+' <term> - <term> ::= <number> | <number> '-' <number> | <number> '(' <expression> ')' - <number> ::= <pos_digit> | <number> <digit> - <digit> ::= '0' | <pos_digit> - <pos_digit> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' This grammar describes a number in decimal system using the following rules: - <number> describes itself, - <number>-<number> (l-r, $l ≤ r$) describes integer which is concatenation of all integers from $l$ to $r$, written without leading zeros. For example, 8-11 describes 891011, - <number>(<expression>) describes integer which is concatenation of <number> copies of integer described by <expression>, - <expression>+<term> describes integer which is concatenation of integers described by <expression> and <term>. For example, 2(2-4+1)+2(2(17)) describes the integer 2341234117171717. You are given an expression in the given grammar. Print the integer described by it modulo $10^{9} + 7$.
First of all we need to somehow parse the expression. Let's suppose we've builded a parse tree for the expression. Every number X can be seen as operation "concatenate something and X". We should understand how such an operation changes the number. $YX = Y \cdot 10^{len(X)} + X$. So we can represent each number $X$ as pair $(10^{len(X)}%MOD, X%MOD)$. Two such pairs can be merged: $(X_{1}, Y_{1}) + (X_{2}, Y_{2}) = (X_{1} \cdot X_{2}, Y_{1} \cdot X_{2} + Y_{2})$. Z((X,Y)) $= (X \cdot Z, \Sigma _{i = 0}^{Z - 1}Y \cdot X^{i}) = (X \cdot Z, Y \cdot \Sigma _{i = 0}^{Z - 1}X^{i})$. Geometric series can be calculated in $O(\log Z)$ time (using binary exponentiation) in both cases $X = 1$ and $X \neq 1$. L-R: if $len(L) = len(R)$ then L-R $= (len(L) \cdot (R - L + 1), \Sigma _{i = 0}^{R - L}(R - i) \cdot (10^{len(L)})^{i})$ $\Sigma_{t=0}^{R-L}(R-i)\cdot(10^{l e n(L)})^{i}=(R+1)\cdot{\frac{(10^{p o n(L))^{2}-L+1}-1}{10^{q e n(L)}-1}}-{\frac{(R-L+1)(10^{p o n(L)})^{n-L+1}}{t0^{q e n(L)}-1}}$. This sum also can be calculated in $O(len(L))$. If $len(L) \neq len(R)$ then we should iterate over all lengths between $len(L) + 1$ and $len(R) - 1$. But for every such length we can first calculate powers ($9 \cdot 10^{len - 1} + eps$) modulo $ \phi (MOD) = MOD - 1$ and then do the calculation in $O(\log M O D)$ time. Overall complexity will be $O(|s|\cdot\log M O D)$.
[ "expression parsing", "math", "number theory" ]
3,400
null
757
A
Gotta Catch Em' All!
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur. Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word "Bulbasaur" (without quotes) and sticks it on his wall. Bash is very particular about case — the first letter of "Bulbasaur" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word "Bulbasaur" from the newspaper. Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today? Note: \textbf{uppercase and lowercase letters are considered different.}
Expected complexity: ${\mathcal{O}}(n)$ Main idea: Maintain counts of required characters. Since we are allowed to permute the string in any order to find the maximum occurences of the string "Bulbasaur", we simply keep the count of the letters 'B', 'u', 'l', 'b', 'a', 's', 'r'. Now the string "Bulbasaur" contains 1 'B', 2'u', 1 'l', 2'a', 1 's', 1'r' and 1 'b', thus the answer to the problem is Min(count('B'), count('b'), count('s'), count('r'), count('l'), count('a')/2, count('u')/2). You can maintain the counts using an array. Corner Cases: 1. Neglecting 'B' and while calculating the answer considering count('b')/2. 2. Considering a letter more than once ( 'a' and 'u' ).
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { map<char, int> m; string s; cin>>s; for(auto x : s) m[x]++; int ans = m['B']; ans = min(ans, m['u']/2); ans = min(ans, m['a']/2); ans = min(ans, m['b']); ans = min(ans, m['s']); ans = min(ans, m['r']); ans = min(ans, m['l']); cout << ans << endl; return 0; }
757
B
Bash's Big Day
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases. But Zulu warns him that a group of $k > 1$ Pokemon with strengths ${s_{1}, s_{2}, s_{3}, ..., s_{k}}$ tend to fight among each other if $gcd(s_{1}, s_{2}, s_{3}, ..., s_{k}) = 1$ (see notes for $gcd$ definition). Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? \textbf{Note}: A Pokemon cannot fight with itself.
Expected complexity: $O(n{\sqrt{m a x(s_{i})}})$ Main idea: Square-root factorization and keeping count of prime factors. The problem can be simplified to finding a group of Pokemons such that their strengths have a common factor other that $1$. We can do this by marking just the prime factors, and the answer will be the maximum count of a prime factor occurring some number of times. The prime numbers of each number can be found out using pre-computed sieve or square-root factorization. Corner Cases : Since a Pokemon cannot fight with itself (as mentioned in the note), the minimum answer is 1. Thus, even in cases where every subset of the input has gcd equal to 1, the answer will be 1.
[ "greedy", "math", "number theory" ]
1,400
#include<bits/stdc++.h> using namespace std; int N; unordered_map<int, int> factors; int main() { ios_base::sync_with_stdio(false); cin >> N; while(N--) { int strength; cin >> strength; int root = sqrt(strength); for(int i = 2; i <= root; i++) { if(strength%i == 0) factors[i]++; while(strength%i == 0) strength /= i; } if(strength > 1) factors[strength]++; } int ans = 1; for(auto it = factors.begin(); it != factors.end(); it++) { ans = max(ans, (*it).second); } cout << ans << endl; return 0; }
757
C
Felicity is Coming!
It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has $n$ gyms. The $i$-th gym has $g_{i}$ Pokemon in it. There are $m$ distinct Pokemon types in the Himalayan region numbered from $1$ to $m$. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving. Formally, an evolution plan is a permutation $f$ of ${1, 2, ..., m}$, such that $f(x) = y$ means that a Pokemon of type $x$ evolves into a Pokemon of type $y$. The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol. Two evolution plans $f_{1}$ and $f_{2}$ are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an $i$ such that $f_{1}(i) ≠ f_{2}(i)$. Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo $10^{9} + 7$.
Expected complexity: $O(n l o g n)$ Main idea: Divide pokemon types into equivalence classes based on their counts in each list. Consider a valid evolution plan $f$. Let $c[p, g]$ be the number of times Pokemon $p$ appears in gym $g$. If $f(p) = q$ then $c[p,g_{i}]=c[q,g_{i}]\quad\forall i$. Now consider a group of Pokemon $P$ such that all of them occur equal number of times in each gym (i.e. for each $p,q\in P,\quad f[p_{i},g_{k}]=f[p_{j},g_{k}]\quad\forall k$). Any permutation of this group would be a valid bijection. Say we have groups $s_{1}, s_{2}, s_{3}, ...$, then the answer would be $|s_{1}|! |s_{2}|! |s_{3}|! ... mod 10^{9} + 7$. For implementing groups, we can use $vector < vector < int > >$ and for $i$-th pokemon, add the index of the gym to $i$-th vector. Now we need to find which of these vectors are equal. If we have the sorted $vector < vector < int > >$, we can find equal elements by iterating over it and comparing adjacent elements. Consider the merge step of merge sort. For a comparison between 2 vectors $v_{1}$ and $v_{2}$, we cover at least $min(v_{1}.size(), v_{2}.size())$ elements. Hence ${\mathcal{O}}(n)$ work is done at each level. There are $O(l o g n)$ levels.
[ "data structures", "hashing", "sortings", "strings" ]
1,900
#include<bits/stdc++.h> using namespace std; typedef long long LL; #define PB push_back #define ALL(X) X.begin(), X.end() #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL) const int N = 1e6; const LL MOD = 1e9 + 7; LL fact[N+1]; int main() { fast_io; fact[0] = fact[1] = 1; for(LL i=2;i<=N;i++) fact[i] = (fact[i-1]*i)%MOD; int n,m; cin >> n >> m; vector< vector<int> > x(m); for(int i=0;i<n;i++) { int s; cin >> s; for(int j=0;j<s;j++) { int t; cin >> t; x[t-1].PB(i); } } for(int i=0;i<m;i++) sort(ALL(x[i])); sort(ALL(x)); LL ans = 1; LL sm = 1; for(int i=1;i<m;i++) { if(x[i]==x[i-1]) sm++; else ans = (ans*fact[sm])%MOD, sm = 1; } ans = (ans*fact[sm])%MOD; cout << ans << endl; return 0; }
757
D
Felicity's Big Secret Revealed
The gym leaders were fascinated by the evolutions which took place at Felicity camp. So, they were curious to know about the secret behind evolving Pokemon. The organizers of the camp gave the gym leaders a PokeBlock, a sequence of $n$ ingredients. Each ingredient can be of type $0$ or $1$. Now the organizers told the gym leaders that to evolve a Pokemon of type $k$ ($k ≥ 2$), they need to make a valid set of $k$ cuts on the PokeBlock to get smaller blocks. Suppose the given PokeBlock sequence is $b_{0}b_{1}b_{2}... b_{n - 1}$. You have a choice of making cuts at $n + 1$ places, i.e., Before $b_{0}$, between $b_{0}$ and $b_{1}$, between $b_{1}$ and $b_{2}$, ..., between $b_{n - 2}$ and $b_{n - 1}$, and after $b_{n - 1}$. The $n + 1$ choices of making cuts are as follows (where a | denotes a possible cut): \[ | b_{0} | b_{1} | b_{2} | ... | b_{n - 2} | b_{n - 1} | \] Consider a sequence of $k$ cuts. Now each pair of consecutive cuts will contain a binary string between them, formed from the ingredient types. The ingredients before the first cut and after the last cut are wasted, which is to say they are not considered. So there will be exactly $k - 1$ such binary substrings. Every substring can be read as a binary number. Let $m$ be the maximum number out of the obtained numbers. If all the obtained numbers are positive and the set of the obtained numbers contains all integers from $1$ to $m$, then this set of cuts is said to be a valid set of cuts. For example, suppose the given PokeBlock sequence is $101101001110$ and we made $5$ cuts in the following way: \[ 10 | 11 | 010 | 01 | 1 | 10 \] So the $4$ binary substrings obtained are: $11$, $010$, $01$ and $1$, which correspond to the numbers $3$, $2$, $1$ and $1$ respectively. Here $m = 3$, as it is the maximum value among the obtained numbers. And all the obtained numbers are positive and we have obtained all integers from $1$ to $m$. Hence this set of cuts is a valid set of $5$ cuts. A Pokemon of type $k$ will evolve only if the PokeBlock is cut using a valid set of $k$ cuts. There can be many valid sets of the same size. Two valid sets of $k$ cuts are considered different if there is a cut in one set which is not there in the other set. Let $f(k)$ denote the number of valid sets of $k$ cuts. Find the value of $s=\sum_{k=2}^{n+1}f(k)$. Since the value of $s$ can be very large, output $s$ modulo $10^{9} + 7$.
Expected complexity: $O(N*2^{20})$ Main idea: DP with Bitmask. This problem can be solved using Dynamic Programming with bitmask. The important thing to note here is that the set of distinct numbers formed will be a maximum of 20 numbers, i.e. from 1 to 20, else it won't fit 75 bits(1*(1 bits) + 2*(2 bits) + 4*(3 bits) + 8*(4 bits) + 5*(5 bits) = 74 bits). So, we can use a bitmask to denote a set of numbers that are included in a set of cuts. Let's see a Top-Down approach to solve it : Lets define the function $f(i, mask)$ as : $f(i, mask)$ denotes the number of sets of valid cuts that can be obtained from the state $i, mask$. The state formation is defined below. Let $M$ be the maximum number among the numbers in $mask$. $mask$ denotes a set of numbers that have been generated using some number of cuts, all of them before $b_{i}$. Out of these cuts, the last cut has been placed just before $b_{i}$. Now, first we check if the set of cuts obtained from $mask$ is valid or not(in order for a mask to be valid, mask == $2^{X - 1}$ where $X$ denotes number of set bits in the mask) and increment the answer accordingly if the mask is valid. And then we also have the option of adding another cut. We can add the next cut just before $b_{x}$ provided the number formed by "$b_{i}$ $b_{i + 1}$...$b_{x - 1}$" <= 20. Set the corresponding bit for this number formed to 1 in the $mask$ to obtain $newMask$ and recursively find $f(x, newMask)$.
[ "bitmasks", "dp" ]
2,200
// Saatwik Singh Nagpal #include <bits/stdc++.h> using namespace std; #define TRACE #ifdef TRACE #define TR(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } #else #define TR(...) #endif typedef long long LL; typedef vector < int > VI; typedef pair < int,int > II; typedef vector < II > VII; #define MOD 1000000007 #define EPS 1e-12 #define N 200100 #define PB push_back #define MP make_pair #define F first #define S second #define ALL(v) v.begin(),v.end() #define SZ(a) (int)a.size() #define FILL(a,b) memset(a,b,sizeof(a)) #define SI(n) scanf("%d",&n) #define SLL(n) scanf("%lld",&n) #define PLLN(n) printf("%lld\n",n) #define PIN(n) printf("%d\n",n) #define REP(i,j,n) for(LL i=j;i<n;i++) #define PER(i,j,n) for(LL i=n-1;i>=j;i--) #define endl '\n' #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL) #define FILEIO(name) \ freopen(name".in", "r", stdin); \ freopen(name".out", "w", stdout); inline int mult(int a , int b) { LL x = a; x *= LL(b); if(x >= MOD) x %= MOD; return x; } inline int add(int a , int b) { return a + b >= MOD ? a + b - MOD : a + b; } inline int sub(int a , int b) { return a - b < 0 ? MOD - b + a : a - b; } LL powmod(LL a,LL b) { if(b==0)return 1; LL x=powmod(a,b/2); LL y=(x*x)%MOD; if(b%2) return (a*y)%MOD; return y%MOD; } int dp[1<<20][77]; int b[77] , n; int go(int mask , int i) { int cnt = __builtin_popcount(mask); if(i == n) { if(cnt != 0 && (1<<cnt)-1 == mask) return 1; return 0; } if(dp[mask][i] != -1) return dp[mask][i]; int ret = 0; if(b[i] == 0) ret = go(mask , i+1); else { int num = 0; int j = i; while(1) { num *= 2; num += b[j]; if(num > 20) break; //if(!(mask & (1<<(num-1)))) ret = add(ret , go(mask | (1<<(num-1)) , j+1)); j ++; if(j == n) break; } if(cnt != 0 && mask == (1<<cnt)-1) ret ++; } return dp[mask][i] = ret; } int main() { FILL(dp,-1); cin >> n; string s; cin >> s; REP(i,0,n) b[i] = s[i] - '0'; int ans = 0; REP(i,0,n) ans = add(ans , go(0,i)); PIN(ans); return 0; }
757
E
Bash Plays with Functions
Bash got tired on his journey to become the greatest Pokemon master. So he decides to take a break and play with functions. Bash defines a function $f_{0}(n)$, which denotes the number of ways of factoring $n$ into two factors $p$ and $q$ such that $gcd(p, q) = 1$. In other words, $f_{0}(n)$ is the number of ordered pairs of positive integers $(p, q)$ such that $p·q = n$ and $gcd(p, q) = 1$. But Bash felt that it was too easy to calculate this function. So he defined a series of functions, where $f_{r + 1}$ is defined as: \[ f_{r+1}(n)=\sum_{u\cdot n=n}{\frac{f_{r}(u)+f_{r}(v)}{2}}, \] Where $(u, v)$ is any ordered pair of positive integers, they need not to be co-prime. Now Bash wants to know the value of $f_{r}(n)$ for different $r$ and $n$. Since the value could be huge, he would like to know the value modulo $10^{9} + 7$. Help him!
Expected complexity: $O((N+Q)l o g N)$ Main idea: Multiplicative Functions. We can easily see that $f_{0}$ = $2^{(number of distinct prime factors of n)}$. We can also see that it is a multiplicative function. We can also simplify the definition of $f_{r + 1}$ as: $f_{r+1}(n)=\sum_{d\mid n}f_{r}(d)$ Since $f_{0}$ is a multiplicative function, $f_{r + 1}$ is also a multiplicative function. (by property of multiplicative functions) For each query, factorize $n$. Now, since $f_{r}$ is a multiplicative function, if $n$ can be written as: $n = p_{1}^{e1}p_{2}^{e2} ... p_{q}^{eq}$ Then $f_{r}(n)$ can be computed as: $f_{r}(n) = f_{r}(p_{1}^{e1}) * f_{r}(p_{2}^{e2}) * ... * f_{r}(p_{q}^{eq})$ Now observe that the value of $f_{r}(p^{n})$ is independent of $p$, as $f_{0}(p^{n}) = 2$. It is dependent only on $n$. So we calculate $f_{r}(2^{x})$ for all r and x using a simple $R * 20$ DP as follows: $d p[r][x]=\sum_{i=0}^{n}d p[r-1][i]$ And now we can quickly compute $f_{r}(n)$ for each query as: $f_{r}(n) = dp[r][e_{1}] * dp[r][e_{2}] * ... * dp[r][e_{q}]$
[ "brute force", "combinatorics", "dp", "number theory" ]
2,500
//Kyokai no Kanata // //Written by Satyam Pandey// #include<bits/stdc++.h> using namespace std; typedef pair<int,int> II; typedef vector<II> VII; typedef vector<int> VI; typedef vector< VI > VVI; typedef long long int LL; #define PB push_back #define MP make_pair #define F first #define S second #define SZ(a) (int)(a.size()) #define ALL(a) a.begin(),a.end() #define SET(a,b) memset(a,b,sizeof(a)) #define si(n) scanf("%d",&n) #define dout(n) printf("%d\n",n) #define sll(n) scanf("%lld",&n) #define lldout(n) printf("%lld\n",n) #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL) #define TRACE #ifdef TRACE #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr<<name<<" : "<<arg1<<endl; } template <typename Arg1, typename... Args> void __f(const char* names,Arg1&& arg1,Args&&... args){ const char* comma=strchr(names+1,','); cerr.write(names,comma-names)<<" : "<<arg1<<" | ";__f(comma+1,args...); } #else #define trace(...) #endif float inf=std::numeric_limits<double>::infinity(); LL INF=std::numeric_limits<LL>::max(); //FILE *fin = freopen("in","r",stdin); //FILE *fout = freopen("out","w",stdout); const int R=int(1e6)+5,P=25,N=R,mod = int(1e9)+7; int F[R][P],LP[N]; inline void seive(){ LP[1]=1; for(int i=2;i<N;i++){ if(!LP[i]) for(int j=i;j<N;j+=i) LP[j]=i; } } inline void precalc() { for(int i=0;i<R;i++) F[i][0] = 1; for(int i=1;i<P;i++) F[0][i] = 2; for(int i=1;i<R;i++) for(int j=1;j<P;j++) F[i][j] = (F[i][j-1] + F[i-1][j])%mod; } inline LL solve(int r,int n) { LL ans=1; while(n!=1) { int cnt=0,p=LP[n]; while(n%p==0) n/=p,cnt++; ans=(ans*F[r][cnt])%mod; } return ans; } int main() { seive();precalc(); int q;si(q); int r,n; while(q--) { si(r);si(n); lldout(solve(r,n)); } return 0; }
757
F
Team Rocket Rises Again
It's the turn of the year, so Bash wants to send presents to his friends. There are $n$ cities in the Himalayan region and they are connected by $m$ bidirectional roads. Bash is living in city $s$. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. \textbf{Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city}. He also wants to send it to them as soon as possible. He finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of $1$ meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash. They do this by destroying exactly one of the other $n - 1$ cities. This implies that \textbf{the friend residing in that city dies, so he is unhappy as well}. Note that \textbf{if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route}. \textbf{Please also note that only friends that are waiting for a gift count as unhappy, even if they die.} Since Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city.
Expected complexity: $O((N+M)\cdot l o g N)$ Main idea: Building Dominator tree on shortest path DAG. First of all, we run Dijkstra's shortest path algorithm from $s$ as the source vertex and construct the shortest path DAG of the given graph. Note that in the shortest path DAG, the length of any path from $s$ to any other node $x$ is equal to the length of the shortest path from $s$ to $x$ in the given graph. Now, let us analyze what the function $f(s, x)$ means. It will be equal to the number of nodes $u$ such that every path from $s$ to $u$ passes through node $x$ in the shortest path DAG, such that on removing node $x$ from the DAG, there will be no path from $s$ to $u$. In other words, we want to find the number of nodes $u$ that are dominated by node $x$ considering $s$ as the sources vertex in the shortest path DAG. This can be calculated by building dominator tree of the shortest path DAG considering $s$ as the source vertex. A node $u$ is said to dominate a node $w$ wrt source vertex $s$ if all the paths from $s$ to $w$ in the graph must pass through node $u$. You can read more about dominator tree here. Once the dominator tree is formed, the answer for any node $x$ is equal to the number of nodes in the subtree of $x$ in the tree formed. Another approach for forming dominator tree is by observing that the shortest path directed graph formed is a DAG i.e. acyclic. So suppose we process the nodes of the shortest path dag in topological order and have a dominator tree of all nodes from which we can reach $x$ already formed. Now, for the node $x$, we look at all the parents $p$ of $x$ in the DAG, and compute their LCA in the dominator tree built till now. We can now attach the node $x$ as a child of the LCA in the tree.
[ "data structures", "graphs", "shortest paths" ]
2,800
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <string> #include <map> #include <set> #include <cassert> using namespace std; #define rep(i,a,n) for (int i=a;i<n;i++) #define per(i,a,n) for (int i=n-1;i>=a;i--) #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second #define SZ(x) ((int)(x).size()) typedef vector<int> VI; typedef long long ll; typedef pair<int,int> PII; const ll mod=1000000007; ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;} // head typedef std::vector<PII> VPII; const int N=201000; VPII e[N]; ll dis[N]; int vis[N]; set<pair<ll,int> > hs; int ord[N],sz[N],dep[N]; const ll inf=1ll<<60; void dijkstra(int S,int n) { rep(i,1,n+1) dis[i]=inf,vis[i]=0; dis[S]=0; rep(i,1,n+1) hs.insert(mp(dis[i],i)); rep(i,0,n) { int u=hs.begin()->se; hs.erase(hs.begin()); vis[u]=1; ord[i]=u; rep(j,0,SZ(e[u])) { int v=e[u][j].fi; if (dis[v]>dis[u]+e[u][j].se) { hs.erase(mp(dis[v],v)); dis[v]=dis[u]+e[u][j].se; hs.insert(mp(dis[v],v)); } } } } int n,m,s,u,v,w,p[N][22]; #define LOGN 20 int lca(int u,int v) { if (dep[u]>dep[v]) swap(u,v); per(i,0,LOGN) if (dep[p[v][i]]>=dep[u]) v=p[v][i]; if (u==v) return u; per(i,0,LOGN) if (p[v][i]!=p[u][i]) u=p[u][i],v=p[v][i]; return p[u][0]; } int main() { scanf("%d%d%d",&n,&m,&s); rep(i,0,m) { scanf("%d%d%d",&u,&v,&w); e[u].pb(mp(v,w)); e[v].pb(mp(u,w)); } dijkstra(s,n); p[s][0]=0; dep[s]=1; rep(i,1,n) { int d=-1; u=ord[i]; for (auto p:e[u]) { if (dis[p.fi]+p.se==dis[u]) { if (d==-1) d=p.fi; else d=lca(d,p.fi); } } if (dis[u]>(1ll<<50)) assert(d==-1); p[u][0]=d; dep[u]=dep[d]+1; rep(j,1,21) p[u][j]=p[p[u][j-1]][j-1]; } rep(i,1,n+1) sz[i]=1; int ret=0; per(i,1,n) { u=ord[i]; sz[p[u][0]]+=sz[u]; if (dis[u]<=(1ll<<50)) ret=max(ret,sz[u]); } printf("%d\n",ret); }
757
G
Can Bash Save the Day?
Whoa! You did a great job helping Team Rocket who managed to capture all the Pokemons sent by Bash. Meowth, part of Team Rocket, having already mastered the human language, now wants to become a master in programming as well. He agrees to free the Pokemons if Bash can answer his questions. Initially, Meowth gives Bash a weighted tree containing $n$ nodes and a sequence $a_{1}, a_{2}..., a_{n}$ which is a permutation of $1, 2, ..., n$. Now, Mewoth makes $q$ queries of one of the following forms: - 1 l r v: meaning Bash should report $\sum_{i=1}^{r}d i s t(a_{i},v)$, where $dist(a, b)$ is the length of the shortest path from node $a$ to node $b$ in the given tree. - 2 x: meaning Bash should swap $a_{x}$ and $a_{x + 1}$ in the given sequence. This new sequence is used for later queries. Help Bash to answer the questions!
Expected complexity: $\ O((N+Q)\cdot l o g N)$ Main idea: Making the Centroid Tree Persistent. First let's try to solve a much simpler problem given as follows. Question: Given a weighted tree, initially all the nodes of the given tree are inactive. We need to support the following operations fast : $Query v$ : Report the sum of distances of all active nodes from node $v$ in the given tree. $Activate v$ : Mark node $v$ to be an active node. Solution: The above problem can be easily solved by a fairly standard technique called Centroid Decomposition. You can read more about here Solution Idea Each query of the form $(L R v)$ can be divided into two queries of form $(1 R v)$ $-$ $(1 L - 1 v)$. Hence it is sufficient if we can support the following query: $(i v)$ : Report the answer to query $(1 i v)$ To answer a single query of the form $(i v)$ we can think of it as what is the sum of distance of all active nodes from node $v$, if we consider the first $i$ nodes to be active. Hence initially if we can preprocess the tree such that we activate nodes from $1$ to $n$ and after each update, store a copy of the centroid tree, then for each query $(i v)$ we can lookup the centroid tree corresponding to $i$, which would have the first $i$ nodes activated, and query for node $v$ in $O(l o g N)$ time by looking at it's ancestors. To store a copy of the centroid tree for each $i$, we need to make it persistent. Persistent Centroid Tree : Key Ideas Important thing to note is that single update in the centroid tree affects only the ancestors of the node in the tree. Since height of the centroid tree is $O(l o g N)$, each update affects only $O(l o g N)$ other nodes in the centroid tree. The idea is very similar to that of a persistent segment tree BUT unlike segtree, here each node of the centroid tree can have arbitrarily many children and hence simply creating a new copy of the affected nodes would not work because linking them to the children of old copy would take ${\cal O}(n u m b e r\ o f\ c h i l d r e n)$ for each affected node and this number could be as large as $N$, hence it could take $O(N)$ time in total ! Binarizing the Input Tree To overcome the issue, we convert the given tree $T$ into an equivalent binary tree $T'$ by adding extra dummy nodes such that degree of each node in the transformed tree $T'$ is $< = 3$, and the number of dummy nodes added is bounded by $O(N)$. The dummy nodes are added such that the structure of the tree is preserved and weights of the edges added are set to $0$. To do this, consider a node $x$ with degree $d > 3$ and let $c_{1}, c_{2}...c_{d}$ be it's adjacent nodes. Add a new node $y$ and change the edges as follows : Delete the edges $(x - c_{3})$, $(x - c_{4})$ $...$ $(x - c_{d})$ and add the edge $(x - y)$ such that degree of node $x$ reduces to $3$ from $d$. Add edges $(y - c_{3})$, $(y - c_{4})$ $...$ $(y - c_{d})$ such that degree of node $y$ is $d - 1$. Recursively call the procedure on node $y$. Delete the edges $(x - c_{3})$, $(x - c_{4})$ $...$ $(x - c_{d})$ and add the edge $(x - y)$ such that degree of node $x$ reduces to $3$ from $d$. Add edges $(y - c_{3})$, $(y - c_{4})$ $...$ $(y - c_{d})$ such that degree of node $y$ is $d - 1$. Recursively call the procedure on node $y$. Since degree of node $y$ is $d - 1$ instead of original degree $d$ of node $x$, it can be proved that we need to add at most $O(N)$ new nodes before degree of each node in the tree is $< = 3$. Conclusion Hence we perform centroid decomposition of this transformed tree $T'$. The centroid tree formed would have the following properties. The height of the centroid tree is $O(l o g N)$ Each node in the centroid tree has $ \le 3$ children. Now we can easily make this tree persistent by path-copying approach. To handle the updates, Way-1 : Observe that swapping $A[i]$ and $A[i + 1]$ would affect only the $i'th$ persistent centroid tree, which can be rebuilt from the tree of $i - 1$ by a single update query. In this approach, for each update we add $O(l o g N)$ new nodes. See author's code below for more details. Way-2 : First we go down to the lca of $A[x]$ and $A[x + 1]$ in the $x$'th persistent tree, updating the values as we go. Now, let $c_{l}$ be the child of lca which is an ancestor of $A[x]$, and let $c_{r}$ be the child which is an ancestor of $A[x + 1]$. Now, we replace $c_{r}$ of $x$'th persistent tree with $c_{r}$ of $(x + 1)$'th persistent tree. Similarly, we replace $c_{l}$ of $x + 1$'th persistent tree with $c_{l}$ of $x$'th persistent tree. So now $A[x + 1]$ is active in $x$'th persistent tree and both $A[x]$ and $A[x + 1]$ are active in $(x + 1)$'th persistent tree.To deactivate $A[x]$ in $x$'th persistent tree we replace $c_{l}$ of $x$'th persistent tree with $c_{l}$ of $(x - 1)$'th persistent tree. Hence in this approach we do not need to create new $O(l o g N)$ nodes for each update.
[ "data structures", "divide and conquer", "graphs", "trees" ]
3,400
//Toshad Salwekar #include<bits/stdc++.h> #define f(i,a,n) for(int i=a;i<n;i++) #define S second #define F first #define Sc(n) scanf("%lld",&n) #define scc(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define sp(a) scanf("%lld %lld",&a.first,&a.second) #define pb push_back #define mp make_pair #define lb lower_bound #define ub upper_bound #define all(a) a.begin(),a.end() #define sc(n) scanf("%d",&n) #define It iterator #define SET(a,b) memset(a,b,sizeof(a)) #define DRT() int t; cin>>t; while(t--) // inbuilt functions // __gcd, __builtin_ffs, (returns least significant 1-bit, __builtin_ffsll(1)=1) // __builtin_clz, (returns number of leading zeroes in // __builtin_popcount, using namespace std; typedef long long LL; typedef pair<int,LL> PII; typedef vector<int> vi; #define tr(container, it) for(__typeof(container.begin()) it = container.begin(); it != container.end(); it++) #define trv(s,it) for(auto it:s) #define TRACE #ifdef TRACE #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } #else #define trace(...) #endif #define N 400005 #define LOGN 20 const int MAX = N*LOGN; const int MOD = (1<<30); int cn[N],nn,par[N],arr[N],centroid,C,tot,anc[N]; LL dis[LOGN][N]; vector<PII> tree[N]; bool mark[N]; stack<int> st; struct node { int id,cn,len; LL sum,psum; node* child[4]; }*pers[N]; node BUFF[MAX]; int buf_len; int dfs1(int i,int p) { int r=1,mx=0,t; for(auto it:tree[i]) if(it.F!=p && !mark[it.F]) r+=dfs1(it.F,i); cn[i]=r; return r; } int dfs2(int i,int p,int num) { for(auto it:tree[i]) if(cn[it.F]>num/2 && !mark[it.F] && it.F!=p) return dfs2(it.F,i,num); return i; } void dfs(int i,int p,LL d) { for(auto it:tree[i]) if(it.F!=p && !mark[it.F]) dfs(it.F,i,d+it.S); dis[C][i]=d; } void dec(int root, node* p,int c) { dfs1(root,root); int cen=dfs2(root,root,cn[root]); //cen is centroid of current subtree C=c; dfs(cen,cen,0LL); mark[cen]=1; node* tmp= BUFF + buf_len++; tmp->id=cen; tmp->cn=0; tmp->len=0; tmp->sum=0; if(p!=NULL) { p->child[p->len++]=tmp; par[cen]=p->id; } else { pers[0]=tmp; //This means cen is the centroid centroid=cen; } for(auto it:tree[cen]) if(!mark[it.F]) dec(it.F,tmp,c+1); } node* persist(node* root, int i,int l) { node* tmp= BUFF + buf_len++; tmp->id=root->id; tmp->sum=root->sum + dis[l][i]; if(l) tmp->psum=root->psum + dis[l-1][i]; tmp->cn=root->cn + 1; tmp->len=0; f(j,0,root->len) if(!st.empty() && (root->child[j])->id==st.top()) { st.pop(); tmp->child[tmp->len++]=persist(root->child[j],i,l+1); } else tmp->child[tmp->len++]=root->child[j]; return tmp; } LL query(node* root, int i,int l) { LL ans=0; ans+=(root->cn)*dis[l][i]+root->sum; // Add all nodes in range which are in subtree(in centroid tree) of current node f(j,0,root->len) if(!st.empty() && root->child[j]->id==st.top()) { st.pop(); ans-=(root->child[j]->psum)+(root->child[j]->cn)*dis[l][i]; //Subtract all nodes which will be considered in the child(i.e., they are ans+=query(root->child[j],i,l+1); // in same subtree as the query node). } return ans; } void binarise(unordered_map<int,LL> &add,int i,PII p,bool fl) { unordered_map<int,LL> tmp; mark[i]=1; if(fl) // fl=1 for those nodes which were not in original tree { add.erase(p.F); tree[i].pb(p); tree[i].pb(*(add.begin())); add.erase(add.begin()); if(add.size()>1) // Need to create more nodes { tree[i].pb(mp(tot++,0LL)); binarise(add,tot-1,mp(i,0LL),1); } else { tree[i].pb(*(add.begin())); binarise(tmp,tree[i][2].F,mp(i,tree[i][2].S),0); } binarise(tmp,tree[i][1].F,mp(i,tree[i][1].S),0); } else if(tree[i].size()>3) { int t=0;bool fl=0; if(tree[i][t].F==p.F) t++; f(j,t,tree[i].size()) if(mark[tree[i][j].F] && tree[i].size()==4) // This means that tree[i][j].F is the parent in original tree fl=1; if(fl) // Only has { f(j,0,tree[i].size()) if(tree[i][j]!=p && !mark[tree[i][j].F]) binarise(tmp,tree[i][j].F,mp(i,tree[i][j].S),0); else if(mark[tree[i][j].F]) tree[i][j]=p; return; } if(mark[tree[i][t].F]) t++; binarise(tmp,tree[i][t].F,mp(i,tree[i][t].S),0); //t represents the child which will stay the child of this node. f(j,0,tree[i].size()) if(j==t); else if(!mark[tree[i][j].F] && tree[i][j].F!=p.F) tmp.insert(tree[i][j]); else if(mark[tree[i][j].F]) //Replace original parent with new parent tree[i][j]=p; PII tm=tree[i][t]; tree[i].clear(); if(i!=1) // 1 is root. For all others, add parent. tree[i].pb(p); tree[i].pb(tm); tree[i].pb(mp(tot++,0LL)); // Add new extra node binarise(tmp,tot-1,mp(i,0LL),1); } else f(j,0,tree[i].size()) if(tree[i][j]!=p && !mark[tree[i][j].F]) binarise(tmp,tree[i][j].F,mp(i,tree[i][j].S),0); else if(mark[tree[i][j].F]) //Replace original with new parent tree[i][j]=p; } int main() { int n,q; LL a,b,c; cin>>n>>q; tot=n+1; f(i,1,n+1) sc(arr[i]); f(i,1,n) { scc(a,b,c); tree[a].pb(mp(b,c)); tree[b].pb(mp(a,c)); } unordered_map<int,LL> stmp; binarise(stmp,1,mp(0,0LL),0); SET(mark,0); dec(1,NULL,0); f(i,1,n+1) { int p=arr[i]; while(p!=centroid) //push all nodes to be added in a stack { st.push(p); p=par[p]; } pers[i]=persist(pers[i-1],arr[i],0); } LL an = 0; f(i,1,q+1) { Sc(a); Sc(b); if(a==1) { Sc(c); Sc(a); b = b ^ an; c = c ^ an; a = a ^ an; int p=a; an=0; while(p!=centroid) //push all nodes to be queried in a stack { st.push(p); p=par[p]; } an-=query(pers[b-1],a,0); p=a; while(p!=centroid) //push all nodes to be queried in a stack { st.push(p); p=par[p]; } an+=query(pers[c],a,0); printf("%lld\n",an); an %= MOD; } else { b = b ^ an; int p=arr[b],lca=centroid,h=centroid; while(p!=centroid) { anc[p]=i; //mark all ancestors of arr[b] p=par[p]; } p=arr[b+1]; while(p!=centroid) { if(anc[p]==i) { lca=p; break; } h=p; // h is the highest ancestor of arr[b+1] which is not an ancestor of arr[b] p=par[p]; } node *rt1=pers[b], *rt2=pers[b+1], *rt=pers[b-1]; int l=0,k=-1; while(rt->id!=lca) //traverse down to lca in all 3 centroid trees. { rt1->sum -= dis[l][arr[b]] - dis[l][arr[b+1]]; if(l) rt1->psum -= dis[l-1][arr[b]] - dis[l-1][arr[b+1]]; l++; f(j,0,rt1->len) if(anc[rt1->child[j]->id]==i) { rt1=rt1->child[j]; break; } f(j,0,rt2->len) if(anc[rt2->child[j]->id]==i) { rt2=rt2->child[j]; break; } f(j,0,rt->len) if(anc[rt->child[j]->id]==i) { rt=rt->child[j]; break; } } rt1->sum-=dis[l][arr[b]]-dis[l][arr[b+1]]; //update lca too if(l) rt1->psum-=dis[l-1][arr[b]]-dis[l-1][arr[b+1]]; /* This is the swapping part. * b1child represents the child containing arr[b], * b2child represents the child containing arr[b+1] and * bchild represents the child containing arr[b] in persistent centroid tree of first b-1 elements * The difference between b1child and bchild is that in b1child the ans due to arr[b] is considered, but it is not so in bchild. * Now we replace b1child with bchild and add b2child in pers[b], so that in pers[b], arr[b+1] is now active and not arr[b]. * */ node *b1child=NULL,*b2child=NULL,*bchild=NULL; f(j,0,rt->len) //find bchild It may not exist if arr[b] = lca if(anc[rt->child[j]->id]==i) bchild=rt->child[j]; f(j,0,rt1->len) if(anc[rt1->child[j]->id]==i) //find b1child. It may not exist if arr[b] = lca { b1child=rt1->child[j]; k=j; } int vv=0; if(b1child!=NULL) // vv is used to handle the case where b1child = NULL vv=b1child->id; f(j,0,rt2->len) if(rt2->child[j]->id==h) //find b2child. It may not exist if arr[b+1] = lca b2child=rt2->child[j]; else if(rt2->child[j]->id==vv) rt2->child[j]=b1child; if(k>=0) //Again, check if b1child exists. rt1->child[k]=bchild; f(j,0,rt1->len) if(rt1->child[j]->id==h) rt1->child[j]=b2child; swap(arr[b],arr[b+1]); } } }
758
A
Holiday Of Equality
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are $n$ citizens, the welfare of each of them is estimated as the integer in $a_{i}$ burles (burle is the currency in Berland). You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.
As it's impossible to decrease numbers, we have to increase them to at least $max(a_{1}, a_{2}, ..., a_{n})$. If all the numbers are already equal to $max(a_{1}, a_{2}, ..., a_{n})$ then there is no need to increase any of them as it will cost extra operations. So you should find $max(a_{1}, a_{2}, ..., a_{n})$ using one iteration over the array. Then iterate one more time summing up differences between $a_{i}$ and maximum. And the answer is $\textstyle\sum_{i=1}^{n}m a x-a_{i}$. Overall complexity - $O(n)$.
[ "implementation", "math" ]
800
null
758
B
Blown Garland
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland. Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is working. It is known that the garland contains light bulbs of four colors: red, blue, yellow and green. The garland is made as follows: if you take any four consecutive light bulbs then there will not be light bulbs with the same color among them. For example, the garland can look like "RYBGRYBGRY", "YBGRYBGRYBG", "BGRYB", but can not look like "BGRYG", "YBGRYBYGR" or "BGYBGY". Letters denote colors: 'R' — red, 'B' — blue, 'Y' — yellow, 'G' — green. Using the information that for each color at least one light bulb still works count the number of dead light bulbs of each four colors.
Four consecutive bulbs should not be of the same color, and it is four possible colors, so the color of the fifth bulb is the same as the first bulb has, the color of the sixth is the same as the second bulb has, it means that the color of the $n$-th bulb equals the color of the $(n - 4)$-th bulb. Thus, the coordinates of all bulbs of the same color equal in module $4$. According to the conditions of the problem the coordinate of at least one light bulb of each color is given, so we can restore the garland and by one pass count the number of blown bulbs. By one pass we learn how numbers in module $4$ correspond to the colors. By the second pass we know the place of the bulb and count the number of blown bulbs of each color. The asymptotic behavior of the solutions is - O(n). There is also a second solution: You can just fix order of first four light bulbs by bruteforce (there is only $4! = 24$ variants), checking the conformity of each option of the given garland. By finding the color of the first four bulbs we easily recreate the garland with working lights and count the number of blown bulbs. At worst this decision will work for $24 \cdot n$.
[ "brute force", "implementation", "number theory" ]
1,100
null
758
C
Unfair Poll
On the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others. Seating in the class looks like a rectangle, where $n$ rows with $m$ pupils in each. The teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order of their seating, then she continues to ask pupils from the next row. If the teacher asked the last row, then the direction of the poll changes, it means that she asks the previous row. The order of asking the rows looks as follows: the $1$-st row, the $2$-nd row, $...$, the $n - 1$-st row, the $n$-th row, the $n - 1$-st row, $...$, the $2$-nd row, the $1$-st row, the $2$-nd row, $...$ The order of asking of pupils on the same row is always the same: the $1$-st pupil, the $2$-nd pupil, $...$, the $m$-th pupil. During the lesson the teacher managed to ask exactly $k$ questions from pupils in order described above. Sergei seats on the $x$-th row, on the $y$-th place in the row. Sergei decided to prove to the teacher that pupils are asked irregularly, help him count three values: - the maximum number of questions a particular pupil is asked, - the minimum number of questions a particular pupil is asked, - how many times the teacher asked Sergei. If there is only one row in the class, then the teacher always asks children from this row.
Let's learn to count $f(x, y)$ - the number of questions which were asked to the pupil in the $x$-th row, at the $y$-th place in the order. Note that the process of asking is periodic. During one period children were asked in the following order: the pupil from the first row who seats at the first table; the pupil from the first row who seats at the second table; the pupil from the first row who seats at the $...$ table; the pupil from the first row who seats at the $m$ table; the pupil from the second row who seats at the first table; the pupil from the second row who seats at the second table; the pupil from the second row who seats at the $...$ table; the pupil from the second row who seats at the $m$ table; the pupil from the $...$ row who seats at the $...$ table; the pupil from the $n - 1$ row who seats at the first table; the pupil from $n - 1$ row who seats at the second table; the pupil from the $n - 1$ row who seats at the $...$ table; the pupil from the $n - 1$ row who seats at the $m$ table; the pupil from the $n$ row who seats at the first table; the pupil from the $n$ row who seats at the second table; the pupil from the $n$ row who seats at the $...$ table; the pupil from the $n$ row who seats at the $m$ table; the pupil from the $n - 1$ row who seats at the first table; the pupil from the $n - 1$ row who seats at the second table; the pupil from the $n - 1$ row who seats at the $...$ table; the pupil from the $n - 1$ row who seats at the $m$ table; the pupil from the $...$ row who seats at the $...$ table; the pupil from the second row who seats at the first table; the pupil from the second row who seats at the second table; the pupil from the second row who seats at the $...$ table; the pupil from the second row who seats at the $m$ table. Thus, during one period $T = n \cdot m + (n - 2) \cdot m$ pupils who seats at the outer rows will be asked once, others will be asked twice. If $n = 1$, then $T = m$. The number of full periods equals $\left\lfloor{\frac{k}{T}}\right\rfloor$. The remaining questions are $k$ $mod$ $T$ $ \le T$, so we can only make poll on the remaining questions for the $O(n \cdot m)$ or for individual $x$ and $y$ print the formula. Thus, $f(x, y)$ can be seen as $O(n \cdot m)$ or as $O(1)$. On what places are people who may be asked more times than the other? Firstly, this is the first row and the first table, because the poll begins from it. Secondly, this is the second row and the first table, because the poll of the central, not outer part of a class at the right side, begins from it. Thirdly, the $n - 1$ row and the first place because the poll of the central, not outer part of a class at the left side, begins from it. The maximum number of asked questions to one pupil equals $max(f(1, 1), f(2, 1), f(n - 1, 1))$. The minimum number of asked questions to one pupil equals $f(n, m)$, because the pupil who seats on the last row and at the last table will be asked less than others. Thus, we have decisions with the asymptotic $O(n \cdot m)$ or $O(1)$.
[ "binary search", "constructive algorithms", "implementation", "math" ]
1,700
null
758
D
Ability To Convert
Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter $A$ he will write the number $10$. Thus, by converting the number $475$ from decimal to hexadecimal system, he gets $11311$ ($475 = 1·16^{2} + 13·16^{1} + 11·16^{0}$). Alexander lived calmly until he tried to convert the number back to the decimal number system. Alexander remembers that he worked with little numbers so he asks to find the minimum decimal number so that by converting it to the system with the base $n$ he will get the number $k$.
Let's compare answers for numbers $k$ and $\left|{\frac{k}{10}}\right|$, that is $k$ without the rightmost digit. Note that for any $x$ number $\textstyle{\left|{\frac{x}{10}}\right|}$ is either contains less substrings (valid digits in base-$n$ numeric system) or it's possible to decrease value of the last substring of number $x$. That proves that partition of number without the rightmost digit isn't worse than partition of the number itself. Thus, greedy strategy will work. On each step take the longest suffix of a string as the last base-$n$ digit and proceed to same task for string with this suffix excluded. Repeat until the string isn't empty. Check carefully that the suffix is a number less than $n$ and also doesn't have any leading zeros except for the case when it's equal to zero. Overall complexity - $O(k)$, where $k$ - length of input string.
[ "constructive algorithms", "dp", "greedy", "math", "strings" ]
2,000
null
758
E
Broken Tree
You are given a tree that has $n$ vertices, which are numbered from $1$ to $n$, where the vertex number one is the root. Each edge has weight $w_{i}$ and strength $p_{i}$. Botanist Innokentiy, who is the only member of the jury of the Olympiad in Informatics, doesn't like broken trees. The tree is broken if there is such an edge the strength of which is less than the sum of weight of subtree's edges to which it leads. It is allowed to reduce weight of any edge by arbitrary integer value, but then the strength of its edge is reduced by the same value. It means if the weight of the edge is $10$, and the strength is $12$, then by the reducing the weight by $7$ its weight will equal $3$, and the strength will equal $5$. It is not allowed to increase the weight of the edge. Your task is to get the tree, which is not broken, by reducing the weight of edges of the given tree, and also all edged should have the positive weight, moreover, the total weight of all edges should be as large as possible. It is obvious that the strength of edges can not be negative, however it can equal zero if the weight of the subtree equals zero.
First, let's calculate min and max weight for subtrees of each vertex. Minimal weight of a subtree is sum of minimal weights of all adjacent to the root of current subtree subtrees and sum of weights of all outgoing edges reduced in weight to minimal possible. Thus, minimal weight is $d p m i n_{x}=\sum_{i=1}^{n_{x}}d p m i n_{y_{x,i}}+w_{x,i}-m i n(p_{x,i}-d p m i n_{y_{x,i}},w_{x,i}-1)$, where $x$ -subtree root, $n_{x}$ -number of outgoing edges from $x$, $y_{x, i}$ - each adjacent to $x$ vertex, $p_{x, i}$ - its strength, $w_{x, i}$ - its weight. Note that minimal weight should be less or equal to strength of incoming edge. If this condition isn't satisfied for at least one subtree then the answer is $- 1$. Maximal weight of a subtree is sum of maximal weights of all adjacent to the root of current subtree subtrees and sum of weights of all outgoing edges. Note that this maximum should stay in such boundaries that the tree remains unbroken. So maximal weight should not exceed strength of incoming edge of a root. Therefore, maximum is $d p m a x_{x}=m i n(p_{z,j},\sum_{i=1}^{n_{x}}d p m a x_{y_{x,i}}+w_{x,i})$, where $x$ -subtree root, $p_{z, i}$ - weight of an incoming edge of $x$, that is $j$-th edge outgoing from some vertex $z$, $n_{x}$ -number of outgoing edges from $x$, $y_{x, i}$ - each adjacent to $x$ vertex, $w_{x, i}$ - its weight. After that, let's calculate current weight of every subtree to find difference between actual value and the optimal one. Weight of subtree is sum of weights of all adjacent to the root of current subtree subtrees and sum of weights of all outgoing edges. Then actual weight is $d p W_{x}=\sum_{i=1}^{n_{x}}d p W_{y_{x,i}}+w_{x,i}$, where $x$ -subtree root, $n_{x}$ -number of outgoing edges from $x$, $y_{x, i}$ - each adjacent to $x$ vertex, $w_{x, i}$ - its weight. One dfs from the root of the tree is enough to calculate all these values. Note that $dpmin$, $dpmax$ and $dpW$ are set to $0$ for leaves . $dpmax_{x}$ is maximal possible weight of each subtree, so weight of the whole tree can be reduced to $dpmax_{1}$, it means that weight of subtree of vertex $1$ should be reduced by $dpW_{1} - dpmax_{1}$. Next goal is to learn how to reduce weight of subtree of vertex $x$ by $s$ units. At first, you should reduce weights of subtrees of adjacent to $x$ vertices to their maximum. So after this step $s=s-\sum_{i=1}^{n_{x}}d p W_{y_{x,i}}-d p m a x_{y_{x,i}}$. Then while $s > 0$, reduce weight of each next subtree. If it's still $s > 0$ then reduce weights of outgoing edges from $x$ maintaining unbroken state of tree. This process also takes one dfs. Overall complexity is the complexity of two dfs calls, that is $O(n)$.
[ "dfs and similar", "dp", "graphs", "greedy", "trees" ]
2,600
null
758
F
Geometrical Progression
For given $n$, $l$ and $r$ find the number of distinct geometrical progression, each of which contains $n$ distinct integers not less than $l$ and not greater than $r$. In other words, for each progression the following must hold: $l ≤ a_{i} ≤ r$ and $a_{i} ≠ a_{j}$ , where $a_{1}, a_{2}, ..., a_{n}$ is the geometrical progression, $1 ≤ i, j ≤ n$ and $i ≠ j$. Geometrical progression is a sequence of numbers $a_{1}, a_{2}, ..., a_{n}$ where each term after first is found by multiplying the previous one by a fixed non-zero number $d$ called the common ratio. Note that in our task $d$ may be non-integer. For example in progression $4, 6, 9$, common ratio is $d={\frac{3}{2}}$. Two progressions $a_{1}, a_{2}, ..., a_{n}$ and $b_{1}, b_{2}, ..., b_{n}$ are considered different, if there is such $i$ ($1 ≤ i ≤ n$) that $a_{i} ≠ b_{i}$.
Let $d$ - is the denominator of the progression. $d$ - is the rational number, because all numbers of progression are integers. $d={\frac{\pi}{y}}$,where $x, y$ - are integers, $gcd(x, y) = 1$. Then $a_{n}=a_{1}\cdot{\frac{x^{n-1}}{v^{n-1}}}$. Because all numbers of progression are integers, so $a_{1}\colon y^{n-1}$. Let $b={\frac{a_{1}}{y^{n-1}}}$, then $a_{1} = b \cdot y^{n - 1}$ and $a_{n} = b \cdot x^{n - 1}$. According to the condition of the problem it must be done: $l \le b \cdot y^{n - 1} \le r$ and $l \le b \cdot x^{n - 1} \le r$. Count the number of increasing progressions, it means $d > 1$ ($y < x$). Note that there are decreasing progressions as much as increasing, any decreasing progression - is increasing, but written from right to left. If $y < x$, then $l \le b \cdot y^{n - 1} < b \cdot x^{n - 1} \le r$. Then for certain $x$ and $y$ the number of possible integers $b$ is calculated by the formula $\frac{r}{x^{n-1}}\to\frac{l}{y^{n-1}}$. Let's sort $y$ from $1$ to $n{\overset{n-{\sqrt{r}}}{\sqrt{r}}}$, $x$ from $y + 1$ to $n{\overset{n-{\sqrt{r}}}{\sqrt{r}}}$. Before you add the number of options for the next $x$ and $y$ you need to check that $gcd(x, y) = 1$. Better to count $gcd(x, y)$ using Euclidean algorithm for $O(\log^{3}n)$. Remember that we counted only increasing progressions, the answer would be higher twice. Note that when $n = 1$ this algorithm is meaningless, so it is necessary to separately register the answer, for $n = 1$ it equals $r - l + 1$, it means that you choose one element from $l$ to $r$. Also for $n = 2$ it is necessary to print the formula, any pair of integers is the geometrical progression, so for $n = 2$ the answer equals $(r - l + 1) \cdot (r - l)$, the first integer can be chosen by using $r - l + 1$ ways, the second which is not equal to the first by using $r - l$ ways. Possible asymptotic behavior: $O({\bf\Phi}^{n-{\sqrt{r}}^{2}}\cdot(n+\log^{3}n))$; $O({\bf\Phi}^{n-{\sqrt{T}}^{2}}\cdot(\log n+\log^{3}n))$ - when we make the binary transfer to the degree; $O(n\cdot\ ^{n-1}{\sqrt{r}}+\ "^{n-{\sqrt{r^{2}}}\cdot\log^{3}n)$ - with preliminary count; $O(\log n\cdot\,^{n-1/r}+\ ^{n-1/r^{2}}\cdot109^{3}\,n)$ - with binary preliminary count.
[ "brute force", "math", "number theory" ]
2,400
null
760
A
Petr and a calendar
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: Petr wants to know how many columns his table should have given the month and the weekday of the first date of that month? Assume that the year is non-leap.
Just implement writing dates one by one and keeping current column and row, or use the formula $answer = ((d - 1) + ndays - 1) / 7 + 1$, where $ndays$ is the number of days in the month.
[ "implementation", "math" ]
800
null
760
B
Frodo and pillows
$n$ hobbits are planning to spend the night at Frodo's house. Frodo has $n$ beds standing in a row and $m$ pillows ($n ≤ m$). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have. Frodo will sleep on the $k$-th bed in the row. What is the maximum number of pillows he can have so that every hobbit has at least one pillow, every pillow is given to some hobbit and no one is hurt?
Let's do binary search on the answer. How to check if Frodo can have $x$ pillows or more? We need to calculate the least amount of pillows we need to give to all the hobbits and compare it to m. The number of pillows is minimized if we give $x - 1$ pillows to Frodo's neighbors, $x - 2$ pillows to the hobbits at the distance $2$ from Frodo and so on, until we reach $1$ pillow or until we reach an end of beds row. The total amount of pillows on one side of Frodo can be calculated using a formula. Suppose there are $y$ beds on one side of Frodo. There are two cases: if $y > x - 1$, then the total number of pillows is ${\frac{(x-1)x}{2}}+y-(x-1)$, otherwise the total number of pillows is $\textstyle{\frac{(x-1+x-y)y}{2}}$.
[ "binary search", "greedy" ]
1,500
null
761
A
Dasha and Stairs
On her way to programming school tiger Dasha faced her first test — a huge staircase! The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — the number of steps with even and odd numbers. You need to check whether there is an interval of steps from the $l$-th to the $r$-th $(1 ≤ l ≤ r)$, for which values that Dasha has found are correct.
It's obvious, that if $|a - b| > 1$ - the answer is <<NO>>. <<NO>> answer was also in the case, when $a$ and $b$ are equal to $0$, because according to the statement, such interval should exist. In other cases the answer is <<YES>>. Complexity: $O(1)$.
[ "brute force", "constructive algorithms", "implementation", "math" ]
1,000
null
761
B
Dasha and friends
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation: The track is the circle with length $L$, in distinct points of which there are $n$ barriers. Athlete always run the track in counterclockwise direction if you look on him from above. All barriers are located at integer distance from each other along the track. Her friends the parrot Kefa and the leopard Sasha participated in competitions and each of them ran one lap. Each of the friends started from some integral point on the track. Both friends wrote the distance from their start along the track to each of the $n$ barriers. Thus, each of them wrote $n$ integers in the ascending order, each of them was between $0$ and $L - 1$, inclusively. \begin{center} {\small Consider an example. Let $L = 8$, blue points are barriers, and green points are Kefa's start (A) and Sasha's start (B). Then Kefa writes down the sequence $[2, 4, 6]$, and Sasha writes down $[1, 5, 7]$.} \end{center} There are several tracks in the country, all of them have same length and same number of barriers, but the positions of the barriers can differ among different tracks. Now Dasha is interested if it is possible that Kefa and Sasha ran the same track or they participated on different tracks. Write the program which will check that Kefa's and Sasha's tracks coincide (it means that one can be obtained from the other by changing the start position). Note that they always run the track in one direction — counterclockwise, if you look on a track from above.
Let's add distances between pairs of adjacent barriers of both tracks in arrays and check if it possible to get one of them from another using cycling shift of the elements. Complexity: $O(n^{2})$.
[ "brute force", "implementation", "math" ]
1,300
null
761
C
Dasha and Password
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length $n$ which satisfies the following requirements: - There is at least one digit in the string, - There is at least one lowercase (small) letter of the Latin alphabet in the string, - There is at least one of three listed symbols in the string: '#', '*', '&'. Considering that these are programming classes it is not easy to write the password. For each character of the password we have a fixed string of length $m$, on each of these $n$ strings there is a pointer on some character. The $i$-th character displayed on the screen is the pointed character in the $i$-th string. Initially, all pointers are on characters with indexes $1$ in the corresponding strings (all positions are numbered starting from one). During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index $1$ to the left, it moves to the character with the index $m$, and when we move it to the right from the position $m$ it moves to the position $1$. You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.
Let's iterate the string, where we want to get a digit to the password, then the string, where we'll get a letter to the password and the string, where we'll get one of the characters '&', '*', '#'. Obviously, in the other strings we can pick any character, so we only need to compute minimal number of moves we have to do to get corresponding characters in fixed strings. We can do it just by iterating that strings. Complexity: $O(n^{3} * m)$.
[ "brute force", "dp", "implementation" ]
1,500
null
761
D
Dasha and Very Difficult Problem
Dasha logged into the system and began to solve problems. One of them is as follows: Given two sequences $a$ and $b$ of length $n$ each you need to write a sequence $c$ of length $n$, the $i$-th element of which is calculated as follows: $c_{i} = b_{i} - a_{i}$. About sequences $a$ and $b$ we know that their elements are in the range from $l$ to $r$. More formally, elements satisfy the following conditions: $l ≤ a_{i} ≤ r$ and $l ≤ b_{i} ≤ r$. About sequence $c$ we know that all its elements are distinct. Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence $a$ and the compressed sequence of the sequence $c$ were known from that test. Let's give the definition to a compressed sequence. A compressed sequence of sequence $c$ of length $n$ is a sequence $p$ of length $n$, so that $p_{i}$ equals to the number of integers which are less than or equal to $c_{i}$ in the sequence $c$. For example, for the sequence $c = [250, 200, 300, 100, 50]$ the compressed sequence will be $p = [4, 3, 5, 2, 1]$. Pay attention that in $c$ all integers are distinct. Consequently, the compressed sequence contains all integers from $1$ to $n$ inclusively. Help Dasha to find any sequence $b$ for which the calculated compressed sequence of sequence $c$ is correct.
Let's match each element of $a$ interval of values, which corresponding element of $c$ could take, i.e for $i$-th element interval $[l - a_{i};r - a_{i}]$. Let $pos_{i}$ be the index of element equal to $i$ in permutation $p$. Now you can know, that solving the initial task is reduced to picking a number of each interval, so that this numbers form an increasing sequence in order from $pos_{1}$ to $pos_{n}$. It is easy to know that we can pick the numbers greedily, picking a number that is greater than previous and belongs to current interval. Complexity: $O(n)$.
[ "binary search", "brute force", "constructive algorithms", "greedy", "sortings" ]
1,700
null
761
E
Dasha and Puzzle
Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve. The tree is a non-oriented connected graph without cycles. In particular, there always are $n - 1$ edges in a tree with $n$ vertices. The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane. It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed $10^{18}$ in absolute value.
The answer doesn't exist, when there is a vertex with degree > $4$. We'll use power of two as length of each edge in the tree. Let's dfs our tree and store in the recursion: the direction, where our parent is located (one of four possible), and the length of the edge we'll build from current vertex. Then iterate the new direction, some neighbour of the vertex and continue recursion. The edges will not intersect, except in the verteces, because $2^{0} + 2^{1} + ... + 2^{k} < 2^{k + 1}$. Comment: It's worth noting that it is possible to solve problem for greater $n$, using the fact that nothing depends on the coordinates, only ratios between X and Y coordinates seperatly, so we can compress them. Complexity: $O(n)$.
[ "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
2,000
null
761
F
Dasha and Photos
Dasha decided to have a rest after solving the problem $D$ and began to look photos from previous competitions. Let's call photos as the matrix with the size $n × m$, which consists of lowercase English letters. Some $k$ photos especially interested her, because they can be received from photo-template by painting a rectangular area in a certain color. Let's call such photos special. More formally the $i$-th special photo is received from the photo-template by replacing all characters on some rectangle with upper left corner of the cell with coordinates $(a_{i}, b_{i})$ and lower right corner in the cell with coordinates $(c_{i}, d_{i})$ to the symbol $e_{i}$. Dasha asks you to find the special photo so that the total distance from it to all other special photos is minimum. And calculate this distance. Determine the distance between two photos as the sum of distances between all corresponding letters. The distance between two letters is the difference module of their positions in the alphabet. For example, the distance between letters 'h' and 'm' equals $|8 - 13| = 5$, because the letter 'h' is the 8-th in the alphabet, the letter 'm' is the 13-th.
Let special photo be the matrix, made by changing subrectangle in the initial, and changed submatrix - changed subrectangle itself. Firsly, let's calculate $cnt(x, y, ch)$ - the number of special photos, in which cell (x, y) belongs to changed submatrix, such that cell (x, y) contains character $ch$. It can be done using addition on submatrix in offline. Then, using $cnt$ array, let's compute $f(x, y)$ - sum of the distances from all $k$ photos to initial, in cell (x, y): $f(x,y)=\sum_{i=A}^{Z}|i-a(x,y)|*c n t(x,y,i)$. Let $g(x,y)=\sum_{i=1}^{x}\sum_{i=1}^{y}f(i,j)$ ( $g(x, y)$ - sum of the distances from all $k$ photos to initial on submatrix $(1, 1, x, y)$. Let $cnt'(x, y, ch)$ - the number of special photos, in which cell (x, y) contains character $ch$. Then calculate, similarly to $g(x, y)$, sums $q(x,y,c h)=\sum_{i=1}^{x}\sum_{j=1}^{y}c n t^{\prime}(i,j,c h)$. Now, using dp's alltogether, we can count for some special photo sum of the distances to all other photos : for all cells, except changed submarix, find the distance using $g(x, y)$ and inclusion-exclusion method in $O(1)$. For the cells in changed submatrix, let's iterate the character and find the answer for it similarly. Complexity: $O(d * (N * M + K))$, where $d$ - alphabet power.
[ "brute force", "data structures", "dp", "implementation" ]
2,600
null
762
A
k-th divisor
You are given two integers $n$ and $k$. Find $k$-th smallest divisor of $n$, or report that it doesn't exist. Divisor of $n$ is any such natural number, that $n$ can be divided by it without remainder.
If you find all the small divisors of n that are less than sqrt(n), you can find the rest of them dividing n by the small ones. By the way, this problem is widely known and googlable :) You can, for example, check out this link: http://stackoverflow.com/questions/26753839/efficiently-getting-all-divisors-of-a-given-number
[ "math", "number theory" ]
1,400
null
762
B
USB vs. PS/2
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis! The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options. You have found a price list of a certain computer shop. In it, for $m$ mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once. You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.
Try coming up either with greedy algorithm or with two pointers algorithm. Try to prove the following greedy: in each step we can choose the cheapest remaining mouse. If there is a computer left that has only one type of port suitable for this mouse, plug it there. Else if there is a computer with both types, plug it there. Else discard this mouse. Try to also come up with the two pointers solution. If you cannot, it is described under the next spoiler. Sort all of the USB mouses and all of the PS/2 mouses so that the price is non-descending. Then you will need to buy some prefix of USB mouses and some prefix of PS/2 mouses. Iterate over the number of USB mouses from 0 to their count. Now, the more USB mouses you buy and plug into computers, the less PS/2 mouses you will be able to buy, because the number of computers will only be decreasing. So you should move the first pointer forward, and in every iteration move the second pointer backwards until you reach such amount that it is possible to plug both USB and PC/2 mouses in.
[ "greedy", "implementation", "sortings", "two pointers" ]
1,400
null
762
C
Two strings
You are given two strings $a$ and $b$. You have to remove the minimum possible number of \textbf{consecutive} (standing one after another) characters from string $b$ in such a way that it becomes a subsequence of string $a$. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from $b$ and make it empty. Subsequence of string $s$ is any such string that can be obtained by erasing zero or more characters (\textbf{not necessarily consecutive}) from string $s$.
Try thinking not about erasing a substring from B, but rather picking some number of characters (possibly zero) from the left, and some from the right. Two pointers For every prefix of B, count how big of a prefix of A you will require. Call these values p[i]. Put infinity in the cells where even whole A is not enough. Same for every suffix of B count the length of the required suffix of A. Call these values s[i]. Now try increasing the length of prefix of B, while decreasing the length of the suffix until p[pref_len] + s[suf_len] is less or equal to the length of A.
[ "binary search", "hashing", "strings", "two pointers" ]
2,100
null
762
D
Maximum path
You are given a rectangular table $3 × n$. Each cell contains an integer. You can move from one cell to another if they share a side. Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximum possible.
The toughest thing about this task, is that you can go to the left. Try to come up with something to handle that. Try to prove that in optimal solution you don't need to go more than one cell to the left before coming back.
[ "dp", "greedy", "implementation" ]
2,300
null
762
E
Radio stations
In the lattice points of the coordinate line there are $n$ radio stations, the $i$-th of which is described by three integers: - $x_{i}$ — the coordinate of the $i$-th station on the line, - $r_{i}$ — the broadcasting range of the $i$-th station, - $f_{i}$ — the broadcasting frequency of the $i$-th station. We will say that two radio stations with numbers $i$ and $j$ reach each other, if the broadcasting range of each of them is more or equal to the distance between them. In other words $min(r_{i}, r_{j}) ≥ |x_{i} - x_{j}|$. Let's call a pair of radio stations $(i, j)$ bad if $i < j$, stations $i$ and $j$ reach each other and they are close in frequency, that is, $|f_{i} - f_{j}| ≤ k$. Find the number of bad pairs of radio stations.
Try to come up with a solution where you iterate over each frequency Try to group stations that will be on the left side in a pair in one vector, and stations that will be on the right side in a pair into another. Iterate over each frequncy. Suppose you are now on frequency $i$. Put all radio stations with frequencly $i$ in the $left$ vector, and all radio stations with frequencies $i - k..i + k$ into the $right$ vector. Notice, that the total size of all vectors you get this way is no more than $(2 * k + 2) * n$, because every radiostation will be one time in the $left$ vector and at most $2 * k + 1$ times in the $right$ vector. Now we need to calculate the number of possible pairs where left radio station is from vector $left$ and right radio station is from vector $right$. Sort stations in the $left$ vector by position. Sort stations in the $right$ vector by left bound of their range. Iterate over the stations from the $left$ vector. Now, as you do that, larger and larger prefix of the $right$ vector will have stations with their left bound less or equal to the coordinate of the currently processed station from the $left$ vector. For each new such station you should add 1 to some RSQ structure (easiest is fenwick tree) to the position of this station. Since positions are up to $10^{9}$, you will have to compress the coordinates (for example, use index of station in the sorted order instead of it's coordinate). Can you see how to query this fenwick tree to get the number of stations that match the currently processed station from the $left$ vector?
[ "binary search", "data structures" ]
2,200
null
762
F
Tree nesting
You are given two trees (connected undirected acyclic graphs) $S$ and $T$. Count the number of subtrees (connected subgraphs) of $S$ that are isomorphic to tree $T$. Since this number can get quite large, output it modulo $10^{9} + 7$. Two subtrees of tree $S$ are considered different, if there exists a vertex in $S$ that belongs to exactly one of them. Tree $G$ is called isomorphic to tree $H$ if there exists a bijection $f$ from the set of vertices of $G$ to the set of vertices of $H$ that has the following property: if there is an edge between vertices $A$ and $B$ in tree $G$, then there must be an edge between vertices $f(A)$ and $f(B)$ in tree $H$. And vice versa — if there is an edge between vertices $A$ and $B$ in tree $H$, there must be an edge between $f^{ - 1}(A)$ and $f^{ - 1}(B)$ in tree $G$.
One of the possible ways to make your life easier is to count the number of automorphisms of tree $T$. This way you will be able to first calculate the number of labeled matchings of vertices of tree $T$ to the vertices of tree $S$, and then divide this number by the number of automorphisms. Although solution that I will describe does not use this! :D First, remember that every automorphism has a fixed point. Either a vertex or an edge. This is called center of the tree, and you can find it by first finding the diameter of the tree. It's middle vertex (or an edge, if there are two middle vertices) is the center of the tree. Let's root T at it's center. Now let's enumerate subtrees (rooted ones!) of T in such a way that if two subtress are isomorphic they will receive the same number and vice versa. You can do it in a single dfs processing subtrees bottom-up. These numbers will correspond to different isomorphisms. Now you can do a dp with memoization to calculate for each subtree of S rooted at some directed edge the number of ways to "attach" each of the isomorphisms from above to this subtree. This can be done by going through all immediate children of the currently processed vertex of S and doing a bitmask DP, where bits are immediate children of the root of currently processed isomophism of T. 1 means it is "attached" to some children in S, 0 means not. One of the problems here is that root of current isomorphism of T can have isomorphic children, and if we shuffle how they are attached to children in S we will still receive the same way to cover S with T, so we will calculate some ways twice or more. The solution is to sort children by their isomorphism number and when processing a bitmask, never put 1 to the bit that has a 0 bit to the left that corresponds to the child with the same isomorphism number. This way you will match such children in a fixed order and won't calculate anything unnecessary.
[ "combinatorics", "graphs", "trees" ]
2,800
null
763
A
Timofey and a tree
Each New Year Timofey and his friends cut down a tree of $n$ vertices and bring it home. After that they paint all the $n$ its vertices, so that the $i$-th vertex gets color $c_{i}$. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Take any edge which vertices are colored in different colors. If such edge doesn't exist you can print any vertex, because all the tree is colored in the same color. Otherwise, try to make a root from each of these vertices. Check if is possible with simple dfs. If it succeedes for one of them, print "YES" and this vertex. If it fails for both vertices, the answer is "NO". Indeed, if both of them cannot be the root, they lay in the same subtree and they are colored differently. So the condition isn't fulfilled. The asymptotics of this solution is $O(n + m)$.
[ "dfs and similar", "dp", "dsu", "graphs", "implementation", "trees" ]
1,600
"//Codeforces Round #395 Div2C/Div1A solution\n#include <bits/stdc++.h>\nusing namespace std;\ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\n#define forab(i, a, b) for (int i = (int)(a); i < (int)(b); ++i)\n#define _ cin.tie(0); ios_base::sync_with_stdio(0);\n#define i64 long long\nconst int N = 100010;\nvector<int> g[N];\nint n, curr_color, color[N];\nbool ok;\n\nbool dfs(int v, int parent) {\n ok = ok && (color[v] == curr_color);\n forn(i, g[v].size()) {\n if (g[v][i] != parent)\n dfs(g[v][i], v);\n }\n}\n\nbool solve(int v) {\n int ans = true;\n forn(i, g[v].size()) {\n curr_color = color[g[v][i]];\n ok = true;\n dfs(g[v][i], v);\n ans = ans && ok;\n }\n return ans;\n}\n\nint main() {\n cin >> n;\n forn(i, n - 1) {\n int u, v;\n cin >> u >> v;\n g[u].push_back(v);\n g[v].push_back(u);\n }\n forn(i, n) cin >> color[i + 1];\n int root1 = -1, root2 = -1;\n forab(i, 1, n + 1) {\n for (auto elem : g[i]) {\n if (color[elem] != color[i]) {\n root1 = elem;\n root2 = i;\n }\n }\n }\n if (root1 == -1) {\n cout << \"YES\\n1\";\n return 0;\n }\n bool res1 = solve(root1);\n bool res2 = solve(root2);\n if (res1)\n cout << \"YES\\n\" << root1;\n else if (res2)\n cout << \"YES\\n\" << root2;\n else\n cout << \"NO\";\n return 0;\n}"
763
B
Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane $n$ rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have \textbf{odd} length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in $4$ different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length \begin{center} {\small The picture corresponds to the first example} \end{center}
Let's consider vertical touchings graph, where vertex is rectangle. For each vertex we keep x coordinate of bottom-right angle. While moving to next rectangle it changes by odd number. In this graph doesn't exist cycle of odd length (sum of odd number of odd numbers can't be zero). Similar to this you can see about horizontal touchings. Let's consider two touching rectagles. Sides lengths are odd, so $2*(x\ {\mathrm{mod}}\ 2)+(y\ {\mathrm{mod}}\ 2)$ give different colors for adjacent rectangles, where $x$ is $x$ coordinate of bottom-left angle and $y$ is $y$ coordinate of bottom-left angle.
[ "constructive algorithms", "geometry" ]
2,100
"//Codeforces Round #395 Div2D/Div1B solution\n#include <bits/stdc++.h>\nusing namespace std;\ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\n#define forab(i, a, b) for (int i = (int)(a); i < (int)(b); ++i)\n#define _ cin.tie(0); ios_base::sync_with_stdio(0);\n#define i64 long long\n\nint main() { \n int n;\n printf(\"YES\\n\");\n scanf(\"%d\", &n);\n for(int i = 0; i < n; i++) {\n int x1, y1, x2, y2;\n scanf(\"%d %d %d %d\", &x1, &y1, &x2, &y2);\n printf(\"%d\\n\", ((12 + 2 * (x1 % 2) + (y1 % 2)) % 4) + 1);\n }\n return 0;\n}"
763
C
Timofey and remoduling
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime $m$. Also, Timofey likes to look for arithmetical progressions everywhere. One of his birthday presents was a sequence of \textbf{distinct} integers $a_{1}, a_{2}, ..., a_{n}$. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo $m$, or not. Arithmetical progression modulo $m$ of length $n$ with first element $x$ and difference $d$ is sequence of integers $x, x + d, x + 2d, ..., x + (n - 1)·d$, each taken modulo $m$.
First, let's think about the case when $2n < m$. In this editorial we say that an outcoming sequence is $s, s + d, s + 2d, ..., s + (n - 1)d$ Assume $x$ is the difference of some two elements $a$ and $b$ of $A$ ($x=b-a\mod m$). Let's say that $a$ was on $i$-th place in the sequence and $b$ was on $i + k$-th place. Then $x=k\cdot d\mod m$. On the other hand, we have that $n$ is less then $\textstyle{\frac{m}{2}}$, so $x$ must be difference of exactly $n - k + 1$ pairs of elements of $A$. We can count this value in $O(n\log n)$ time using binary search or in $O(n)$ time using a hashtable. Then we know the value of $k$. After that we calculate the value $x\div k\mod m$ ($m$ is prime so we can use Fermat's little theorem) and then we know the difference of the sequence. Then we just take any element $y$ of $A$ and look on values $y, y + d, y + 2d, ...$, and also on $y - d, y - 2d, ...$. If we can get all of the numbers in $A$ in this way, then we know the first element of the sequence. Otherwise, the answer is NO. If $2n > m$, we just solve the problem for the complement of $A$ in $\mathbb{Z}_{m}$, and then add to the first element value $(m - n)d$. If we had a correct sequence in $A$, then we must have a correct sequence in its complement with the same difference (as long as $m$ is coprime with the difference, the complement is just set of numbers $s + nd, s + (n + 1)d, ..., s + (m - 1)d$).
[ "brute force", "implementation", "math", "number theory" ]
2,600
"//Codeforces Round #395 Div2E/Div1C solution\n#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <cstring>\n#include <string>\n#include <set>\n#include <map>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <algorithm>\n#include <sstream>\n#include <cstdlib>\n#include <cmath>\n#include <random>\n#include <bitset>\n#include <cassert>\n#include <tuple>\n#include <list>\n#include <iterator>\n#include <unordered_set>\n#include <unordered_map>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\n#define mp make_pair\n#define pb push_back\n#define mt make_tuple\n\n#define forn(i, n) for (int i = 0; i < ((int)(n)); ++i)\n#define forrn(i, s, n) for (int i = (int)(s); i < ((int)(n)); ++i)\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n\nconst int INF = 1791791791;\nconst ll INFLL = 1791791791791791791ll;\n\nll pow(ll x, int n, ll m) {\n if (n == 0)\n return 1;\n else if (n & 1)\n return (x * pow(x, n ^ 1, m)) % m;\n else {\n ll t = pow(x, n >> 1, m);\n return (t * t) % m;\n }\n}\n\nll divide(ll a, ll b, ll m) {\n return (a * pow(b, m - 2, m)) % m;\n}\n\nint n;\nll m;\nvector<int> a; // sorted\n\nbool is_good_difference(int d, int& first) {\n int y = a[0];\n int cnt = 0;\n auto it = lower_bound(all(a), y);\n while (it != a.end() && *it == y) {\n y += d;\n if (y >= m)\n y -= m;\n cnt++;\n it = lower_bound(all(a), y);\n }\n y = a[0];\n it = lower_bound(all(a), y);\n while (it != a.end() && *it == y) {\n first = y;\n y -= d;\n if (y < 0)\n y += m;\n cnt++;\n it = lower_bound(all(a), y);\n }\n return cnt == n + 1;\n}\n\nint count_differences(int d) {\n int cnt = 0;\n for (int i = 0; i < n; i++) {\n for (int add = -d; add <= d; add += 2 * d) {\n int y = a[i] + add;\n if (y >= m) y -= m;\n if (y < 0) y += m;\n if (a[i] > y)\n continue;\n auto it = lower_bound(all(a), y);\n if (it != a.end() && *it == y)\n cnt++;\n }\n }\n return cnt;\n}\n\npair<int, int> solve() {\n if (n == 0)\n return make_pair(1, 1);\n if (n == 1)\n return make_pair(a[0], 1);\n sort(all(a));\n int first;\n int difference = a[1] - a[0];\n int k = n - count_differences(difference);\n int d = divide(difference, k, m);\n if (is_good_difference(d, first)) {\n return make_pair(first, d);\n } else {\n return make_pair(-1, -1);\n }\n}\n\nint main() {\n int cn;\n cin >> m >> n;\n cn = n;\n vector<int> c;\n c.resize(n);\n forn(i, n)\n cin >> c[i];\n\n if (n == 1) {\n cout << c[0] << \" 1\" << endl;\n return 0;\n }\n\n pair<int, int> answer(-1, -1);\n\n if (2 * n >= m) {\n sort(all(c));\n vector<int> b;\n for (int i = 0; i < m; i++) {\n auto it = lower_bound(c.begin(), c.end(), i);\n if (it == c.end() || *it != i)\n b.push_back(i);\n }\n n = m - n;\n a = b;\n pair<int, int> now = solve();\n if (now.first > -1) {\n answer.second = now.second;\n answer.first = (now.first + 1ll * n * now.second) % m;\n }\n } else {\n a = c;\n answer = solve();\n }\n \n if (answer.first == -1)\n cout << -1 << endl;\n else\n cout << answer.first << \" \" << answer.second << endl;\n\n return 0;\n}"
763
D
Timofey and a flat tree
Little Timofey has a big tree — an undirected connected graph with $n$ vertices and no simple cycles. He likes to walk along it. His tree is flat so when he walks along it he sees it entirely. Quite naturally, when he stands on a vertex, he sees the tree as a rooted tree with the root in this vertex. Timofey assumes that the \textbf{more} non-isomorphic subtrees are there in the tree, the more beautiful the tree is. A subtree of a vertex is a subgraph containing this vertex and all its descendants. You should tell Timofey the vertex in which he should stand to see the most beautiful rooted tree. Subtrees of vertices $u$ and $v$ are isomorphic if the number of children of $u$ equals the number of children of $v$, and their children can be arranged in such a way that the subtree of the first son of $u$ is isomorphic to the subtree of the first son of $v$, the subtree of the second son of $u$ is isomorphic to the subtree of the second son of $v$, and so on. In particular, subtrees consisting of single vertex are isomorphic to each other.
There are only $2 \cdot (n - 1)$ subtrees in the whole tree: two for each edge. Let's calculate hashes of each of them. We can calculate hash of a subtree, for example, in a following. Let's associate each vertex with a correct bracket sequence. Leaves are associated with "()", other vertices are associated with their sequences according to the following rule. Assume that the children of our vertex are associated with sequences $s_{1}, s_{2}, ..., s_{k}$. Let's sort strings $s_{1}, s_{2}, ..., s_{k}$ in some order, for example, in order of ascending hashes. Then our vertex is associated with sequence $(s_{1s}_{2}... s_{k})$. It's easy to check that isomorphic subtrees are associated with equal sequences and non-isomoriphic are associated with different sequences. Then hash of a subtree is the hash of the sequence associated with the root of the subtree. In this problem we will calculate the polynomial hash because we will need to count the hash of concatenation of several strings knowing only their hash and length. We know hashes for all of the leaves. Let's do a bfs-like algorithm that will greedily count all of the hashes. Let's count $out_{v}$ - number of outer edges for vertex $v$, for which we have already counted hashes of their subtrees. Then we know new hashes in two cases: $o u t_{v}=\operatorname*{deg}_{v}-\rfloor$. Then we can calculate the hash for the inner edge of $v$, for which we don't already know the outer hash in $O(\deg_{v}\log(\deg_{v})$ time. $o u t_{v}=\deg_{v}$. Then we can calculate the hash for all of the inner edges, for which we don't already know it. Let's calculate hashes for all of concatenations of prefixes and suffixes of the sorted array. If we count polynomial hash, we can calculate them knowing only their hashes and length. Then when we calculate the hash for particular edge, we just have to concatenate the prefix and the suffix of our array. This all works in $\deg_{v}\log(\deg_{v})$ time. Now we have to calculate for each vertex $v$ the number of distinct hashes in case $v$ is the root. Let's select some vertex and calculate this number fairly, using dfs and storing for each hash number of its occurrences in a hashtable. Then we go through the tree in order of Euler tour and maintain the hashtable. When we go through edge $u\rightarrow v$, we should add hash of the edge $v\to u$ and remove hash of the edge $v\to u$, other hashes in the hashtable doesn't change. This works in $O(n\log n)$ time.
[ "data structures", "graphs", "hashing", "shortest paths", "trees" ]
2,900
"//Codeforces Round #395 Div1D solution\n#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <cstring>\n#include <string>\n#include <set>\n#include <map>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <algorithm>\n#include <sstream>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <random>\n#include <bitset>\n#include <cassert>\n#include <tuple>\n#include <list>\n#include <iterator>\n#include <unordered_set>\n#include <unordered_map>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\n#define mp make_pair\n#define pb push_back\n#define mt make_tuple\n#define ff first\n#define ss second\n\n#define forn(i, n) for (int i = 0; i < ((int)(n)); ++i)\n#define forrn(i, s, n) for (int i = (int)(s); i < ((int)(n)); ++i)\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n\nconst int INF = 1791791791;\nconst ll INFLL = 1791791791791791791ll;\n\nvector<vector<int> > tree;\nvector<vector<ll> > frw_hash;\nvector<vector<ll> > rev_hash;\nvector<int> num;\n\nvoid get_all(int v, int par, unordered_map<ll, int>& ums) {\n int i = 0;\n for (int u : tree[v]) {\n if (u != par) {\n ums[frw_hash[v][i]]++;\n get_all(u, v, ums);\n }\n i++;\n }\n}\n\nvoid dfs(int v, int par, unordered_map<ll, int>& ums) {\n num[v] = ums.size();\n int i = 0;\n for (int u : tree[v]) {\n if (u != par) {\n ums[frw_hash[v][i]]--;\n if (ums[frw_hash[v][i]] == 0)\n ums.erase(frw_hash[v][i]);\n ums[rev_hash[v][i]]++;\n dfs(u, v, ums);\n ums[rev_hash[v][i]]--;\n if (ums[rev_hash[v][i]] == 0)\n ums.erase(rev_hash[v][i]);\n ums[frw_hash[v][i]]++;\n }\n i++;\n }\n}\n\nconst ll p = 179;\nconst ll mod = 1791791791l;\nconst int maxn = 1e6 + 179;\n\nint main() {\n ll ppows[maxn];\n ppows[0] = 1;\n forrn(i, 1, maxn)\n ppows[i] = (ppows[i - 1] * p) % mod;\n \n int n;\n cin >> n;\n tree.resize(n);\n vector<pair<int, int> > edges;\n forn(i, n - 1) {\n int u, v;\n cin >> u >> v;\n u--; v--;\n tree[u].pb(v);\n tree[v].pb(u);\n edges.pb(mp(u, v));\n edges.pb(mp(v, u));\n }\n\n map<pair<int, int>, int> index;\n forn(i, 2 * n - 2)\n index[edges[i]] = i;\n\n vector<ll> hash_of(edges.size(), -1);\n vector<ll> rem_hh(edges.size(), -1);\n vector<int> sz_of(edges.size(), -1);\n queue<int> q;\n forn(i, n)\n if (tree[i].size() == 1) {\n rem_hh[index[mp(tree[i][0], i)]] = ('(' * p + ')') % mod;\n sz_of[index[mp(tree[i][0], i)]] = 1;\n q.push(index[mp(tree[i][0], i)]);\n }\n vector<int> out(n, 0);\n while (!q.empty()) {\n int a = q.front();\n q.pop();\n if (hash_of[a] != -1)\n continue;\n hash_of[a] = rem_hh[a];\n int v = edges[a].ff;\n out[v]++;\n if (out[v] == (int)tree[v].size() - 1) {\n int u = -1;\n vector<ll> pr_next_hh, next_hh;\n vector<int> pr_szs, szs;\n for (int w : tree[v]) {\n if (hash_of[index[mp(v, w)]] == -1)\n u = w;\n else {\n pr_next_hh.pb(hash_of[index[mp(v, w)]]);\n pr_szs.pb(sz_of[index[mp(v, w)]]);\n }\n }\n vector<int> ind(pr_next_hh.size());\n iota(all(ind), 0);\n sort(all(ind), [&](const int& i, const int& j) -> bool {return pr_next_hh[i] < pr_next_hh[j];});\n forn(i, pr_next_hh.size()) {\n next_hh.pb(pr_next_hh[ind[i]]);\n szs.pb(pr_szs[ind[i]]);\n }\n int i = index[mp(u, v)];\n rem_hh[i] = '(';\n sz_of[i] = 1;\n forn(j, next_hh.size()) {\n rem_hh[i] = (rem_hh[i] * ppows[2 * szs[j]]) % mod;\n rem_hh[i] = (rem_hh[i] + next_hh[j]) % mod;\n sz_of[i] += szs[j];\n }\n rem_hh[i] = (rem_hh[i] * p + ')') % mod;\n q.push(i);\n } else if (out[v] == (int)tree[v].size()) {\n vector<ll> pr_next_hh, next_hh;\n vector<int> pr_szs, szs;\n for (int w : tree[v]) {\n pr_next_hh.pb(hash_of[index[mp(v, w)]]);\n pr_szs.pb(sz_of[index[mp(v, w)]]);\n }\n vector<int> ind(pr_next_hh.size());\n vector<int> rev(pr_next_hh.size());\n iota(all(ind), 0);\n sort(all(ind), [&](const int& i, const int& j) -> bool {return pr_next_hh[i] < pr_next_hh[j];});\n forn(i, pr_next_hh.size()) {\n rev[ind[i]] = i;\n next_hh.pb(pr_next_hh[ind[i]]);\n szs.pb(pr_szs[ind[i]]);\n }\n vector<ll> pref_hh(next_hh.size() + 1, 0);\n pref_hh[0] = '(';\n pref_hh[1] = ('(' * p + next_hh[0]) % mod;\n forrn(i, 1, next_hh.size() + 1) {\n pref_hh[i] = (pref_hh[i - 1] * ppows[2 * szs[i - 1]] + next_hh[i - 1]) % mod;\n }\n pref_hh.pb((pref_hh.back() * p + ')') % mod);\n vector<ll> suf_hh(next_hh.size() + 2, 0);\n vector<int> suf_sz(next_hh.size() + 2, 0);\n suf_hh.back() = ')';\n for (int i = next_hh.size(); i > 0; i--) {\n suf_hh[i] = (suf_hh[i + 1] + next_hh[i - 1] * ppows[2 * suf_sz[i + 1] + 1]) % mod;\n suf_sz[i] = suf_sz[i + 1] + szs[i - 1];\n }\n suf_hh[0] = (suf_hh[1] + '(' * ppows[2 * suf_sz[1] + 1]) % mod;\n suf_sz[0] = suf_sz[1];\n forn(i, next_hh.size()) {\n int u = tree[v][ind[i]];\n if (rem_hh[index[mp(u, v)]] == -1) {\n sz_of[index[mp(u, v)]] = n - sz_of[index[mp(v, u)]];\n rem_hh[index[mp(u, v)]] = (pref_hh[i] * ppows[2 * suf_sz[i + 2] + 1] + suf_hh[i + 2]) % mod;\n q.push(index[mp(u, v)]);\n }\n }\n }\n }\n\n \n frw_hash.resize(n);\n rev_hash.resize(n);\n num.resize(n);\n forn(i, n) {\n for (int v : tree[i]) {\n frw_hash[i].pb(hash_of[index[mp(i, v)]]);\n rev_hash[i].pb(hash_of[index[mp(v, i)]]);\n\t}\n }\n unordered_map<ll, int> ump;\n get_all(0, -1, ump);\n dfs(0, -1, ump);\n\n cout << distance(num.begin(), max_element(all(num))) + 1 << endl;\n return 0;\n}"
763
E
Timofey and our friends animals
After his birthday party, Timofey went to his favorite tree alley in a park. He wants to feed there his favorite birds — crows. It's widely known that each tree is occupied by a single crow family. The trees in the alley form a row and are numbered from $1$ to $n$. Some families are friends to each other. For some reasons, two families can be friends only if they live not too far from each other, more precisely, there is no more than $k - 1$ trees between any pair of friend families. Formally, the family on the $u$-th tree and the family on the $v$-th tree can be friends only if $|u - v| ≤ k$ holds. One of the friendship features is that if some family learns that Timofey is feeding crows somewhere, it notifies about this all friend families. Thus, after Timofey starts to feed crows under some tree, all the families that are friends to the family living on this tree, as well as their friends and so on, fly to the feeding place. Of course, the family living on the tree also comes to the feeding place. Today Timofey came to the alley and noticed that all the families that live on trees with numbers strictly less than $l$ or strictly greater than $r$ have flown away. Thus, it is not possible to pass the information about feeding through them. Moreover, there is no need to feed them. Help Timofey to learn what is the minimum number of trees under which he has to feed crows so that all the families that have remained will get the information about feeding. You are given several situations, described by integers $l$ and $r$, you need to calculate the answer for all of them.
Let's build a segment tree on crow families. Let's save DSU in each vertex, having information about number of components of connectivity on it. In one vertex will be DSU with size $n$. In two vertices will be DSU with size $n / 2$. In four vertices will be DSU with size $n / 4$. It's easy to show that we will store only $O(nlogn)$ values. Let's understand how we can unite segments. Knowing answer (number of components) for [a; b) and [b; c) we can obtain answer for [a; c) in the following way: We can sum answers for for [a; b) and [b; c) and substract number of components, which united during the "gluing". If components become united, there is edge between vertex in one and vertex in another. We have constraint on edge legth: vertex $u$ and vertex $v$ can be connected only if $abs(u - v) \le k$ Then we can easily unite two segments of the segment tree in $O(k^{2})$ time: we just unite some of the $k$ components of families represented in the end of each segment when they are connected by edge. Segment tree can split query in $O(\log n)$ already calculated segments. So we can answer the query in $O(k^{2}\log{n})$ time. Precalc will take nearly $O(n\log n)$.
[ "data structures", "divide and conquer", "dsu" ]
2,900
"//Codeforces Round #395 Div1E solution\n#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <cstring>\n#include <string>\n#include <set>\n#include <map>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <algorithm>\n#include <sstream>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <random>\n#include <bitset>\n#include <cassert>\n#include <tuple>\n#include <list>\n#include <iterator>\n#include <unordered_set>\n#include <unordered_map>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\n#define mp make_pair\n#define pb push_back\n#define mt make_tuple\n#define lb lower_bound\n#define ub upper_bound\n#define ff first\n#define ss second\n\n#define forn(i, n) for (int i = 0; i < ((int)(n)); ++i)\n#define forrn(i, s, n) for (int i = (int)(s); i < ((int)(n)); ++i)\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n\n\nconst int INF = 1791791791;\nconst ll INFLL = 1791791791791791791ll;\n\nclass dsu {\n vector<int> par;\n vector<int> rank;\npublic:\n int cnum;\n dsu() {}\n dsu(int n) {\n cnum = n;\n par.resize(n);\n iota(all(par), 0);\n rank.resize(n, 1);\n }\n int get(int u) {\n if (u != par[u])\n par[u] = get(par[u]);\n return par[u];\n }\n void merge(int u, int v) {\n u = get(u);\n v = get(v);\n if (u == v)\n return;\n cnum--;\n if (rank[u] > rank[v])\n swap(u, v);\n par[u] = v;\n rank[v] = max(rank[v], rank[u] + 1);\n }\n};\n\nclass solve {\n int n, k;\n vector<vector<int> > graph;\n vector<dsu> tree;\n void build(int v, int L, int R) {\n tree[v] = dsu(R - L);\n forrn(i, L, R) {\n for (int u : graph[i]) {\n if (L <= u && u < R)\n tree[v].merge(i - L, u - L);\n }\n }\n if (L != R - 1) {\n build(2 * v + 1, L, (L + R) >> 1);\n build(2 * v + 2, (L + R) >> 1, R);\n }\n }\n vector<tuple<int, int, int> > vertex;\n void get_vertex(int v, int L, int R, int l, int r) {\n if (r <= L || R <= l)\n return;\n else if (l <= L && R <= r)\n vertex.pb(mt(v, L, R));\n else {\n get_vertex(2 * v + 1, L, (L + R) >> 1, l, r);\n get_vertex(2 * v + 2, (L + R) >> 1, R, l, r);\n }\n }\n int different(vector<int> vec) {\n sort(all(vec));\n return distance(vec.begin(), unique(all(vec)));\n }\n int on_two_segments(vector<int> fvec, int fl, int fr, vector<int> svec, int sl, int sr) {\n assert(fr == sl);\n\n vector<int> fcds = fvec;\n sort(all(fcds));\n fcds.resize(distance(fcds.begin(), unique(all(fcds))));\n vector<int> scds = svec;\n sort(all(scds));\n scds.resize(distance(scds.begin(), unique(all(scds))));\n int m = fcds.size();\n \n dsu ds(fcds.size() + scds.size());\n forrn(i, fl, fr) {\n for (int u : graph[i])\n if (sl <= u && u < sr)\n ds.merge(lb(all(fcds), fvec[i - fl]) - fcds.begin(), m + (lb(all(scds), svec[u - sl]) - scds.begin()));\n }\n \n return ds.cnum;\n }\n vector<int> segment_comps(int l, int r) {\n vector<int> ans;\n dsu ds(r - l);\n forrn(i, l, r) {\n for (int u : graph[i])\n if (l <= u && u < r)\n ds.merge(i - l, u - l);\n }\n forrn(i, l, r)\n ans.pb(ds.get(i - l));\n return ans;\n }\npublic:\n solve(int _n, int _k) {\n n = _n; k = _k;\n graph.resize(n);\n tree.resize(4 * n);\n }\n void add_edge(int u, int v) {\n graph[u].pb(v);\n graph[v].pb(u);\n }\n void precalc() {\n build(0, 0, n);\n }\n int compnum(int l, int r) {\n vertex.clear();\n get_vertex(0, 0, n, l, r);\n int cur = 0;\n vector<int> last;\n int cl = l, cr = l;\n for (auto t : vertex) {\n int v = get<0>(t);\n int L = get<1>(t);\n assert(L == cr);\n int R = get<2>(t);\n\n int sl = max(cr - k, cl);\n int sr = min(L + k, R);\n\n int n1 = different(last);\n vector<int> next;\n forrn(i, L, sr)\n next.pb(tree[v].get(i - L));\n int n2 = different(next);\n\n cur = cur + tree[v].cnum - (n1 + n2) + on_two_segments(last, sl, cr, next, L, sr);\n cr = R;\n if (R - L >= k) {\n last.clear();\n forrn(i, R - k, R)\n last.pb(tree[v].get(i - L));\n } else\n last = segment_comps(max(cl, cr - k), cr);\n }\n return cur;\n }\n};\n\nint main() {\n // Code here:\n \n int n, k;\n scanf(\"%d %d\", &n, &k);\n solve prob(n, k);\n int m;\n scanf(\"%d\", &m);\n forn(i, m) {\n int u, v;\n scanf(\"%d %d\", &u, &v);\n u--; v--;\n prob.add_edge(u, v);\n }\n prob.precalc();\n int q;\n scanf(\"%d\", &q);\n forn(i, q) {\n int l, r;\n scanf(\"%d %d\", &l, &r);\n l--;\n printf(\"%d\\n\", prob.compnum(l, r));\n }\n\n return 0;\n}"
764
A
Taymyr is calling you
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist. Ilia-alpinist calls every $n$ minutes, i.e. in minutes $n$, $2n$, $3n$ and so on. Artists come to the comrade every $m$ minutes, i.e. in minutes $m$, $2m$, $3m$ and so on. The day is $z$ minutes long, i.e. the day consists of minutes $1, 2, ..., z$. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute.
You can look over all minutes of the day. If both events happen on the some minute, we increment our answer.
[ "brute force", "implementation", "math" ]
800
"#Codeforces Round #395 Div2A solution\nfrom math import gcd\n\nn, m, z = map(int, input().split())\ng = gcd(n, m)\nlcm = n * m // g\nprint(z // lcm)"
764
B
Timofey and cubes
Young Timofey has a birthday today! He got kit of $n$ cubes as a birthday present from his parents. Every cube has a number $a_{i}$, which is written on it. Timofey put all the cubes in a row and went to unpack other presents. In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from $1$ to $n$ in their order. Dima performs several steps, on step $i$ he reverses the segment of cubes from $i$-th to $(n - i + 1)$-th. He does this while $i ≤ n - i + 1$. After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
Note that Dima's operations are reversible. If we apply them to the current order, we will get the initial. Also note that all the elements on even positions will remain on their places. Such numbers are affected an even number of times, so nothing will change. Similarly all elements on odd positions will change places with simmetrial ones relatively the centre. So, we change elements on odd places with their pairs. This works for $O(n)$ time.
[ "constructive algorithms", "implementation" ]
900
"//Codeforces Round #395 Div2B solution\n#include <bits/stdc++.h>\nusing namespace std;\ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\n#define forab(i, a, b) for (int i = (int)(a); i < (int)(b); ++i)\n#define _ cin.tie(0); ios_base::sync_with_stdio(0);\n#define i64 long long\n\nconst int MAXN = 1000000 + 10;\nint n, a[MAXN];\n\nint main() { _\n scanf(\"%d\\n\", &n);\n forn(i, n)\n scanf(\"%d\", &a[i]);\n for (int i = 0; i <= n - i - 1; ++i) {\n if (i % 2 - 1)\n swap(a[i], a[n - i - 1]);\n }\n forn(i, n) {\n if (i)\n printf(\" \");\n printf(\"%d\", a[i]);\n }\n return 0;\n}"
765
A
Neverending competitions
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: - this list contains all Jinotega's flights in this year (\textbf{in arbitrary order}), - Jinotega has only flown from his hometown to a snooker contest and back, - after each competition Jinotega flies back home (though they may attend a competition in one place several times), - and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location!
Each competition adds two flights to the list - there and back. The only exception is the last competition: if Jinotega is now there, it adds only one flight. So if $n$ is odd, the answer is contest, otherwise home.
[ "implementation", "math" ]
900
null
765
B
Code obfuscation
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest. To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol $a$, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with $b$, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs. You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
In this problem you needed to check that the first occurrences of letters $a$, $b$, ... appear in order (that is, first "$a$" is before first "$b$", which, in order, is before first "$c$", so on). One possible solution: for each letter $x$ check that there is at least one letter $x - 1$ before it.
[ "greedy", "implementation", "strings" ]
1,100
null
765
C
Table Tennis Game 2
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly $k$ points, the score is reset and a new set begins. Across all the sets Misha scored $a$ points in total, and Vanya scored $b$ points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible. Note that the game consisted of several complete sets.
There are several possible cases how the game could go: The first player won all the sets. In this case, each set gave him exactly $k$ points, hence $a$ must be divisible by $k$. Moreover, $b \le (a / k) \cdot (k - 1)$ since the second player could get at most $k - 1$ points per set. If we have $k|a$ and $0 \le b \le (a / k) \cdot (k - 1)$, then the answer is at least $a / k$. The second player won all the sets. The analysis in symmetrical. Each player has won at least one set. In this case we must have $a \ge k$ and $b \ge k$. If this condition holds, the game is possible with the maximal number of sets $ \lfloor a / k \rfloor + \lfloor b / k \rfloor $. Indeed, consider the following sequence of sets: $(k,b{\mathrm{~mod~}}k)$, $(a{\mathrm{~mod~}}k{\mathrm{,}}k)$, $( \lfloor a / k \rfloor - 1)$ copies of $(k, 0)$, $( \lfloor b / k \rfloor - 1)$ copies of $(0, k)$. In short: if ($a \ge k$ and $b \ge k$) or ($a$ divisible by k) or ($b$ divisible by $k$) the answer $ \lfloor a / k \rfloor + \lfloor b / k \rfloor $, otherwise $- 1$. One can check that this is equivalent to the reasoning above.
[ "math" ]
1,200
null
765
D
Artsem and Saunders
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem. Let $[n]$ denote the set ${1, ..., n}$. We will also write $f: [x] → [y]$ when a function $f$ is defined in integer points $1$, ..., $x$, and all its values are integers from 1 to $y$. Now then, you are given a function $f: [n] → [n]$. Your task is to find a positive integer $m$, and two functions $g: [n] → [m]$, $h: [m] → [n]$, such that $g(h(x)) = x$ for all $x\in[m]$, and $h(g(x)) = f(x)$ for all $x\in[n]$, or determine that finding these is impossible.
Suppose that $h(g) \equiv f$ (that is, the functions match on all inputs), and $g(h)\equiv1$ (the identity function). Hence, we must have $f(f(x))=h(g(h(g(x))))=h({\bf1}(g(x)))=h(g(x))=f(x)$. It means that if $f(x) = y$, then $f(y) = f(f(x)) = f(x) = y$, that is, all distinct values of $f$ must be its stable points. If this is violated, we can have no answer. We will put $m$ equal to the number of stable points. Let's enumerate all distinct values of $f$ as $p_{1}$, ..., $p_{m}$, and define a function $q$ that maps a point $p_{i}$ to the index $i$. We will determine functions $g(x) = q(f(x))$, and $h(x) = p_{x}$. We can see that: if $x\in[n]$, then $h(g(x)) = p_{q(f(x))} = f(x)$. if $x\in[m]$, then $g(h(x)) = q(p_{x}) = x$. All enumeration can be done in linear time.
[ "constructive algorithms", "dsu", "math" ]
1,700
null
765
E
Tree Folding
Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex $v$, and two disjoint (except for $v$) paths of equal length $a_{0} = v$, $a_{1}$, ..., $a_{k}$, and $b_{0} = v$, $b_{1}$, ..., $b_{k}$. Additionally, vertices $a_{1}$, ..., $a_{k}$, $b_{1}$, ..., $b_{k}$ must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices $b_{1}$, ..., $b_{k}$ can be effectively erased: Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.
Let's look at the performed actions in reverse. First, we have some path of odd length (by saying length we mean the number of edges} and double it several times. Now we do several "unfoldings". Among two leaves of this path exactly one (or its copy) participate in each unfolding; depending on it we call the unfolding "left" or "right". Note that left and right unfoldings have no edges in common; thus there is some vertex on the path which is not being unfolded. Let's call this vertex root. Here is a criterion that a vertex can be a valid root. Root the tree at it and look at its certain subtree: the depths of all leaves there must be equal. Moreover, among all subtrees of the root there must be not more than 2 different depths of the leaves. This criterion follows directly if you look at the sequence of unfoldings. Now we have a solution: for each directed edge in a tree compute a set of depths to the leaves by a 2-way tree DP (actually, it must be computed only if its size is at most 1). Afterwards for each vertex check the root criterion. However, there is an idea which makes the solution simpler: the midpoint of the diameter of the given tree is always an appropriate root. Given this, we should only run a standard tree DP which checks if all leaves in a subtree have the same depth. Here is the outline of a proof: in the path from the first paragraph select the leftmost and the rightmost possible root, now look through all possible distances from left root to the left leaf and from the right root to the right leaf. There are several configurations which are easy to check manually.
[ "dfs and similar", "dp", "greedy", "implementation", "trees" ]
2,200
null
765
F
Souvenirs
Artsem is on vacation and wants to buy souvenirs for his two teammates. There are $n$ souvenir shops along the street. In $i$-th shop Artsem can buy one souvenir for $a_{i}$ dollars, and he cannot buy more than one souvenir in one shop. He doesn't want to introduce envy in his team, so he wants to buy two souvenirs with least possible difference in price. Artsem has visited the shopping street $m$ times. For some strange reason on the $i$-th day only shops with numbers from $l_{i}$ to $r_{i}$ were operating (weird? yes it is, but have you ever tried to come up with a reasonable legend for a range query problem?). For each visit, Artsem wants to know the minimum possible difference in prices of two different souvenirs he can buy in the opened shops. In other words, for each Artsem's visit you should find the minimum possible value of $|a_{s} - a_{t}|$ where $l_{i} ≤ s, t ≤ r_{i}$, $s ≠ t$.
We will answer queries offline, moving right endpoint to the right and storing the answer for each left endpoint in a segment tree. The tree will support two operations: set minimum on a segment and get a value in the point. More, we assume that among two elements $a_{i}$ and $a_{j}$ in our array $a_{i} > a_{j}$ and $i < j$ and solve the problem twice - for the original array and for the reversed one. Consider one step of moving the right endpoint and adding new element $x$ to the position $i$. We find the first element to the left of $i$ which is not less than $x$; denote it with $a_{j} = y$. Obviously, now the answer for all left endpoints in range $[0, j]$ is $y - x$. Now we find some $a_{j'} = y'$ such that $x \le y' < y$ and $j' < j$, and the answer for all left endpoints in range $[0, j']$ is at most $y' - x$. If we repeat this step while possible, we maintain correct values in our segment tree. The crucial idea of the problem is the following inequality: $y' - x < y - y'$. Why? Because each segment with $r = i$ and $0 \le l \le j'$ contains elements $y$ and $y'$, and adding $x$ will improve the answer for these endpoints only if this inequality holds. Having this, we need to consider only $O(\log10^{9})$ values of $y$. The asymptotic of the solution is $O(n\log n\log10^{9}+m\log n)$.
[ "data structures" ]
3,100
null
765
G
Math, math everywhere
If you have gone that far, you'll probably skip unnecessary legends anyway... You are given a binary string $s=s_{0}\cdot\cdot\cdot s_{m-1}$ and an integer $N=p_{1}^{\alpha_{1}}\cdot\cdot\cdot p_{n}^{\alpha_{n}}$. Find the number of integers $k$, $0 ≤ k < N$, such that for all $i = 0$, $1$, ..., $m - 1$ \[ \operatorname*{gcd}(k+i,N)=1\ \operatorname{if}\operatorname{and\only}\operatorname{if}\ \ s_{i}=1 \] Print the answer modulo $10^{9} + 7$.
First I'll describe our original approach to this problem, and then some issues we encountered after the round finished. Suppose that $p_{1} = 2$. If we have $x\equiv0(\mathrm{mod}\,2)$, then the string $s$ must look like 0?0?0?..., that is, all even positions 0, 2, 4, ... will have 0's (for all others, we can't say), and if $x\equiv1(\mathrm{mod}\ 2)$, then $s$ looks like ?0?0?0.... Similarly, knowing the remainder of $x$ modulo a prime $p$ in factorization of $N$ implies that there are zeros in $s$ with $p$ positions apart. If we fix all remainder modulo $p_{1}$, ..., $p_{n}$, then the string will be determined unambigiously. Notice that after fixing the modulos, there are still $N' = p_{1}^{ \alpha 1 - 1}... p_{n}^{ \alpha n - 1}$ possible $x$'s between $0$ and $N - 1$; we will simply multiply the answer by $N'$ in the end. At this point we have a brute-force solution: try all values for remainders, count how many of the values give the string $s$. This is of course too slow, but we can make a few optimizations: Make a brute-force into a DP by introducing memoization. We will count the number of ways to obtain each partial string $s$ after fixing first $i$ remainders. Of course, we don't have to store all $2^{m}$ masks, but just the reachable ones. Once $p_{i} > m$, each choice of remainder either places a single zero into a string, or doesn't change anything. At this point we are not interested in the full mask, but rather in the number of "unsatisfied" zeros of initial string $s$. Each transition either satisfies one zero, or doesn't change anything; the number of transitions of each kind is easy to count. We will do a full memoization DP for $p_{i} \le m$, and continue with a compressed DP once $p_{i} > m$. The second part can be done in $O(nm)$ time and $O(m)$ memory. The complexity of the first part depends on the total number of states in the memoization DP. Turns out this number can be much larger than we anticipated on certain tests, for instance, primes starting from 5 or 7. On these cases, all our model solutions received time out. Such tests didn't appear in the original test set, of course. KAN and myself tried to improve the solution. The idea behind our optimization is that once $p_{i} > m / 2$, several central bits of the mask behave just like the "unsatisfied" bits in the large-prime part of the original solution: if we choose to cover them, it will be the single bit we cover. Thus we can do a "hybrid" DP that has parameters (number of unsatisfied bits in the middle, mask of all the rest bits). KAN's solution used "naive" mask DP for $p_{i} \le 23$, switched to static array for $p_{i} = 29, 31, 37$, and then proceeded to large primes as before. I tried to write a self-adaptive solution that handles all ranges of primes pretty much the same way. KAN was more successful: his solution works in $\sim3.5$ seconds on all cases we could counstruct; my solution works in $\sim11$ seconds and uses a lot of excess memory.
[ "brute force", "dp", "math", "meet-in-the-middle", "number theory" ]
3,200
null
766
A
Mahmoud and Longest Uncommon Subsequence
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem. Given two strings $a$ and $b$, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other. A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.
If the strings are the same, Any subsequence of $a$ is indeed a subsequence of $b$ so the answer is "-1", Otherwise the longer string can't be a subsequence of the other (If they are equal in length and aren't the same, No one can be a subsequence of the other) so the answer is maximum of their lengths. Time complexity : $O(|a| + |b|)$.
[ "constructive algorithms", "strings" ]
1,000
"#include <iostream>\n#include <string.h>\nusing namespace std;\nint main()\n{\n\tstring a,b;\n\tcin >> a >> b;\n\tif (a==b)\n\tcout << -1;\n\telse\n\tcout << max(a.size(),b.size());\n}"
766
B
Mahmoud and a Triangle
Mahmoud has $n$ line segments, the $i$-th of them has length $a_{i}$. Ehab challenged him to use \textbf{exactly $3$} line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly $3$ of them to form a non-degenerate triangle. Mahmoud should use exactly $3$ line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.
Let $x$, $y$ and $z$ be the lengths of 3 line segments such that $x \le y \le z$, If they can't form a non-degenerate triangle, Line segments of lengths $x - 1$, $y$ and $z$ or $x$, $y$ and $z + 1$ can't form a non-degenerate triangle, So we don't need to try all the combinations, If we try $y$ as the middle one, We need to try the maximum $x$ that is less than or equal to $y$ and the minimum $z$ that is greater than or equal to $y$, The easiest way to do so is to sort the line segments and try every consecutive 3. Time complexity : $O(nlog(n))$. Depending on the note from the first solution, If we try to generate a sequence such that after sorting, Every consecutive 3 line segments will form a degenerate triangle, It will be $1$ $1$ $2$ $3$ $5$ $8$ $13$ $...$ which is Fibonacci sequence, Fibonacci is a fast growing sequence, $fib(45) = 1134903170$, Notice that Fibonacci makes maximum $n$ with "NO" as the answer, That means the answer is indeed "YES" for $n \ge 45$, For $n < 45$, You can do the naive $O(n^{3})$ solution or the first solution. Let $x$ be the number that satisfies these inequalities:- $fib(x) \le maxAi$. $fib(x + 1) > maxAi$. Time complexity : $O(x^{3})$ or $O(xlog(x))$.
[ "constructive algorithms", "geometry", "greedy", "math", "number theory", "sortings" ]
1,000
"#include <iostream>\n#include <algorithm>\nusing namespace std;\nbool check(int a,int b,int c)\n{\n\tint tmp[]={a,b,c};\n\tsort(tmp,tmp+3);\n\treturn (tmp[0]+tmp[1]>tmp[2]);\n}\nint main()\n{\n\tint n;\n\tcin >> n;\n\tif (n>=45)\n\tcout << \"YES\";\n\telse\n\t{\n\t\tint arr[n];\n\t\tfor (int i=0;i<n;i++)\n\t\tcin >> arr[i];\n\t\tfor (int i=0;i<n;i++)\n\t\t{\n\t\t\tfor (int x=i+1;x<n;x++)\n\t\t\t{\n\t\t\t\tfor (int j=x+1;j<n;j++)\n\t\t\t\t{\n\t\t\t\t\tif (check(arr[i],arr[x],arr[j]))\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"YES\";\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << \"NO\";\n\t}\n}"
766
C
Mahmoud and a Message
Mahmoud wrote a message $s$ of length $n$. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number $i$ in the English alphabet to be written on it in a string of length more than $a_{i}$. For example, if $a_{1} = 2$ he can't write character 'a' on this paper in a string of length $3$ or more. String "aa" is allowed while string "aaa" is not. Mahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be $n$ and they shouldn't overlap. For example, if $a_{1} = 2$ and he wants to send string "aaa", he can split it into "a" and "aa" and use $2$ magical papers, or into "a", "a" and "a" and use $3$ magical papers. He can't split it into "aa" and "aa" because the sum of their lengths is greater than $n$. He can split the message into single string if it fulfills the conditions. A substring of string $s$ is a string that consists of some consecutive characters from string $s$, strings "ab", "abc" and "b" are substrings of string "abc", while strings "acb" and "ac" are not. Any string is a substring of itself. While Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions: - How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is $n$ and they don't overlap? Compute the answer modulo $10^{9} + 7$. - What is the maximum length of a substring that can appear in some valid splitting? - What is the minimum number of substrings the message can be spit in? Two ways are considered different, if the sets of split positions differ. For example, splitting "aa|a" and "a|aa" are considered different splittings of message "aaa".
Let $dp[i]$ be the number of ways to split the prefix of $s$ ending at index $i$ into substrings that fulfills the conditions. Let it be 1-indexed. Our base case is $dp[0] = 1$. Our answer is $dp[n]$. Now let's calculate it for every $i$. Let $l$ be the minimum possible index such that the substring from $l$ to $i$ satisfies the condition, Let $x$ be a moving pointer, At the beginning $x = i - 1$ and it decreases, Every time we decrease $x$, We calculate the new value of $l$ depending on the current character like that, $l = max(l, i - a_{s[x]})$. While $x$ is greater than or equal to $l$ we add $dp[x]$ to $dp[i]$, To find the longest substring, Find maximum $i - x$, To find the minimum number of substrings, there is an easy greedy solution, Find the longest valid prefix and delete it and do the same again until the string is empty, The number of times this operation is repeated is our answer, Or see the dynamic programming solution in the code. Time complexity : $O(n^{2})$. Try to find an $O(n)$ solution(I'll post a hard version of some problems on this blog soon).
[ "brute force", "dp", "greedy", "strings" ]
1,700
"#include <iostream>\n#include <string.h>\nusing namespace std;\n#define mod 1000000007\nstring s;\nint arr[26],dp[1005],dp2[1005];\nint main()\n{\n\tint n,l=0;\n\tcin >> n >> s;\n\tfor (int i=0;i<26;i++)\n\tcin >> arr[i];\n\tdp[0]=1;\n\tdp2[0]=0;\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tint f=0;\n\t\tdp2[i]=n;\n\t\tfor (int x=i-1;x>=0;x--)\n\t\t{\n\t\t\tf=max(f,i-arr[s[x]-'a']);\n\t\t\tif (f>x)\n\t\t\tcontinue;\n\t\t\tdp[i]=(dp[i]+dp[x])%mod;\n\t\t\tdp2[i]=min(dp2[i],1+dp2[x]);\n\t\t\tl=max(l,i-x);\n\t\t}\n\t}\n\tcout << dp[n] << endl << l << endl << dp2[n] << endl;\n}"
766
D
Mahmoud and a Dictionary
Mahmoud wants to write a new dictionary that contains $n$ words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words. He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on. Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time. After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations. After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Let's build a graph containing the words, For every relation in the input add a new edge with the weight of $0$ if they are equal and $1$ if they are opposites, If adding the edge doesn't make the graph cyclic, Our relation is valid, Otherwise it may be valid or invalid so we'll answer them offline. Check if adding that edge will make the graph cyclic or not using union-find like Kruskal's algorithm. Suspend answering relations that will make the graph cyclic, Now we have a forest of trees, Let $cum[i]$ be the xor of the weights on the edges in the path from the root of the component of node $i$ to node $i$. Calculate it using dfs. To find the relation between 2 words $u$ and $v$, Check if they are in the same component using union-find, If they aren't, The answer is $3$ otherwise the answer is $\left(c u m[u]\oplus c u m[v]\right)+1$, Now to answer suspended relations, Find the relation between the 2 words and check if it's the same as the input relation, Then answer the queries. Time complexity : $O((n + m + q)log(n) * maxL)$ where $maxL$ is the length of the longest string considering that union-find works in constant time.
[ "data structures", "dfs and similar", "dp", "dsu", "graphs" ]
2,000
#include <iostream> #include <string.h> #include <vector> #include <map> using namespace std; map<string,int> m; pair<int,int> arr[100005]; vector<pair<int,int> > v[100005]; vector<pair<pair<int,int>,pair<int,int> > > sus; bool valid[100005],vis[100005]; int n,cum[100005]; int find(int x) { if (x!=arr[x].first) x=find(arr[x].first); return arr[x].first; } bool Union(int x,int y) { x=find(x); y=find(y); if (x==y) return 0; if (arr[x].second<arr[y].second) arr[x].first=y; else if (arr[x].second>arr[y].second) arr[y].first=x; else { arr[x].first=y; arr[y].second++; } return 1; } void dfs(int node,int pnode,int x) { vis[node]=1; cum[node]=x; for (int i=0;i<v[node].size();i++) { if (v[node][i].first!=pnode) dfs(v[node][i].first,node,(x^v[node][i].second)); } } void preprocess() { for (int i=0;i<n;i++) { if (!vis[i]) dfs(i,i,0); } for (int i=0;i<sus.size();i++) { int x=sus[i].first.first,y=sus[i].first.second,idx=sus[i].second.first,r=sus[i].second.second; if ((cum[x]^cum[y])==r) valid[idx]=1; else valid[idx]=0; } } int main() { int q1,q2; cin >> n >> q1 >> q2; for (int i=0;i<n;i++) { string s; cin >> s; m[s]=i; arr[i]=make_pair(i,0); } for (int i=0;i<q1;i++) { int t; string s1,s2; cin >> t >> s1 >> s2; int x=m[s1],y=m[s2]; if (Union(x,y)) { v[x].push_back(make_pair(y,t-1)); v[y].push_back(make_pair(x,t-1)); valid[i]=1; } else sus.push_back(make_pair(make_pair(x,y),make_pair(i,t-1))); } preprocess(); for (int i=0;i<q1;i++) { if (valid[i]) cout << "YES" << endl; else cout << "NO" << endl; } while (q2--) { int t; string s1,s2; cin >> s1 >> s2; int x=m[s1],y=m[s2]; if (find(x)!=find(y)) cout << 3 << endl; else if (cum[x]^cum[y]) cout << 2 << endl; else cout << 1 << endl; } }
766
E
Mahmoud and a xor trip
Mahmoud and Ehab live in a country with $n$ cities numbered from $1$ to $n$ and connected by $n - 1$ undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number $a_{i}$ attached to it. We define the distance from city $x$ to city $y$ as the xor of numbers attached to the cities on the path from $x$ to $y$ \textbf{(including both $x$ and $y$)}. In other words if values attached to the cities on the path from $x$ to $y$ form an array $p$ of length $l$ then the distance between them is $p_{1}\oplus p_{2}\oplus\cdot\cdot\Leftrightarrow p_{l}$, where $\mathbb{C}$ is bitwise xor operation. Mahmoud and Ehab want to choose two cities and make a journey from one to another. The index of the start city is always less than or equal to the index of the finish city (they may start and finish in the same city and in this case the distance equals the number attached to that city). They can't determine the two cities so they try every city as a start and every city with greater index as a finish. They want to know the total distance between all pairs of cities.
If we have an array $ans[i]$ which represents the number of paths that makes the $i^{th}$ bit sit to $1$, Our answer will be $\sum_{i=0}^{l o g(n)}2^{i}*a n s[i]$ Let $arr[i][x]$ be the binary value of the $x^{th}$ bit of the number attached to node $i$(just to make work easier). There are 2 types of paths from node $u$ to node $v$ where $u$ is less in depth than or equal to $v$, Paths going down which are paths with $lca(u, v)$=$u$ and other paths, Let's root the tree at node $1$ and dfs, let current node be $node$, Let $dp[i][x][j]$ be the number of paths going down from node $i$ that makes the $x^{th}$ bit's value equal to $j$. A path going down from node $i$ is a path going down from a child of $i$ with node $i$ concatenated to it so let's calculate our $dp$. A path that isn't going down is a concatenation of 2 paths which are going down from $lca(u, v)$, Now we can calculate $ans$. See the code for formulas. Time complexity : $O(nlog(a_{i}))$.
[ "bitmasks", "constructive algorithms", "data structures", "dfs and similar", "dp", "math", "trees" ]
2,100
"#include <iostream>\n#include <iomanip>\n#include <string.h>\n#include <vector>\nusing namespace std;\nvector<int> v[100005];\nint arr[100005][25];\nlong long dp[100005][25][2],ans[25];\nvoid dfs(int node,int pnode)\n{\n\tlong long s[25][2];\n\tmemset(s,0,sizeof(s));\n\tfor (int i=0;i<25;i++)\n\tdp[node][i][arr[node][i]]=1;\n\tfor (int i=0;i<v[node].size();i++)\n\t{\n\t\tif (v[node][i]!=pnode)\n\t\t{\n\t\t\tdfs(v[node][i],node);\n\t\t\tfor (int j=0;j<25;j++)\n\t\t\t{\n\t\t\t\tfor (int x=0;x<2;x++)\n\t\t\t\t{\n\t\t\t\t\tdp[node][j][x]+=dp[v[node][i]][j][x^arr[node][j]];\n\t\t\t\t\ts[j][x]+=dp[v[node][i]][j][x];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor (int j=0;j<25;j++)\n\t{\n\t\tlong long x0=0,x1=0;\n\t\tfor (int i=0;i<v[node].size();i++)\n\t\t{\n\t\t\tif (v[node][i]!=pnode)\n\t\t\t{\n\t\t\t\tx0+=(s[j][1]-dp[v[node][i]][j][1])*dp[v[node][i]][j][1]+(s[j][0]-dp[v[node][i]][j][0])*dp[v[node][i]][j][0];\n\t\t\t\tx1+=(s[j][1]-dp[v[node][i]][j][1])*dp[v[node][i]][j][0]+(s[j][0]-dp[v[node][i]][j][0])*dp[v[node][i]][j][1];\n\t\t\t}\n\t\t}\n\t\tif (arr[node][j])\n\t\tans[j]+=x0/2;\n\t\telse\n\t\tans[j]+=x1/2;\n\t}\n\tfor (int j=0;j<25;j++)\n\tans[j]+=dp[node][j][1];\n}\nint main()\n{\n\tint n;\n\tcin >> n;\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tint a;\n\t\tcin >> a;\n\t\tfor (int x=0;x<25;x++)\n\t\tarr[i][x]=(bool)(a&(1<<x));\n\t}\n\tfor (int i=1;i<n;i++)\n\t{\n\t\tint a,b;\n\t\tcin >> a >> b;\n\t\tv[a].push_back(b);\n\t\tv[b].push_back(a);\n\t}\n\tdfs(1,0);\n\tlong long res=0;\n\tfor (int i=0;i<25;i++)\n res+=(ans[i]*(1LL<<i));\n\tcout<< res << endl;\n}"
767
A
Snacktower
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time $n$ snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top. Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it. Write a program that models the behavior of Ankh-Morpork residents.
It is enough to do what is written in the statements. You can maintain an array $has$, and mark in it which snacks has already fallen, and which hasn't. Create another variable $next$ which tracks the next snack which should be put on the top. Let's proceed with the integers in the input one by one. After reading next integer, mark it in the $has$ array and go from $next$ to the first snack which is not marked. Print all integers which we passed by.
[ "data structures", "implementation" ]
1,100
null
767
B
The Queue
Finally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow. He knows that the receptionist starts working after $t_{s}$ minutes have passed after midnight and closes after $t_{f}$ minutes have passed after midnight (so that $(t_{f} - 1)$ is the last minute when the receptionist is still working). The receptionist spends exactly $t$ minutes on each person in the queue. If the receptionist would stop working within $t$ minutes, he stops serving visitors (other than the one he already serves). Vasya also knows that exactly $n$ visitors would come tomorrow. For each visitor Vasya knows the point of time when he would come to the passport office. Each visitor queues up and doesn't leave until he was served. If the receptionist is free when a visitor comes (in particular, if the previous visitor was just served and the queue is empty), the receptionist begins to serve the newcomer immediately. \begin{center} {\small "Reception 1"} \end{center} For each visitor, the point of time when he would come to the passport office is positive. Vasya can come to the office at the time zero (that is, at midnight) if he needs so, but he can come to the office only at integer points of time. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and stand in the queue after the last of them. Vasya wants to come at such point of time that he will be served by the receptionist, and he would spend the minimum possible time in the queue. Help him!
Let's calculate the point of time when each visitor would be served. Let array $a$ contain the points of time when visitors arrive. The receptionist would begin to serve the first visitor at the point of time when the receptionist begins to work $t_{s}$, if the first visitor came to the passport office before it, or when he comes to the office, if he didn't. We can calculate the point of time when the receptionist would begin to serve the $i$-th visitor in the same way if we know when the receptionist began to serve the $i - 1$-th visitor. Let's suppose that the receptionist began to serve the $i - 1$-th visitor at $b_{i - 1}$ minute. It means that receptionist would begin to serve the $i$-th visitor no sooner than $t$ minutes later, that is $b_{i - 1} + t$ minute. The receptionist would begin to serve him at this point of time if $i$-th visitor came before ($a_{i} \le b_{i - 1} + t$). If he came later, his serving would begin when he comes. This way we will find the time $b_{i}$ when the receptionist would begin to serve him. If any visitor came later than the previous visitor was served ($a_{i} > b_{i - 1} + t$), the receptionist was free. It means that Vasya can be served immediately if he arrives at the proper time, for example, at $b_{i - 1} + t$ minute. If there are no such visitors, to be the $i$-th person served this day, Vasya has to arrive at the passport office no later than $(a_{i} - 1)$ and he would have to wait a minimum of $b_{i} - (a_{i} - 1)$ minutes. From all of these options we have to find a point of time with the minimal waiting time. There are several special cases we have to consider: If $i$-th and $(i - 1)$-th visitors arrived at the same time, Vasya can't arrive between them. Some visitors wouldn't be served this day if the time the receptionist would begin to serve them is more or equal to $T_{f} - t$ and that means we shouldn't attive to the passport office after them. Vasya can be the last person served this day if there are at least $t$ minutes between the point of time receptionist serves the last customer and the point of time he stops working. Vasya can be the first person served only if he comes before every other visitor. Considering the $10^{12}$ bound, all calculations should use the 64-bit data. To conclude, this task is reduced to careful calculation of the visitors' serving times ($O(n)$ time), considering the aforementioned edge cases.
[ "brute force", "greedy" ]
2,100
null
767
C
Garland
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps. There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp. Help Dima to find a suitable way to cut the garland, or determine that this is impossible. While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer.
We can note that the given graph is a tree. Let's perform a dfs from the root of the tree. Let's calculate the sums if $t_{i}$ in each subtree, let this value be $s_{v}$ for the subtree of the vertex $v$. In order to compute $s_{v}$ we need to recursively call dfs from all sons of $v$ and add the value $t_{v}$. Let the overall sum of $t_{i}$ be equal to $x$. If $x$ is not divisible by three, there is no answer. Otherwise there are two different cases (let the answer lamps be $v_{1}$ and $v_{2}$) to obtain three subtrees with equal sum ($x / 3$): 1. One of the vertices is an ancestor of the other (we can think that $v_{2}$ is ancestor of $v_{1}$), then $s_{v2} = 2x / 3$, $s_{v1} = x / 3$. 2. Neither $v_{1}$ nor $v_{2}$ is ancestor of the other. In this case $s_{v1} = s_{v2} = x / 3$ To check the first option, it is enough to track is the dfs if there is at least one vertex $u$ in the subtree of current vertex $v$ with sum $s_{u} = x / 3$. If there is one, and $s_{v} = 2x / 3$, then there is an answer $v_{2} = v, v_{1} = u$. To check the second option, let's write down all vertices $v$ such that $s_{v} = x / 3$ and there isno other $u$ with $s_{u} = x / 3$ in the subtree of $v$. Note that we do the same thing when checking the first option. So, if there are at least two vertices we wrote down, they form the answer we are looking for.
[ "dfs and similar", "graphs", "greedy", "trees" ]
2,000
null
767
D
Cartons of milk
Olya likes milk very much. She drinks $k$ cartons of milk each day if she has at least $k$ and drinks all of them if she doesn't. But there's an issue — expiration dates. Each carton has a date after which you can't drink it (you still can drink it exactly at the date written on the carton). Due to this, if Olya's fridge contains a carton past its expiry date, she throws it away. Olya hates throwing out cartons, so when she drinks a carton, she chooses the one which expires the fastest. It's easy to understand that this strategy minimizes the amount of cartons thrown out and lets her avoid it if it's even possible. \begin{center} {\small Milk. Best before: 20.02.2017.} \end{center} The main issue Olya has is the one of buying new cartons. Currently, there are $n$ cartons of milk in Olya's fridge, for each one an expiration date is known (how soon does it expire, measured in days). In the shop that Olya visited there are $m$ cartons, and the expiration date is known for each of those cartons as well. Find the maximum number of cartons Olya can buy so that she wouldn't have to throw away any cartons. Assume that Olya drank no cartons today.
Let $t$ be the maximum expiry date in the input. The key observation in this problem is the fact that if we can buy some $x$ cartons from the shop and not have to throw away the cartons, we can buy $x$ cartons with the biggest expiry dates and we won't have to throw away any cartons either. It happens because if we increase the carton's expiry date while having fixed distribution of cartons per days, the distribution would stay correct. Then, let's learn to check for an arbitrary $x$ is it true that if we take $x$ cartons with the maximum expiry dates we can distribute those cartons per days so that we won't have to throw cartons away. To do this, it is sufficient to check for each day $i$ from $0$ to $t$ that the amount of cartons with expiry dates $ \le i$ (both from a fridge and bought) is no bigger than $(i + 1)k$. Then the solution would be to search for maximum $x$ using the binary search. If $z$ is the answer, the check would pass for all $x$ from $0$ to $z$ and wouldn't for $x > z$, this monotony is sufficient for the binary search to work. Then we output the found $z$ and the $z$ cartons with maximum expiry dates (we don't even have to sort $s_{i}$, we can justdo an enumeration sort because $s_{i} \le 10^{7}$). This soluton runs in $O(tlogm)$ time.
[ "binary search", "data structures", "greedy", "sortings", "two pointers" ]
2,100
null
767
E
Change-free
Student Arseny likes to plan his life for $n$ days ahead. He visits a canteen every day and he has already decided what he will order in each of the following $n$ days. Prices in the canteen do not change and that means Arseny will spend $c_{i}$ rubles during the $i$-th day. There are $1$-ruble coins and $100$-ruble notes in circulation. At this moment, Arseny has $m$ coins and a sufficiently large amount of notes (you can assume that he has an infinite amount of them). Arseny loves modern technologies, so he uses his credit card everywhere except the canteen, but he has to pay in cash in the canteen because it does not accept cards. Cashier always asks the student to pay change-free. However, it's not always possible, but Arseny tries to minimize the dissatisfaction of the cashier. Cashier's dissatisfaction for each of the days is determined by the total amount of notes and coins in the change. To be precise, if the cashier gives Arseny $x$ notes and coins on the $i$-th day, his dissatisfaction for this day equals $x·w_{i}$. Cashier always gives change using as little coins and notes as possible, he always has enough of them to be able to do this. \begin{center} {\small "Caution! Angry cashier"} \end{center} Arseny wants to pay in such a way that the total dissatisfaction of the cashier for $n$ days would be as small as possible. Help him to find out how he needs to pay in each of the $n$ days! Note that Arseny always has enough money to pay, because he has an infinite amount of notes. Arseny can use notes and coins he received in change during any of the following days.
The first thing to note is that during day $i$ it makes sense to either pay $c_{i}\mathrm{~div~}100$ notes and $c_{i}{\mathrm{~mod~}}100$ coins (in this case, the cashier's dissatisfaction would be equal to $0$), or just $c_{i}\,\mathrm{div}\,100+1$ notes (in that case, the cashier's dissatisfaction would be equal to $(100-(c_{i}\;{\mathrm{mod}}\;100))\,w_{i}$)/ Moreover, the second case is impossible if $c_{i}{\mathrm{~mod~}}100=0$, so in that case you just have to pay the required amount of notes. In order to solve the problem, we have to note the additional fact. Let's suppose Arseny paid change-free during the $i$-th day and gave the cashier $c_{i}{\mathrm{~mod~}}100$ coins. Then, if we change the payment way this day, the amount of coins availible to Arseny would increase by $100$ regardless of the $c_{i}$! Indeed, Arseny wouldn't spend those $c_{i}{\mathrm{~mod~}}100$ coins, and he would aso receive $100-(c_{i}{\mathrm{~mod~}}100)$ coins in change, which adds up to exactly $100$ coins. Let's build the optimal solution day-by-day beginning from day one, trying to pay change-free every time to minimize the cashier's dissatisfaction. Let $i$-th day be the first one when Arseny wouldn't be able to pay change-free. It means that Arseny has to get some change at least once during days from first to $i$-th. But, regardless of the day, after $i$-th day he would have the same amount of coins! It means that the optimal way is to get change during the day when the cashier's dissatisfaction would be minimal. Then, let's continue to pay change-free whenever we can. If Arseny again can't pay change-free during day $j$, there must be a day from first to $j$-th when he got change. Using similiar considerations, whe should choose the day with the minimal cashier's dissatisfaction (except the first one). We should do these operations until we process all days. The simple implementation of this process works in $O(n^{2})$ time and hits TLE. But if you use any structure of data which allows you to add or delete element or find minimum in $O(\log n)$ time, for example, heap or binary seach tree, we can save all previous days into it and find a day with the minimal cashier's dissatisfaction faster than $O(n)$. The final time is $O(n\log n)$.
[ "greedy" ]
2,400
null
768
A
Oath of the Night's Watch
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath. With that begins the watch of Jon Snow. He is assigned the task to support the stewards. This time he has $n$ stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him. Can you find how many stewards will Jon support?
You just have to find the number of elements greater than the minimum number occurring in the array and less than the maximum number occurring in the array. This can be done in $O(n)$ by traversing the array once and finding the minimum and maximum of the array, and then in another traversal, find the good numbers. Complexity: $O(n)$
[ "constructive algorithms", "sortings" ]
900
#include<bits/stdc++.h> using namespace std; int a[100005]; int main() { int n,c1=0,c2=0,mx=0,mn=1000000007; cin>>n; for(int i=0;i<n;i++) { cin>>a[i]; mx=max(mx,a[i]),mn=min(mn,a[i]); } for(int i=0;i<n;i++) { if(a[i]==mx) c1++; if(a[i]==mn) c2++; } if(mx==mn) cout<<0; else cout<<(n-c1-c2); return 0; }
768
B
Code For 1
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element $n$. Then he has to perform certain operations on this list. In each operation Sam must remove any element $x$, such that $x > 1$, from the list and insert at the same position $\left|{\frac{x}{2}}\right|$, $x\ {\mathrm{mod}}\ 2$, $\left|{\frac{x}{2}}\right|$ sequentially. He must continue with these operations until all the elements in the list are either $0$ or $1$. Now the masters want the total number of $1$s in the range $l$ to $r$ ($1$-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?
It is easy to see that the total number of elements in the final list will be $2^{\lfloor\log_{2}n\rfloor+1}-1$ . The problem can be solved by locating each element in the list and checking whether it is $'1'$ .The $i^{th}$ element can be located in $O(logn)$ by using Divide and Conquer strategy. Answer is the total number of all such elements which equal $'1'$. Complexity : $O((r - l + 1) * logn)$
[ "constructive algorithms", "dfs and similar", "divide and conquer" ]
1,600
#include<bits/stdc++.h> using namespace std; long long int cnt(long long int temp) //returns the length of final list { long long int x=1; while(temp>1) { temp/=2; x*=2; } return x; } int is_one(long long int pos,long long int target,long long int num) { if(num<2) return num; if(pos+1==2*target) { return num%2; } num/=2; pos/=2; if(target>pos+1) target-=(pos+1); return is_one(pos,target,num); } int main() { long long int l,r,n,x,ans=0,i; cin>>n>>l>>r; x=cnt(n); x=2*x-1; for(i=l; i<=r; i++) ans+=is_one(x,i,n); cout<<ans<<endl; return 0; }
768
C
Jon Snow and his Favourite Number
Jon Snow now has to fight with White Walkers. He has $n$ rangers, each of which has his own strength. Also Jon Snow has his favourite number $x$. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now thinks that if he takes the bitwise XOR of strengths of some of rangers with his favourite number $x$, he might get soldiers of high strength. So, he decided to do the following operation $k$ times: - Arrange all the rangers in a straight line in the order of increasing strengths. - Take the bitwise XOR (is written as $\mathbb{C}$) of the strength of each alternate ranger with $x$ and update it's strength. Suppose, Jon has $5$ rangers with strengths $[9, 7, 11, 15, 5]$ and he performs the operation $1$ time with $x = 2$. He first arranges them in the order of their strengths, $[5, 7, 9, 11, 15]$. Then he does the following: - The strength of first ranger is updated to $5\oplus2$, i.e. $7$. - The strength of second ranger remains the same, i.e. $7$. - The strength of third ranger is updated to $9\oplus2$, i.e. $11$. - The strength of fourth ranger remains the same, i.e. $11$. - The strength of fifth ranger is updated to $15\oplus2$, i.e. $13$. The new strengths of the $5$ rangers are $[7, 7, 11, 11, 13]$Now, Jon wants to know the maximum and minimum strength of the rangers after performing the above operations $k$ times. He wants your help for this task. Can you help him?
The range of strengths of any ranger at any point of time can be [0,1023]. This allows us to maintain a frequency array of the strengths of the rangers. Now, the updation of the array can be done in the following way: Make a copy of the frequency array. If the number of rangers having strength less than a strength $y$ is even, and there are $freq[y]$ rangers having strength y, ceil($freq[y] / 2$) rangers will be updated and will have strengths $y$^$x$, and the remaining will retain the same strength. If the number of rangers having strength less than a strength $y$ is odd,and there are $freq[y]$ rangers having strength y, floor($freq[y] / 2$) rangers will be updated and will have strengths $y$^$x$, and remaining will have the same strength. This operation has to be done $k$ times, thus the overall complexity is $O(1024 * k)$. Complexity: $O(k * 2^{10})$
[ "brute force", "dp", "implementation", "sortings" ]
1,800
#include<bits/stdc++.h> #define rep(i,start,lim) for(int i=start;i<lim;i++) using namespace std; #define N 100005 int freq[1100],tmp[1024]; int main() { int n,k,maxm=0,minm=INT_MAX,p,x; cin>>n>>k>>x; rep(i,0,n) cin>>p,freq[p]++; rep(i,0,k) { rep(j,0,1024) tmp[j]=freq[j]; int par=0; rep(j,0,1024) { if(freq[j]>0) { int curr = (j^x),change = (freq[j]/2); if(par==0) change+=(freq[j]&1); tmp[j]-=change; tmp[curr]+=change; par^=(freq[j]&1); } } rep(j,0,1024) freq[j]=tmp[j]; } rep(i,0,1024) if(freq[i]>0) minm=min(minm,i),maxm=max(maxm,i); cout<<maxm<<" "<<minm; return 0; }
768
D
Jon and Orbs
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are $k$ different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least $\frac{p_{i}-\varepsilon}{2000}$, where $ε < 10^{ - 7}$. To better prepare himself, he wants to know the answer for $q$ different values of $p_{i}$. Since he is busy designing the battle strategy with Sam, he asks you for your help.
This problem can be solve using inclusion-exclusion principle but precision errors need to be handled. Therefore, we use the following dynamic programming approach to solve this problem. On $n - th$ day there are two possibilities, Case-1 : Jon doesn't find a new orb then the probability of it is $\scriptstyle{\frac{\pi}{n}}$. Case-2 : Jon does find a new orb then the probability of it is $\scriptstyle{\frac{k-x+1}{n}}$. Therefore, $d p[n][x]={\textstyle\frac{x}{k}}\cdot d p[n-1][x]+{\frac{k-x+1}{k}}\cdot d p[n-1][x-1]$ We need to find the minimum $n$ such that $d p[n][k]\geqslant{\frac{p_{i}}{2000}}.$ where, $n$ = number of days Jon waited. $x$ = number of distinct orbs Jon have till now. $dp[n][x]$ = probability of Jon having $x$ distinct orbs in $n$ days. $k$ = Total number of distinct orbs possible. PS:The $ \epsilon $ was added so that the any solution considering the probability in the given range $\left({\frac{p_{i}-\epsilon}{2000}},\;{\frac{p_{i}}{2000}}\right)$ passes the system tests.
[ "dp", "math", "probabilities" ]
2,200
#include <bits/stdc++.h> using namespace std; const int N = 1004; const double eps = 1e-7; double dp[N]; int ans[N]; int main(){ int k, q, d = 1; cin >> k >> q; dp[0] = 1; for(int n = 1; d <= 1000; ++n){ for(int x = k; x > 0; --x){ dp[x] = (x * dp[x] + (k - x + 1) * dp[x - 1]) / k; } while(d <= 1000 && 2000 * dp[k] >= (d - eps)){ ans[d] = n; d++; } dp[0] = 0; } while(q--){ int x; cin >> x; cout << ans[x] << "\n"; } }
768
E
Game of Stones
Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple: - The game starts with $n$ piles of stones indexed from $1$ to $n$. The $i$-th pile contains $s_{i}$ stones. - The players make their moves alternatively. A move is considered as removal of some number of stones from a pile. Removal of $0$ stones does not count as a move. - The player who is unable to make a move loses. Now Jon believes that he is ready for battle, but Sam does not think so. To prove his argument, Sam suggested that they play a modified version of the game. In this modified version, no move can be made more than once on a pile. For example, if $4$ stones are removed from a pile, $4$ stones cannot be removed from that pile again. Sam sets up the game and makes the first move. Jon believes that Sam is just trying to prevent him from going to battle. Jon wants to know if he can win if both play optimally.
This problem can be solved using DP with Bitmasks to calculate the grundy value of piles. Let us have a 2-dimensional dp table, $dp[i][j]$, where the first dimension is for number of stones in the pile and second dimension is for bitmask. The bitmask has $k$-th bit set if we are allowed to remove $k + 1$ stones from the pile. Now, to calculate $dp[i][j]$ we need to iterate over all possible moves allowed and find the mex. Finally for the game, we use the grundy values stored in $dp[i][2^{i} - 1]$ for a pile of size $i$. We take the xor of grundy values of all piles sizes. If it is 0, then Jon wins, otherwise Sam wins. The complexity of this solution is $O(n*2^{n}*\log n)$. This will not be accepted. We can use the following optimizations for this problem: So we can rewrite the above code to incorporate these change. Hence, the final solution is as follows Bonus: Try to find and prove the $O(1)$ formula for grundy values
[ "bitmasks", "dp", "games" ]
2,100
#include<bits/stdc++.h> using namespace std; typedef long long ll; map<pair<int, ll>, int> grundy; map<pair<int, ll>, bool> mp; int retgrundy(int ps, ll bm, int prev = 63){ for(int i=ps ; i<prev ; ++i){ if(((bm>>i)&1LL) == 1LL) bm ^= (1LL<<i); } if(mp[{ps, bm}]) return grundy[{ps, bm}]; vector<bool> marked(63, false); for(int k=0 ; k<ps ; ++k){ if(((bm>>k)&1LL) == 0) continue; marked[retgrundy(ps-k-1LL, (bm^(1LL<<k)), ps)] = true; } int ret; for(int i=0 ; i<63 ; ++i){ if(marked[i]) continue; grundy[{ps, bm}] = i; ret = i; break; } mp[{ps, bm}] = true; return ret; } int main(){ int n, in, x=0; scanf("%d", &n); grundy[{0, 0}] = 0; mp[{0, 0}] = true; vector<int> gr(70, 0); for(int i=0 ; i<=60 ; ++i) gr[i] = retgrundy(i, (1LL<<i)-1LL); while(n--){ scanf("%d", &in); x ^= gr[in]; } if(x == 0) printf("YES"); else printf("NO"); }
768
F
Barrels and boxes
Tarly has two different type of items, food boxes and wine barrels. There are $f$ food boxes and $w$ wine barrels. Tarly stores them in various stacks and each stack can consist of either food boxes or wine barrels but not both. The stacks are placed in a line such that no two stacks of food boxes are together and no two stacks of wine barrels are together. The height of a stack is defined as the number of items in the stack. Two stacks are considered different if either their heights are different or one of them contains food and other contains wine. Jon Snow doesn't like an arrangement if any stack of wine barrels has height less than or equal to $h$. What is the probability that Jon Snow will like the arrangement if all arrangement are equiprobably? Two arrangement of stacks are considered different if exists such $i$, that $i$-th stack of one arrangement is different from the $i$-th stack of the other arrangement.
Every arrangement of stacks can expressed in the form of linear arrangement. In this linear arrangement, every contiguous segment of wine barrels are separated by food boxes. For the arrangement to be liked by Jon each of the $f + 1$ partitions created by $f$ food boxes must contain either $0$ or greater than $h$ wine barrels. Let $u$ out of $f + 1$ partitions have non-zero wine barrels then the remaining $r + 1 - u$ partitions must have $0$ wine barrels.. Total number of arrangements with exactly u stacks of wine barrels are $({f}_{\mathfrak{n}}^{\cdot1})\cdot X$ $\textstyle{\binom{f+1}{n}}$ is the number of ways of choosing $u$ partitions out of $f + 1$ partitions. $X$ is the number of ways to place $w$ wine barrels in these $u$ partitions which is equal to the coefficient of $x^{w}$ in ${x^{h + 1} \cdot (1 + x + ...)}^{u}$. Finally we sum it up for all $u$ from $1$ to $f + 1$. So the time complexity becomes $O(w)$ with pre-processing of factorials. $w = 0$ was the corner case for which the answer was $1$. We did not anticipate it will cause so much trouble. Not placing it in the pretests was a rookie mistake.
[ "brute force", "combinatorics", "math", "number theory", "probabilities" ]
2,300
#include <bits/stdc++.h> using namespace std; const int N = 212345; const int mod = 1000000007; int fac[N], ifac[N], inv[N]; void prep(){ fac[0] = ifac[0] = inv[1] = 1; for(int i = 1; i < N; ++i) fac[i] = 1LL * i * fac[i - 1] % mod; for(int i = 2; i < N; ++i) inv[i] = mod - 1LL * (mod / i) * inv[mod % i] % mod; for(int i = 1; i < N; ++i) ifac[i] = 1LL * inv[i] * ifac[i - 1] % mod; } int C(int n, int r){ if(r < 0 || n < r) return 0; return 1LL * fac[n] * ifac[n - r] % mod * ifac[r] % mod; } int num(int r, int b, int k){ if(b == 0) return 1; int ans = 0; for(int u = 1; u <= r + 1 && (k == 0 || u <= (b - 1) / k); ++u){ ans += 1LL * C(r + 1,u) * C(b - k * u - 1, u - 1) % mod; ans %= mod; } return ans; } int pwr(int b, int p){ int r = 1; while(p){ if(p & 1) r = 1LL * r * b % mod; b = 1LL * b * b % mod; p >>= 1; } return r; } int finv(int x){ return pwr(x, mod - 2); } int main(){ prep(); int f, w, h; cin >> f >> w >> h; int sn = num(f, w, h); int sd = C(f + w, w); cout << 1LL * sn * finv(sd) % mod << "\n"; }
768
G
The Winds of Winter
Given a rooted tree with $n$ nodes. The Night King removes exactly one node from the tree and all the edges associated with it. Doing this splits the tree and forms a forest. The node which is removed is not a part of the forest. The root of a tree in the forest is the node in that tree which does not have a parent. We define the strength of the forest as the size of largest tree in forest. Jon Snow wants to minimize the strength of the forest. To do this he can perform the following operation at most once. He removes the edge between a node and its parent and inserts a new edge between this node and any other node in forest such that the total number of trees in forest remain same. For each node $v$ you need to find the minimum value of strength of the forest formed when node $v$ is removed.
We are given a tree. We remove one node from this tree to form a forest. Strength of forest is defined as the size of largest tree in forest. We need to minimize the strength by changing the parent of atmost one node to some other node such that number of components remain same. To find the minimum value of strength we do a binary search on strength. It is possible to attain Strength $S$ if 1. There is less than one component with size greater than $S$. 2. There exists a node in maximum component with subtree size $Y$ such that, $M - Y \le S$ (Here $M$ is size of maximum component and m is size of minimum component) $m + Y \le S$. Then we can change the parent of this node to some node in smallest component. The problem now is to store Subtree_size of all nodes in the maximum component and perform binary search on them. We can use Stl Map for this. Let $X$ be the node which is removed and $X_{size}$ be its subtree size There are two cases now -: 1. When max size tree is child of $X$. 2. When max size tree is the tree which remains when we remove subtree of $X$ from original tree.(We refer to this as outer tree of $X$). In the second case the subtree sizes of nodes on path from root to $X$ will change when $X$ is removed. Infact their subtree size will decrease exactly by $X_{size}$. While performing binary search on these nodes there will be an offset of $X_{size}$. So we store them seperately. Now we need to maintain $3$ Maps, where $map_{children}$ : Stores the Subtree_size of all nodes present in heaviest child of $X$. $map_{parent}$ : Stores the Subtree_size of all nodes on the path from root to $X$. $map_{outer}$ : Stores the Subtree_size of all nodes in outer tree which are not on path from root to $X$. Go through this blog post before reading further (http://codeforces.com/blog/entry/44351). Maintaining the Maps $map_{children}$ and $map_{parent}$ are initialised to empty while $map_{outer}$ contains Subtree_size of all nodes in the tree. $map_{parent}$ : This can be easily maintained by inserting the Subtree_size of node in map when we enter a node in dfs and remove it when we exit it. $map_{children}$ : $map_{children}$ can be maintained by using the dsu on tree trick mentioned in blogpost. $map_{outer}$ : When we insert a node's subtree_size in $map_{childern}$ or $map_{parent}$ we can remove the same from $map_{outer}$ and similarly when we insert a node's Subtree_size in $map_{childern}$ or $map_{parent}$ we can remove the same from $map_{outer}$. Refer to HLD style implementation in blogpost for easiest way of maintaining $map_{outer}$. Refer to code below for exact point of insertions and deletions into above mentioned $3$ maps. Complexity $O(NlogN^{2})$
[ "binary search", "data structures" ]
3,300
#include <bits/stdc++.h> using namespace std; const int N = 100005; vector<int> adj[N]; int sz[N], ans[N]; int n, root; bool big[N]; map<int,int> mp, mpo, par; void getsz(int s){ sz[s] = 1; ans[s] = n - 1; for(auto it : adj[s]){ getsz(it); sz[s] += sz[it]; } mpo[sz[s]]++; } void bs(map<int, int> &mp1, int l, int r, int mi, int s, int off){ if(mi == n - 1) return; int ma = r; while(r - l > 1){ int mid = (r + l) / 2; auto it = mp1.lower_bound(ma - mid + off); if(it == mp1.end()) l = mid; else if(mi + it->first <= mid + off) r = mid; else l = mid; } ans[s] = min(ans[s], r); } void add(int s){ mp[sz[s]]++; if(mpo[sz[s]] == 1) mpo.erase(sz[s]); else mpo[sz[s]]--; for(auto it:adj[s]) if(!big[it]) add(it); } void rem(int s){ mpo[sz[s]]++; if(mp[sz[s]] == 1) mp.erase(sz[s]); else mp[sz[s]]--; for(auto it:adj[s]) if(!big[it]) rem(it); } void dfs(int s, bool isbig){ par[sz[s]]++; if(mpo[sz[s]] == 1) mpo.erase(sz[s]); else mpo[sz[s]]--; int ma = -1, sma = -1, mac = -1, mi = n - 1; for(auto it:adj[s]){ if(sz[it]>ma){ sma = ma; ma = sz[it]; mac = it; } else if(sz[it]==ma) sma = ma; else sma = max(sma,sz[it]); mi = min(mi,sz[it]); } if(s != root) mi = min(mi,n-sz[s]); for(auto it:adj[s]){ if(it!=mac) dfs(it,0); } if(mac != -1){ big[mac]=true; dfs(mac,1); } if(ma >= n - sz[s]){ sma = max(sma, n - sz[s]); bs(mp, sma - 1, ma, mi, s, 0); } mpo[sz[s]]++; add(s); if(par[sz[s]] == 1) par.erase(sz[s]); else par[sz[s]]--; if(n-sz[s] > ma){ sma = ma; bs(mpo, sma - 1, n - sz[s], mi, s, 0); bs(par, sma - 1, n - sz[s], mi, s, sz[s]); } if(mac != -1) big[mac] = false; if(!isbig) rem(s); } int main(){ int i, u, v; scanf("%d", &n); for(i = 0; i < n; ++i){ scanf("%d%d", &u ,&v); if(u == 0) root = v - 1; else adj[u - 1].push_back(v - 1); } getsz(root); dfs(root, 1); for(i = 0; i < n; ++i) printf("%d\n", ans[i]); }