User editorial for Codeforces Round 513 by Barcelona Bootcamp (rated, Div. 1 + Div. 2)
It's been about 5 years since the round took place, and since there was no editorial all this time, I decided to write one myself.
Thanks to tfg for discussing problem F with me and coming up with the permutation interpretation that makes it much easier to reason about the problem. The idea in F was also inspired by other submissions.
Hints/intuition
Think about two cases: when there are very few 8s, and when there are a lot of 8s.
Solution
Let the number of -s given to us be . We can not make more than phone numbers, because every phone number has digits, and the number of phone numbers can't be more than . So an upper bound on the number of phone numbers is .
We claim that this is indeed achievable. Indeed, we make the following two cases:
: this means . So we have sufficient cards to assign cards (without an on them) to each card with an on it, and this leads to phone numbers.
: this means that we can pick cards with on each of them, and assign cards out of the rest to them in order to construct phone numbers. This is possible since the total number of cards used is , the last of which is true since is non-negative.
The time complexity is .
Submission: [submission:196688903]
Hints/intuition
What happens to the digit sum of the sum of two numbers (compared to their individual digit sums) when there is no carry-bit when adding two numbers? When there is one carry-bit? Two carry-bits? Can you quantify this result? One might guess that we want to maximize the number of carry-bits, and that is correct.
Solution
Firstly let's show a claim to show that the intuition was correct.
Claim 1. Let be two non-negative integers. Let the number of carry-bits encountered while adding them be . Then .
Proof. We will induct on the number of carry-bits in the addition. For this proof to be made amenable to induction, we will need the following observation, and a slight restructuring of the claim.
Observation 1.1. The carry bit when adding two numbers can be at most 1.
Proof. Induction on the current position in the process of addition. At the rightmost position, the carry bit is . So the next carry bit can at most be , and the base case is shown. Let's say we are at some position from the right. Then the carry bit is at most . So the next carry bit can be at most , and we are done.
Claim 1.2. (Relaxation of claim 1): Let be two non-negative integers, and let be one of and . Let the number of carry bits encountered while adding be . Then .
Proof. Let's denote by the number of digits in for and let . We will induct on . The base case is trivial. For the inductive step, note that when there is a carry in the last place, then the carry bit can be at most . Applying the inductive hypothesis for , we know that . Let's now see what happened at the last place.
We consider the quantity .
- If there was a carry: this quantity reduces by .
- If there was no carry: this quantity stays the same.
Now note that this combined with the conclusion from the inductive hypothesis proves the claim.
As a consequence of claim 1, it is easy to see that we want satisfying that maximize the number of carry bits when added. By induction on the length of the suffix of the decimal representation of that consists only of -s, we can show that it is impossible to get any carry bit. Let's remove the largest suffix consisting entirely of -s from . It suffices to find the answer for this now.
So either you run out of -s in the suffix (in which case for some positive integer ), or there is a digit that is not . In the former case, the answer is just the sum of digits of . In the latter, note that we can't get more than carry bits. This is also achievable: consider . (or if ).
The time complexity is .
Submission: [submission:196689846]
Hints/intuition
Can we get a closed form for the sum of elements of the subrectangle?
Solution
Note that for a subrectangle corresponding to as in the statement, corresponds to the term we get when we multiply . This allows us to decouple the rows and the columns of the matrix.
More specifically, consider the subarray of with indices from to (let's call it ), and also consider the subarray of with indices from to (let's call it ). Define the cost of a subarray as the sum of elements in it. Then the sum of the subrectangle equals the cost of times the cost of . So now, we focus on only the one dimensional arrays given to us.
For a given value of the cost, let's try to find the maximum length of a subarray of with cost (let's call this ). Using this, we can compute the maximum length of a subarray that has a cost at most , by finding the prefix maximums of . Let's also do this for the array .
The problem now reduces to finding subject to the constraints , for two monotonically non-decreasing arrays and (the reduction follows by setting to be the array found in the previous paragraph for , and to be the analogue of for ).
Now, this problem can be solved in linear time in the sizes of the arrays using two pointers: let's iterate over from right to left. Note that the rightmost such that is in fact , and this is non-decreasing as decreases. In fact, since is non-decreasing, two pointers are redundant, and we can simply query .
Note that there is one potential catch: the sizes of and might be large. But the constraints on the arrays and show that the maximum size is , and the constraints on show that we can run an loop to compute the arrays and from and fast enough.
The time complexity is .
Submission: [submission:196755317]
Hints/intuition
There are two possible approaches to this problem:
- Try finding a lower bound on the answer. Can you show that it is actually the answer?
- Try to rephrase the setup in another way, and observe some structure.
Solution
Firstly, let's try finding a lower bound on the answer. To visualize this setup better, let's construct a graph where there is an edge from a person to the person on their right. Then the resulting graph is a union of isolated cycles (and possibly self-loops).
Clearly, for a person, there is exactly one person to their right, and every person has exactly one person on their left. So the function that maps a person to the person on their right is a permutation. Also, note that every permutation has a cycle decomposition, and by arranging people according to the cycles in the decomposition, we can recover a valid seating plan. In other words, there is a bijection between seating plans and permutations.
Any edge from a person to person contributes to the answer, and every person contributes . So we want to minimize over all permutations of size . We claim that this expression is minimized when and are sorted the same way. The proof will be via construction.
Without loss of generality, let's say is sorted (reindex people if this is not the case).
Consider a permutation with at least one inversion. Note that here an inversion is defined as for --- in particular, we are not looking at inversions in , but in the "permutation" , or more precisely the composition of the permutation that you get when you map elements of to their ranks (ties broken arbitrarily), and .
Every permutation with at least one inversion has at least one inversion with adjacent indices. Let's say those indices are . This means and . We now construct the permutation by applying a swap to . We claim that is at least as good as . In particular, we just need to show that for positive integers and , the following holds: , or equivalently, that . Consider the function . For it evaluates to , for it evaluates to , and for it evaluates to . So, this is a non-increasing function, and we are done.
This operation (replacing by ) reduces the number of inversions by exactly one. By doing this process while there is at least one inversion, we come to a permutation such that is the identity permutation --- that is, and are sorted the same way.
Now that we are done with the proof, we have shown that there exists an optimal seating plan which requires chairs, where are the arrays you get when you sort respectively.
The time complexity is for sorting.
Submission: [submission:196760424]
Hints/intuition
Can we map shortest paths in the new graph to shortest paths in the tree?
Solution
Consider a shortest path between two vertices and in the new graph. It consists of two types of edges: edges that were originally in the tree, and edges that were added to the tree. Let's call them old and new edges respectively.
We construct a walk in the original tree corresponding to this shortest path: for every new edge, replace it by two adjacent old edges due to which this new edge was added.
So if the number of old edges is and the number of new edges is , the length of the considered shortest path is , and the length of the walk in the original tree is . By reducing this walk to a path, we get a path in the tree of length . Note that this is at most twice the length of the considered shortest path.
Conversely, from a shortest path (in fact, the unique path) of length in the tree between and , we can construct a path of length in the new tree. Since , we have , so this is indeed the shortest path between the two vertices in the new graph.
This shows that for vertices , the distance between them in the new graph is .
Now we only need to compute the sum of this expression over all . equals if the distance between is even, and otherwise. In other words, we just need to compute the sum of over all vertices, and the number of pairs of vertices that are at an odd distance to each other. Since we can color a tree in 2 colors, we just need to find the product of the sizes of the two bipartitions.
Computing the sum of is standard: every edge contributes to each pair of vertices such that removing that edge will disconnect these vertices. So we can root the tree, do a DFS, and then compute the number of such pairs for each edge quite easily.
The time complexity is .
Submission: [submission:196767377]
Hints/intuition
Fix the vertex for which we want the answer, and call it the root. Let's try to think about the operations sequentially. We have a total of choices, corresponding to sequence of (edge, choice) pairs where the choice is to choose which label is assigned to the collapsed vertex. Try to count the sequences of these choices which allow the root to survive. A probabilistic interpretation works too.
Solution
Read the previous spoiler if not done already for the basic intuition behind the solution.
Let and be two permutations. Applying the mapping to the array and shuffling the elements of and together, while keeping their internal order the same will generate another permutation with size . We shall call this operation interleaving. Note that when and vary over all permutations, and the interleavings are taken over all possible interleavings, this generates all possible permutations of size . We can generalize this to adding an extra bit of information with every element of and , and an analogous result holds true for this setup too.
We will look at the choices as interleavings of the choices for each of the children's subtrees (with an extra edge added on top for each subtree). The operation corresponding to adding an extra edge corresponds to interleaving the permutation with the permutation for the subtree (and there is precisely one choice that must be taken whenever we consider the extra edge). We'll call this edge the hanging edge for that subtree.
Now at any stage of the interleaving, note how the structure of the tree looks like. It might be helpful to consider the shrinking operations in the following way: initially all edges are represented with dotted lines (implying that they're just a template for connecting edges, and don't connect the edges at this stage), and every vertex is its own representative, and every shrinkage converts a dotted line into a solid line, and sets the representative of the sets of vertices connected by this edge to one of the representatives randomly. Basically how DSU works.
In this interpretation, consider the component containing the root. The choices made for the children subtrees that have only one correct choice (for the root to survive) correspond to the choices that end up in the root's component. Let's un-interleave these choices. Then this problem reduces to the same problem but for the child subtrees. Also, note that when interleaving these subtrees and counting the number of choices that allow the root to survive, only the number of choices made (before choosing the hanging edge) for each subtree matter. Also, note that we can do these interleavings associatively (that is, first the first subtree, then the second with the result of the first subtree, then the third with the result of the first and second subtrees and so on), and the computation remains the same.
So the merges will go as follows: for a vertex, we will compute the answers for its children, and for each child, extend the set of choices by the extra choice that needs to be made for adding a hanging edge (by interleaving with the single choice), and then interleave these choices again.
Using these ideas, we can do a DP with the following state: dp[u][k] is the number of choices for the subtree of a vertex when decisions are done before we choose the hanging edge. For the transitions, you can refer to the submission.
Submission: [submission:196942805]
Hints/intuition
How can you exploit the fact that when there are -s to the left of a number which is not on a pocket, it gets shifted to the left by ? Try finding some properties and some nice locations that can help.
Solution
We'll reindex for its indices to start from .
Let's start out with an easy to prove observation:
We call an interval of positive integers good if there are exactly pockets with positions . Then after a single operation, a good interval moves to positions that form a good interval. The proof goes as follows: let's say there are pockets under the interval. Then the left endpoint moves by (potentially falling into a pocket), the right endpoint moves by , and balls that didn't fall into a pocket remain contiguous (filling holes if formed).
Let's try to take advantage of such good intervals. We will try to construct good intervals with some maximal right endpoints, so as to partition the integer line into some partitions.
Define the sequence by and for . This is clearly a non-decreasing sequence.
This roughly corresponds to the set of right endpoints of our intervals (though some will be repeated here, and though we'll ignore them in the current analysis, they'll be helpful for implementation).
Observation 1. By the definition of floor, we have .
Observation 2. Whenever , we have .
Proof. Since is divisible by , the difference is at least . So by the previous observation, we have , as desired.
From this, we get that if , the length of the moving interval stays intact for operations, and after one more operation, it ends up at some suffix of positions . That is, after some operations hits . This sequence gives a partition of the integer line into smaller chunks that can be reasoned about locally.
Now that the main idea of the solution is complete, all that remains is to back-compute the number that ends up at a given position. For this, it is (theoretically) straightforward to compute the answer if you reason about the number that ends up at certain -s close to . For the relevant book-keeping that needs to be done as a part of implementation details, a persistent segment tree can be used. Note that the queries can also be solved offline, but that needs some more work.
Submission: [submission:196921763]
Hints/intuition
What kinds of operations can we implement using addition alone? Try small cases, like .
Solution
Using addition, we can implement multiplication by a "compile-time" constant in steps. Since arithmetic is modular, we can implement this in steps (remember that multiplication by is an edge case here, so it needs to be handled like multiplication by ).
If you try , you can realize that it suffices to be able to find from a variable , because then we have .
Now we only want to be able to go from to . For this, note that there is a set of linear equations in the formal variables relating them to for to . The determinant of the matrix is non-zero since it is a non-zero (mod too, because ) factor times the Vandermonde determinant (which is non-zero mod because ), so it is invertible.
By inverting this matrix, we can get from for to . The total number of queries is about in both space and memory, and it passes very comfortably.
Submission: [submission:196822812]
Cite this post
@online{user-editorial-cf-513-2023,
author = {nor},
title = {User editorial for Codeforces Round 513 by Barcelona Bootcamp (rated, Div. 1 + Div. 2)},
year = {2023},
month = {03},
day = {10},
url = {https://nor-blog.pages.dev/posts/2023-03-10-user-editorial-cf-513},
}