TCO18 Algorithm Round 3A Editorials

Share

This is the first of two round 3s and the competition is getting tougher. Only 600 people have made it to this round, but only 100 will move on (50 in round 3A and 50 in round 3B). Participants also have a chance to win a t-shirt if they score a positive number of points in either of the rounds.

Round 3A’s easy and medium problem are authored by [misof], while the hard one is authored by [ltdtl]. The editorials are all by [lg5293].

LeftToRightGame

In this problem, Alice and Bob are playing a game where they take alternating turns writing the digits of a positive integer from left to right. The game ends once there are exactly N digits, and Bob wins if and only if the number is divisible by D. Your task is given N and D, determine the winner of the game if both players play optimally.

There are a few ways to solve this problem and I’ll go over two of them. One is by dynamic programming and the other by casework. The dynamic programming approach is a bit “brainless” and doesn’t require any careful thinking, but may take longer to code. The casework approach is much faster to code but is much easier to get wrong if you miss a case.

Dynamic Programming Approach (dp)

To do dp, our state space is how many digits are left, what the current modulus is for the divisor, and the result is whether the current player will win. To get the winner of a particular state, we can check all subsequent states they can reach. The state is winnable if they can reach a state that is a losing state.

The advantage of this approach is that it is very easy to prove correctness and it is relatively easy to code. The disadvantage is that it does take a bit more time to type.

The runtime of this approach is the number of states times the number of subsequent states we can reach, which in this case is O(N * D).

Casework approach

Next, this is the approach by casework: it’s easy to see that if D = 1, then Bob always wins no matter what either player does, so let’s assume D > 1 now.

Now, we claim that the player that goes last almost decides the entire game. For instance, if Alice goes last, she has 10 choices of the last digit, and one of them is guaranteed to not cause the number to be divisible by D, so she can always win if she goes last (short justification, not all choices can be divisible by D when D > 1). So, for now, let’s assume N is even (i.e. Bob goes last).

For Bob, it is not always the case that he has a valid winning choice, for example, consider the case when N = 2, and D = 12. If Alice chooses the first digit to be 5, there is no valid choice for the second digit for Bob that makes the number divisible by 12.

If D <= 10, Bob can win since he has a choice of 10 digits, and since the gap between divisors is less than 10, he always has a valid winning choice. For D = 11, Bob can choose to always copy Alice’s move, so he has a winning strategy. Now, let’s say D >= 12. We want to claim on Alice’s last turn (i.e. the second to last turn in the game), she can choose a digit that gives Bob no winning choices. Let’s say for each choice 0,1,2,…,9 for Alice that Bob has a corresponding winning choice. Since D >= 10, Bob has at most one winning choice for each of Alice’s choice. Let the winning choices be a_0, a_1, …, a_9. We must have a_i = a_(i-1) + (D – 10). However this will make some a_i bigger than 10, which is a contradiction, which shows Alice has a winning strategy.

This only checks a constant number of conditions, so this code takes O(1) time.

ProductThreshold

In this problem, you would like to know how many subarrays in an array have a product that doesn’t exceed a particular threshold. This array can be pretty large, so a sub-quadratic solution is required.

This is almost a standard problem. For instance, if you know all elements are positive, you can do a 2-pointer approach to solve this. However, here, there can be negative and zero elements in the array, so 2-pointers doesn’t work out of the box, and we need to be more careful in how we approach this problem. For example, consider an array like [2, -2, 2, -2, 2, -2, …], with a threshold of 1. The valid endpoints for a particular start point don’t form a contiguous range, which makes 2 pointers not work.

Instead of counting subarrays that stay below a threshold, let’s instead count subarrays that exceed the threshold and subtract it from the total number of subarrays. The reason for doing it is that it is easier to constrain these types of subarrays a bit more, in particular, none of these subarrays can contain zeros.

To exceed a particular threshold, we can naively iterate through the first log_2(10^9) non-one elements. So for each start point, we can naively scan from left to right on non-one elements until we exceed our product. We also want to make sure our product is positive after this point, so we can also keep track of how many elements have a positive or negative product.

To implement this, I scanned from right to left, and for each start point, I computed how many ending indices have a positive / negative suffix product. If I hit a zero, I reset all counts to zero (since no subarrays that exceed the limit can contain a zero). I also keep track of a stack of all non-one elements, which I can use to iterate through until I exceed the limit. After finding the point at which I always exceed the limit, I can use the previously computed counts of product / negative suffix products to compute how many elements after have the same parity (thus will be a positive product).

ColoringEdgesDiv1

In this problem, we are given a 3-regular graph, and we would like to colour the edges of the graph with two colours such that no cycle is all the same colour. If there are multiple solutions, we can return any of them. Here, I’ll describe two different approaches

Solution 1

We show a solution always exists by constructing one. Here is a linear-time solution (O(V+E)) that takes advantage of 3-regularity of the given graph.

There are three main phases to this algorithm. All steps in each phase are done “simultaneously” (for the proof later).
[1] First, colour the edges such that no vertex has all 3 of its incident edges as the same colour.
This can be done via a max-flow algorithm, or by adding a dummy node connected to all vertices and finding a Eulerian tour which would guarantee that each vertex has at least one incident edge of each colour. This can be done in linear time.
[2] Once this is done, identify all monochromatic cycles in linear time (all these cycles will be vertex disjoint, due to 3-regularity, and the fact that each node has at most 2 adjacent edges of the same colour). For each cycle, pick one edge arbitrarily and flip its colour. Do this simultaneously for all cycles at once.
[3] Then, check if new monochromatic cycles are introduced (old cycles are guaranteed to be gone by now — this is easy to prove due to 3-regularity). For each new monochromatic cycle C, it is clear that at least one edge e on C was re-coloured in the previous step. Choose one of these edges arbitrarily and recall which cycle it belonged to before the colour-flip — let’s call it C’. On C’, choose one of the two adjacent edges to e and flip its colour as well as flip the colour of e (the colour of e will go back to its original colour). Do this for all new cycles simultaneously. This can all be done in linear time. This guarantees that there is no monochromatic cycle left (we’ll prove this now).

To observe why this solution works, let’s consider what happens at the end of step [1]. All monochromatic cycles are vertex-disjoint (due to 3-regularity). In addition, all new cycles introduced after step [2] are also vertex-disjoint (again, due to 3-regularity) Moreover, every vertex has at most two incident edges of the same color after step [1], [2], and [3], respectively (note we do all flips “simultaneously”). We’ll skip a formal proof, but this fact (referred to as (*)) is used in the proof later.

Let us now show that there is no monochromatic cycle after step [3].
Consider the edges that are coloured as 0 after step [3]. We’ll show that there is no cycle of colour 0 after step [3] (by symmetry the same holds for colour 1).
In step [3], we want to show that no 0-colour cycle is created by colouring some edge from 1 to 0.
Consider some 0-colour cycle C at the beginning of step [3] (after step [2]). Suppose we pick some edge e = (x, y) on cycle C and color it (back) to 1 and pick its neighboring edge e’ = (y, z) on the cycle C’ (that is a 1-colored cycle at the beginning of step [2]) and color it to 0. Clearly, neither C nor C’ is monochromatic after step [3].

This is a picture of C and C’ at the beginning of step [3]

After step [3]:

Note that x != z (since C has length at least 3). Colouring e’ from 1 to 0 can create a 0-colour cycle only if there is a path consisting only of 0-colour edges between y and z while excluding the edge e’ itself. Yet y is still connected by a 0-color path to x after step [3] (why? Because of step [3], and no other edges on this cycle were modified), and it’s impossible to get a path from z to y, since such a path would need to connect to some node in C’, which is not possible due to 3-regularity and (*)).

This completes the proof, and the algorithm runs in linear time. Here is a Java implementation of this approach:

Solution 2

Another way to solve this problem is to solve this more generally for arbitrary graphs. We can restate this problem by finding two edge-disjoint forests of the graph that cover all edges. This is almost the same as this problem: https://en.wikipedia.org/wiki/Arboricity (or more specifically, it is the same as pseudo arboricity).

This can be solved by reducing the matroid partitioning problem, which is similar to maximum flow.

To do this, we can add edges one by one. Without loss of generality, let’s say we are adding an edge in forest 0. If this doesn’t form a cycle, then we can just add it and be done. Otherwise, this induces a path on one of the trees in forest 0. We can add this edge to forest 0, iterate through the edges on this path and remove it from forest 0 and add it to forest 1 instead (note this can go back and forth recursively). We can repeat as many times as necessary until the edge can be added (only considering each (edge, forest) pair once). Note that it will always eventually be possible to add the edge if the original graph can be split into two edge-disjoint forests (due to proof of a 2-colouring existing and the matroid partitioning algorithm).

This as written, is O(E^3) in the worst case theoretically (though it is hard to make it reach the worst case). This can be sped up to O(n^2) if we didn’t iterate through used edges in the pathfinding which can be done by storing the pointer of highest edge that is still unused at each iteration. It may be possible to break this solution with a carefully constructed test case. Note that this approach does not take advantage of the fact that the graph is 3-regular, just that it can be split into two colours (it can also be modified to detect whether such a 2-colouring is possible by seeing if the code raises an assertion error)

Solution 3

Actually, the two above solutions are overkill. It is possible to solve this by using DFS to find an arbitrary forest. Edges in the forest are colored 0, otherwise, they are colored 1.

To prove this work, obviously, there are no cycles in the 0 edges, so it suffices to show there can’t be any cycles in 1 edges. Since the graph is 3-regular, the only possible way we can get a cycle in the 1 edges is on the nodes that use only at most 1 zero edge. This happens to be the leaves of our DFS tree. However, it’s impossible for the leaves to form a cycle of unused edges, otherwise, our DFS would have visited them earlier.