User editorial for Codeforces Round 513 by Barcelona Bootcamp (rated, Div. 1 + Div. 2)

March 10, 2023 · 21 min · 4409 words · nor

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.

1060A

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 88-s given to us be mm. We can not make more than n/11\lfloor n / 11 \rfloor phone numbers, because every phone number has 1111 digits, and the number of phone numbers can't be more than mm. So an upper bound on the number of phone numbers is min(m,n/11)\min(m, \lfloor n / 11\rfloor).

We claim that this is indeed achievable. Indeed, we make the following two cases:

  • mn/11m \le n / 11: this means n11mn10mmn \ge 11 m \implies n - 10m \ge m. So we have sufficient cards to assign 1010 cards (without an 88 on them) to each card with an 88 on it, and this leads to mm phone numbers.

  • m>n/11m > n / 11: this means that we can pick n/11\lfloor n / 11 \rfloor cards with 88 on each of them, and assign 10n/1110 \lfloor n / 11 \rfloor cards out of the rest to them in order to construct n/11\lfloor n / 11 \rfloor phone numbers. This is possible since the total number of cards used is n/11+10n/11=11n/11n\lfloor n / 11 \rfloor + 10 \lfloor n / 11 \rfloor = 11 \lfloor n / 11 \rfloor \le n, the last of which is true since nn is non-negative.

The time complexity is O(n)O(n).

Submission: [submission:196688903]

1060B

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 a,ba, b be two non-negative integers. Let the number of carry-bits encountered while adding them be cc. Then S(a)+S(b)=S(a+b)+9cS(a) + S(b) = S(a + b) + 9c.

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 00. So the next carry bit can at most be (9+9)/10=1\lfloor (9 + 9) / 10 \rfloor = 1, and the base case is shown. Let's say we are at some position ii from the right. Then the carry bit is at most 11. So the next carry bit can be at most (1+9+9)/10=1\lfloor (1 + 9 + 9) / 10 \rfloor = 1, and we are done.

Claim 1.2. (Relaxation of claim 1): Let a,ba, b be two non-negative integers, and let ε\varepsilon be one of 00 and 11. Let the number of carry bits encountered while adding a,b,εa, b, \varepsilon be cc. Then S(a)+S(b)+S(ε)=S(a+b+ε)+9cS(a) + S(b) + S(\varepsilon) = S(a + b + \varepsilon) + 9c.

Proof. Let's denote by (a)\ell(a) the number of digits in aa for a>0a > 0 and let (0)=0\ell(0) = 0. We will induct on max((a),(b))\max(\ell(a), \ell(b)). The base case is trivial. For the inductive step, note that when there is a carry in the last place, then the carry bit hh can be at most (1+9+9)/10=1\lfloor (1 + 9 + 9) / 10 \rfloor = 1. Applying the inductive hypothesis for (a/10,b/10,h)(\lfloor a/10 \rfloor, \lfloor b/10 \rfloor, h), we know that S(a/10)+S(b/10)+S(h)=S(a/10+b/10+h)S(\lfloor a/10 \rfloor) + S(\lfloor b/10 \rfloor) + S(h) = S(\lfloor a/10 \rfloor + \lfloor b/10 \rfloor + h). Let's now see what happened at the last place.

We consider the quantity a%10+b%10+ε(a+b+ε)%10ha \% 10 + b \% 10 + \varepsilon - (a + b + \varepsilon) \% 10 - h.

  • If there was a carry: this quantity reduces by 99.
  • 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. \blacksquare

As a consequence of claim 1, it is easy to see that we want a,ba, b satisfying a+b=na + b = n that maximize the number of carry bits when added. By induction on the length of the suffix of the decimal representation of nn that consists only of 99-s, we can show that it is impossible to get any carry bit. Let's remove the largest suffix consisting entirely of 99-s from nn. It suffices to find the answer for this nn now.

So either you run out of 99-s in the suffix (in which case n=10k1n = 10^k - 1 for some positive integer kk), or there is a digit that is not 99. In the former case, the answer is just the sum of digits of nn. In the latter, note that we can't get more than (n)1\ell(n) - 1 carry bits. This is also achievable: consider b=10(n)11b = 10^{\ell(n) - 1} - 1. (or 11 if (n)=0\ell(n) = 0).

The time complexity is O(logn)O(\log n).

Submission: [submission:196689846]

1060C

Hints/intuition

Can we get a closed form for the sum of elements of the subrectangle?

Solution

Note that for a subrectangle corresponding to x1,y1,x2,y2x_1, y_1, x_2, y_2 as in the statement, ci,jc_{i, j} corresponds to the term we get when we multiply (i=x1x2ai)(j=y1y2bj)(\sum_{i = x_1}^{x_2} a_i) \cdot (\sum_{j = y_1}^{y_2} b_j). This allows us to decouple the rows and the columns of the matrix.

More specifically, consider the subarray of aa with indices from x1x_1 to x2x_2 (let's call it a[x1:x2]a[x_1 : x_2]), and also consider the subarray of bb with indices from y1y_1 to y2y_2 (let's call it b[y1:y2]b[y_1 : y_2]). Define the cost of a subarray as the sum of elements in it. Then the sum of the subrectangle equals the cost of a[x1:x2]a[x_1 : x_2] times the cost of b[y1:y2]b[y_1 : y_2]. So now, we focus on only the one dimensional arrays given to us.

For a given value CC of the cost, let's try to find the maximum length of a subarray of aa with cost CC (let's call this (C)\ell( C)). Using this, we can compute the maximum length of a subarray that has a cost at most CC, by finding the prefix maximums of \ell. Let's also do this for the array bb.

The problem now reduces to finding maxAiBj\max A_i \cdot B_j subject to the constraints ijxi \cdot j \le x, for two monotonically non-decreasing arrays AA and BB (the reduction follows by setting AA to be the array found in the previous paragraph for aa, and BB to be the analogue of AA for bb).

Now, this problem can be solved in linear time in the sizes of the arrays using two pointers: let's iterate over ii from right to left. Note that the rightmost jj such that ijxi \cdot j \le x is in fact x/i\lfloor x / i \rfloor, and this is non-decreasing as ii decreases. In fact, since BB is non-decreasing, two pointers are redundant, and we can simply query Bx/iB_{\lfloor x / i \rfloor}.

Note that there is one potential catch: the sizes of AA and BB might be large. But the constraints on the arrays aa and bb show that the maximum size is 41064 \cdot 10^6, and the constraints on nn show that we can run an O(n2)O(n^2) loop to compute the arrays AA and BB from aa and bb fast enough.

The time complexity is O(max(i=1nai,i=1mbi)+n2+m2)O(\max(\sum_{i = 1}^n a_i, \sum_{i = 1}^m b_i) + n^2 + m^2).

Submission: [submission:196755317]

1060D

Hints/intuition

There are two possible approaches to this problem:

  1. Try finding a lower bound on the answer. Can you show that it is actually the answer?
  2. 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 ii to person jj contributes max(ri,lj)\max(r_i, l_j) to the answer, and every person contributes 11. So we want to minimize n+i=1nmax(ri,lpi)n + \sum_{i = 1}^n \max(r_i, l_{p_i}) over all permutations pp of size nn. We claim that this expression is minimized when rir_i and lpil_{p_i} are sorted the same way. The proof will be via construction.

Without loss of generality, let's say rr is sorted (reindex people if this is not the case).

Consider a permutation pp with at least one inversion. Note that here an inversion is defined as lpj>lpil_{p_j} > l_{p_i} for i<ji < j --- in particular, we are not looking at inversions in pp, but in the "permutation" lpl \circ p, or more precisely the composition of the permutation that you get when you map elements of ll to their ranks (ties broken arbitrarily), and pp.

Every permutation with at least one inversion has at least one inversion with adjacent indices. Let's say those indices are (i,i+1)(i, i + 1). This means lpi+1<lpil_{p_{i + 1}} < l_{p_i} and riri+1r_i \le r_{i + 1}. We now construct the permutation pp' by applying a swap (i,i+1)(i, i + 1) to pp. We claim that pp' is at least as good as pp. In particular, we just need to show that for positive integers aba \le b and c<dc < d, the following holds: max(a,c)+max(b,d)max(a,d)+max(b,c)\max(a, c) + \max(b, d) \le \max(a, d) + \max(b, c), or equivalently, that max(a,d)max(a,c)max(b,d)max(b,c)\max(a, d) - \max(a, c) \ge \max(b, d) - \max(b, c). Consider the function f(x)=max(x,d)max(x,c)f(x) = \max(x, d) - \max(x, c). For xcx \le c it evaluates to dcd - c, for c<xdc < x \le d it evaluates to dxd - x, and for d<xd < x it evaluates to 00. So, this is a non-increasing function, and we are done.

This operation (replacing pp by pp') 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 lpl \circ p is the identity permutation --- that is, ll and rr 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 n+i=1nmax(Li,Ri)n + \sum_{i = 1}^n \max(L_i, R_i) chairs, where L,RL, R are the arrays you get when you sort l,rl, r respectively.

The time complexity is O(nlogn)O(n \log n) for sorting.

Submission: [submission:196760424]

1060E

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 uu and vv 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 n1n_1 and the number of new edges is n2n_2, the length of the considered shortest path is n1+n2n_1 + n_2, and the length of the walk in the original tree is n1+2n2n_1 + 2 n_2. By reducing this walk to a path, we get a path in the tree of length n1+2n2\le n_1 + 2 n_2. 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 ll in the tree between uu and vv, we can construct a path of length l/2\lceil l / 2 \rceil in the new tree. Since ln1+2n22(n1+n2)l \le n_1 + 2 n_2 \le 2 (n_1 + n_2), we have l/2n1+n2\lceil l / 2 \rceil \le n_1 + n_2, so this is indeed the shortest path between the two vertices in the new graph.

This shows that for vertices u,vu, v, the distance between them in the new graph is d(u,v)/2\lceil d(u, v) / 2 \rceil.

Now we only need to compute the sum of this expression over all u,vu, v. d(u,v)/2\lceil d(u, v) / 2 \rceil equals d(u,v)/2d(u, v) / 2 if the distance between u,vu, v is even, and (d(u,v)+1)/2(d(u, v) + 1) / 2 otherwise. In other words, we just need to compute the sum of d(u,v)d(u, v) 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 d(u,v)d(u, v) is standard: every edge contributes 11 to each pair (u,v)(u, v) 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 O(n)O(n).

Submission: [submission:196767377]

1060F

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 2n1(n1)!2^{n-1} (n-1)! 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 σ\sigma and π\pi be two permutations. Applying the mapping xx+|σ|x \mapsto x + |\sigma| to the array π\pi and shuffling the elements of σ\sigma and π\pi together, while keeping their internal order the same will generate another permutation with size |σ|+|π||\sigma| + |\pi|. We shall call this operation interleaving. Note that when σ\sigma and π\pi vary over all permutations, and the interleavings are taken over all possible (|σ|+|π||π|)\binom{|\sigma| + |\pi|}{|\pi|} interleavings, this generates all possible permutations of size |σ|+|π||\sigma| + |\pi|. We can generalize this to adding an extra bit of information with every element of σ\sigma and π\pi, 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 {1}\{1\} 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 uu when kk decisions are done before we choose the hanging edge. For the transitions, you can refer to the submission.

Submission: [submission:196942805]

1060G

Hints/intuition

How can you exploit the fact that when there are kk aia_i-s to the left of a number which is not on a pocket, it gets shifted to the left by kk? Try finding some properties and some nice locations that can help.

Solution

We'll reindex aa for its indices to start from 00.

Let's start out with an easy to prove observation:

We call an interval [a,b][a, b] of positive integers good if there are exactly ba+1b - a + 1 pockets with positions <b< b. 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 cc pockets under the interval. Then the left endpoint moves by ba+1cb - a + 1 - c (potentially falling into a pocket), the right endpoint moves by ba+1b - a + 1, 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 {ri}i=0n1\{r_i\}_{i = 0}^{n - 1} by r0=a01r_0 = a_0 - 1 and ri=ri1+iai1ri1ir_i = r_{i - 1} + i \cdot \left\lfloor \frac{a_i - 1 - r_{i - 1}}{i} \right\rfloor for i>0i > 0. This is clearly a non-decreasing sequence.

This roughly corresponds to the set of right endpoints of our intervals (though some rir_i 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 ri+1airi+ir_i + 1 \le a_i \le r_i + i.

Observation 2. Whenever ri>ri1r_i > r_{i - 1}, we have ri>ai1r_i > a_{i-1}.

Proof. Since riri1r_i - r_{i - 1} is divisible by ii, the difference is at least ii. So by the previous observation, we have riri1+iai1+1>ai1r_i \ge r_{i - 1} + i \ge a_{i - 1} + 1 > a_{i - 1}, as desired.

From this, we get that if ri>ri1r_i > r_{i - 1}, the length of the moving interval [rii+1,ri][r_i - i + 1, r_i] stays intact for ai1ri1i1\left\lfloor \frac{a_i - 1 - r_{i - 1}}{i} \right\rfloor - 1 operations, and after one more operation, it ends up at some suffix of positions ri1\le r_{i - 1}. That is, rir_i after some operations hits ri1r_{i - 1}. 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 rir_i-s close to xx. 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]

1060H

Hints/intuition

What kinds of operations can we implement using addition alone? Try small cases, like d=2d = 2.

Solution

Using addition, we can implement multiplication by a "compile-time" constant nn in O(logn)O(\log n) steps. Since arithmetic is modular, we can implement this in O(logp)O(\log p) steps (remember that multiplication by 00 is an edge case here, so it needs to be handled like multiplication by pp).

If you try d=2d = 2, you can realize that it suffices to be able to find a2a^2 from a variable aa, because then we have xy=((x+y)2x2y2)((p+1)/2))xy = ((x + y)^2 - x^2 - y^2) \cdot ((p + 1) / 2)).

Now we only want to be able to go from xdx^d to x2x^2. For this, note that there is a set of d+1d + 1 linear equations in the formal variables 1,x,x2,,xd1, x, x^2, \dots, x^d relating them to (x+i)d(x + i)^d for i=0i = 0 to dd. The determinant of the matrix is non-zero since it is a non-zero (mod pp too, because d<pd < p) factor times the Vandermonde determinant (which is non-zero mod pp because d<pd < p), so it is invertible.

By inverting this matrix, we can get x2x^2 from (x+i)d(x + i)^d for i=0i = 0 to dd. The total number of queries is about O(dlogp)O(d \log p) 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},
}