The bracket problem: why I always finished the practice tasks
2002
At the 2002 Latvian Olympiad in Informatics I was the only contestant to score 100 on two problems. Progmeistars gave me its special prize for it, which goes to the quality of solutions, not to the total score.
Behind one of those problems was a training session. In class we had worked through a problem about an “operation with brackets”, and at the olympiad almost the same one came up (more on it below). I always finished practice problems to the end, and I was the only one who solved it for full marks. The strongest student in our group lost tests on time: in the output he had used + instead of bitwise OR.
The problem was called “Operācija @”, the third problem of day one of the final round, 25 March 2002. An operation @ is defined on the digits 0 to n (n ≤ 9) by a table. For n = 2, for example:
@ | 0 1 2
---+------
0 | 1 1 0
1 | 2 1 0
2 | 1 2 2
The operation is not commutative: 0@1 = 1, but 1@0 = 2. Nor is it associative: (0@1)@2 = 0, but 0@(1@2) = 1. So where the brackets go changes the result.
Given a string of up to 250 digits x1x2…xk, for each t from 0 to n you answer VAR or NEVAR: can the brackets in x1@x2@…@xk be placed so that it comes out as t. Two seconds per test. For the sample string 11110 the answer is VAR, NEVAR, VAR: (1@(1@1))@(1@0) = 0 and (((1@1)@1)@1)@0 = 2, while 1 cannot be reached at all.
The solution is dynamic programming over segments: for each segment of the string keep the set of values it can produce, and build the set of a long segment from every way of cutting it into two shorter ones. A set of ten digits is ten bits, and sets are merged with OR.
At heart, DP like this is the same recursion, only with memory. You try cutting the segment at every place and go down inside, but if the options for, say, characters 5 to 20 are already computed, you take them from the table and go no deeper. Recursion is easier to think in; the only thing that can get in the way is stack depth, and on a 250-character string that is no problem. When we went through DP at the courses, someone from another town complained: “Nobody told us about DP.” Sergey Ilyich replied: “You could have invented it.”
Later that year came bronze at the Baltic olympiad in Vilnius and gold at the International Olympiad in Korea, and for the olympiads, awards from the Government of Latvia and the Riga City Council (its Golden Pen).
What I took from it: a practice problem you finish to the end will one day turn up in the exam.