Sunday, August 12, 2018

A week in memory of Leo

The Jun 25 - Jul 1 week presented the last of the last chances to progress in TopCoder Open 2018 with its Round 2C on Tuesday (problems, results, top 5 on the left, parallel round results with 2/3 shared problems, analysis). This round was ran in honor of Leopoldo Taravilse, who has tragically passed away recently. It was really sad to hear this news, and I express my sincere sympathy to Leopoldo's family and friends.

fruwajacybyk has squeezed out the first place through challenges from Min,lu and tozangezan who led after the coding phase. Well done!

Codeforces held its Round 493 on Sunday (problems, results, top 5 on the left, analysis). fjzzq2002 dominated the proceedings, solving all problems with 20 minutes to spare while everybody else could manage at most four. Congratulations on the impressive performance!

Problem D, after removing a somewhat artificial complication, boiled down to the following cute combinatorial puzzle: you are given a tree with n<=2000 vertices. How many cycles of length 1, 2, ..., k (k<=75) does it have, modulo 998244353? A tree does not have simple cycles, so we're interested in non-simple cycles of course. Two cycles that differ only by choosing the starting point and direction are still considered different.

In my previous summary, I have mentioned another Codeforces problem: you are given a prime modulo p up to 109 and two numbers u and v between 0 and p-1. In one step, you can either add one modulo p, subtract one modulo p, or take inverse modulo p. You need to obtain v from u in at most 200 steps (the solution doesn't need to be the shortest).

This problem allows many approaches, so I'd like to share a bit more how my thinking went. I've started to write down which numbers we can get in a few steps, like u+1 or 1/(u+1) or 1+1/(u+1)=(u+2)/(u+1). Then I've noticed that if we represent our current number as x/y, then the three operations we have are x->x-y, x->x+y, and swap(x,y). This has strongly resembled the Euclidean algorithm, which can go from (x,y) to (0,gcd(x,y)) using those operations. Now I had a sketch of the solution: we'll represent u as (u*k mod p)/k, then apply the Euclidean algorithm to go from u to 0. Now we do the same for v, and since all operations are reversible, we can now go from u to 0 to v.

However, the Euclidean algorithm takes a small (logarithmic) number of steps only if we have the modulo operation available. With just subtraction, it can take a lot of steps - for example, if we pick k=1, then we'll start with u/1 and need u steps to get to 0 just subtracting 1 every time. So we need to choose k wisely so that the number of steps to get from u to 0 will not exceed 100.

First I tried to find k so that (u*k mod p)/k is as close to the golden ratio as possible, as the golden ratio is the case where the Euclidean algorithm proceeds in the fastest way. However, this did not work as sometimes just being close is not enough, and on last steps we still start making too many subtractions. But then I've realized that I can just try random values of k until I find one that works, and this ended up working flawlessly.

Thanks for reading, and check back for more!

Saturday, July 28, 2018

A too simple week

The Jun 18 - Jun 24 week had Codeforces Round 492 (problems, results, top 5 on the left, analysis). I've also included myself in the standings on the left to highlight the fact that OO0OOO00O0OOO0O00OOO0OO's performance was so amazing that he got all 6 problems accepted before I got any one of those :) Well done!

Right after this round, Scott Wu and Andrew He streamed a post-contest discussion on twitch (CF post). Unfortunately the recording is no longer available, but the concept is exciting and I've enjoyed listening to a part of it.

The round had a few mathy problems, but I'd like to highlight problem E which had a more algorithmic flavor: you are given a prime modulo p up to 109 and two numbers u and v between 0 and p-1. In one step, you can either add one modulo p, subtract one modulo p, or take inverse modulo p. You need to obtain v from u in at most 200 steps (the solution doesn't need to be the shortest). Do you see a way?

Thanks for reading, and check back for more!

Wednesday, July 25, 2018

A week without automorphisms

The Jun 11 - Jun 17 week was supposed to present the last chance to qualify for further TopCoder Open 2018 rounds in Round 2B (problems, results, top 5 on the left, parallel round resultsanalysis). However, because of technical issues an extra Round 2C was added two weeks later. Those issues notwithstanding, congratulations to gs14004 on creating just enough cushion during the coding phase to withstand the challenge push from maroon_kuri, sky_love_high and FizzyDavid! sky_love_high in particular actually had 1262.53 points after four minutes of the challenge phase, which would be enough for the first place.

Codeforces had its own share of issues with Round 488 on Saturday (problems, results, top 5 on the left, analysis), this time not technical but with an incorrect reference solution for the hardest problem. It turned out that the test data was luckily correct anyway, so this ended up being a somewhat theoretical discussion that did not affect the round. Congratulations to Um_nik and Errichto on solving all problems!

In my previous summary, I have mentioned an exciting Code Jam problem. You are given a number n between 10 and 50, and need to print a connected simple undirected graph with n vertices, and each vertex having degree exactly 4. The interactor will then randomly permute the vertices of your graph and give it back to you, and you need to then restore the permutation that was used. In other words, you need to find such graph without automorphisms, and be able to identify its vertices after they're shuffled.

This is another example where there are two main ways: either solve it "on paper", or try various random-looking things at the computer until one works. Since there are only 41 possible inputs, it's quite easy to verify if an approach works or not.

It turns out that in this problem even the expected solution went the random way. First, we have to come up with a way we'll use to identify the vertices. Then, we'll try random connected graphs with all degrees equal to 4 until we can uniquely identify all vertices in one. Of course, this last step also requires some way of generating such graphs.

As a way to identify the vertices, we can use an iterative approach: initially all vertices start with the same label. Then we compute some function for all vertices that depends on the existing labels and the structure of the graph, but does not change when we permute the vertices. In case the values of the function for some vertices is different, we can update their labels to be different, and repeat the process. Eventually we need for all labels to become different.

The function we compute can't just depend on the neighbors of the node: since every node has exactly 4 neighbors, and initially they all have the same values, we will never get different function values. However, we can look further and for example check how many of those 4 neighbors are connected to each other, or what set of labels we have at distance 2,3,... from the vertex, and then one of those ideas will be enough to find a solution for all 41 possible testcases (see the official analysis for more details).

Finally, in order to quickly generate such graphs, we can also use various approaches. I find the following one the most logical: start with any such graph, and then repeatedly apply random local modifications that don't change the degrees of the vertices (again, check out the official analysis for more details).

I have also enjoyed the way this problem used the interactive problem paradigm to encode the "challenge-response" setup that is not usually seen in programming contests.

Thanks for reading, and check back for more!

Tuesday, July 24, 2018

An obtuse week

The Jun 4 - Jun 10 week was the week of the Google Code Jam: the onsite advancers were determined both in the normal and in the distributed competition.

First off, the Google Code Jam 2018 Round 3 took place on Saturday (problems, results, top 5 on the left, analysis). Somewhat surprisingly, none of the full scores stood during the system testing. Errichto.rekt and ifsmirnov lost the least points at that stage :) Congratulations!

I found the problem Name-Preserving Network really exciting. You are given a number n between 10 and 50, and need to print a connected simple undirected graph with n vertices, and each vertex having degree exactly 4. The interactor will then randomly permute the vertices of your graph and give it back to you, and you need to then restore the permutation that was used. In other words, you need to find such graph without automorphisms, and be able to identify its vertices after they're shuffled. How would you approach this one?

The Distributed Code Jam 2018 Online Round followed a day later (problems, results, top 5 on the left, analysis). Errichto.rekt was at the top for the second day in a row, thanks to being one of only two solvers of the hardest problem E. Well done!

In my previous summary, I have mentioned an unusual TopCoder problem: You are given 3n sticks with lengths a, a+1, ..., a+3n-1. You need to find any way to split them into n triples in such a way that each triple forms a non-degenerate obtuse triangle, or report that there isn't one. n is up to 500, a is an integer between 1 and 10.

There are a few principal approaches to this kind of problem (did I already enumerate those on the blog? Please share a link, and also please add ones that I missed):

  • Just solve the problem on paper, in other words come up with a direct explicit construction.
  • Solve the problem on paper in two steps a-la induction: come up with a way to solve the problem for small instances of the problem, and also come up with a way to change a solution for n to a solution for n+5 (for some value of 5).
  • Only do the second inductive part on paper, and use brute force to find solutions to small instances.
  • Also replace the inductive part with something less formal: do some kind of greedy for most of the solution, and use brute force when the remaining problem is small enough.
The official analysis suggests to use the third approach, while I went with the last one since it requires the least amount of thinking :)

I like to code such solutions as a brute force that runs even for large values of n, with the greedy part being implicit by the order the brute force tries the possibilities: since for most of the decisions, we will never have time to come back to them, the first decision we try in the brute force is effectively the greedy decision. This way I don't have to explicitly choose the boundary between the greedy and the brute force, and thus can try different ideas faster.

You can take a look at my solution from the round for more details, but in short, the ordering that worked was: as the first attempt, try to pair the smallest remaining stick with the 1/3-rd and 2/3-rd ones in sorted order, and then go from those in both directions.

Thanks for reading, and check back for more!

Sunday, July 22, 2018

An extra log week

Codeforces Round 485 got the May 28 - Jun 3 week going (problems, results, top 5 on the left, analysis). OO0OOO00O0OOO0O00OOO0OO has tried an unusual problem solving order, but it didn't really help as tourist was faster overall and got the well-deserved first place. Congratulations!

The round thread is also notable for discussions about modern problemsetting practices (search for Um_nik's replies and surrounding comments).

On Saturday, TopCoder Open 2018 Round 2A saw the top-rated participants enter the competition (problems, results, top 5 on the left, parallel round resultsanalysis, my screencast). A lot of solutions failed challenges and system test in this round, and after the dust has settled it turned out that bmerry both had the highest coding phase score, and has protected the lead very well by adding 100 challenge points. Well done!

The hardest problem in this round allowed one to get quite creative. You are given 3n sticks with lengths a, a+1, ..., a+3n-1. You need to find any way to split them into n triples in such a way that each triple forms a non-degenerate obtuse triangle, or report that there isn't one. n is up to 500, a is an integer between 1 and 10.

Finally, AtCoder Grand Contest 025 wrapped up the week on Sunday (problems, results, top 5 on the left, analysis). Only Stonefeang was able to solve all problems, and thus got a clear first place. Contestants behind him solved quite varied subsets of problems in an attempt to score most points in the limited time available, but it did not really matter in the end. Congratulations to Stonefeang!

Thanks for reading, and check back for more.

Friday, July 20, 2018

A deterministic week

Codeforces hosted the Avito Code Challenge 2018 during the May 21 - May 27 week (problems, results, top 5 on the left, analysis). While OO0OOO00O0OOO0O00OOO0OO and tourist were very close during most of the contest, tourist was much faster with solving the hardest problem, and thus won with a comfortable margin in the end — well done!

In my previous summary, I have mentioned an interactive Yandex problem, which required one to locate the number n in a permutation of integers between 1 and n. You are given just the number n and can send queries to learn the permutation. Each query is a number k between 1 and n, and means "increase the number in k-th position in the array by 1". After performing the requested action, the system tells you the number of distinct values in the array (which initially contains the permutation), and you can send the next query which will be applied to the new array (which is not a permutation anymore). You must tell the original location of the number n after at most 50n queries.

The official analysis mentions a nice randomized solution, but there's actually a similar deterministic one as well. Let's increment all numbers by one in some order, for example from left to right, and for each number record the delta between the number of distinct elements after and before incrementing it. Two things happen for the number x:

1) If the number x-1 does not exist or was not yet incremented, then we lose x from the set of distinct numbers, this contributes -1 to the delta.

2) If the number x+1 does not exist or was already incremented, then we add x+1 to the set of distinct numbers, this contributes +1 to the delta.

If both of those things happen, the contributions add up, and the delta is 0.

Now let's once again increment all numbers one by one, but in reverse order to the first pass, and add the delta for each position to the delta we already remember for it. The "was already incremented" conditions will flip since we iterate in reverse order now, and thus for all numbers except 1 and n we will get exactly one -1 and exactly one +1, so the total delta will be 0.

For the number n, however, the second condition always holds, so we'll get one -1 and two +1's, for the total of +1. Similarly, for the number 1 we'll get the total of -1. This easily identifies the location of the number n after just 2n queries.

Thanks for reading, and check back for more!

Thursday, July 19, 2018

A penalty week

The competitive May 14 - May 20 week started with Codeforces Round 483 on Tuesday (problems, results, top 5 on the left, analysis). Problem D turned out to be almost unsolvable, and skipping it was the key to victory. Congratulations to fateice on solving all remaining problems in just under an hour!

TopCoder SRM 734 followed on Thursday (problems, results, top 5 on the left, analysis). The round has feature three relatively standard problems, in particular the last two problems should be good dynamic programming practice.

On Saturday Google Code Jam 2018 Round 2 narrowed the field to just 1000 competitors (problems, results, top 5 on the left, analysis). Getting into the top 1000 does not usually present a big challenge for the top competitors, so they can focus on competing for fun. This time Um_nik was the fastest to solve all problems, but he allowed one incorrect attempt and Gennady.Korotkevich claimed the first place. Congratulations to both!

Yandex.Algorithm 2018 Final Round took place in St Petersburg and online early on Sunday (problems with Yandex login, results, top 5 on the left, my screencast, analysis). The top 2 did not change from the Code Jam round, although this time Gennady has actually left the door wide open by solving the first five problems a lot slower than Um_nik and accumulating some penalty time — Um_nik just needed to get the last problem accepted before the end of the contest, but it did not happen. Congratulations to Gennady on the victory!

The easiest problem of the round, Problem E, required one to locate the number n in a permutation of integers between 1 and n. You are given just the number n and can send queries to learn the permutation. Each query is a number k between 1 and n, and means "increase the number in k-th position in the array by 1". After performing the requested action, the system tells you the number of distinct values in the array (which initially contains the permutation), and you can send the next query which will be applied to the new array (which is not a permutation anymore). You must tell the original location of the number n after at most 50n queries.

And finally, AtCoder Grand Contest 024 wrapped up the week (problems, results, top 5 on the left, my screencast, analysis). This time it was actually me who was the fastest to finish all problems, but I paid the price for the three incorrect attempts. Congratulations to Gennady on the victory!

I found problem F in this round quite educational: you are given a set of strings of length <=20 (possibly all such strings — see the problem statement for the input format that makes it possible to read the input quickly) and a number k. You need to find the longest string that is a subsequence of at least k of the given strings. In case there are many, you need to find the lexicographically smallest one.

Thanks for reading, and check back for more!