Editorial for COCI '11 Contest 6 #3 Zagrade


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

The first step is to find matching pairs of brackets. This is easily done by traversing the expression from left to right and using a stack to keep track of currently unmatched open brackets. More precisely, when we encounter some open bracket, we push its location to the stack. When we encounter a closed bracket, this bracket and the bracket at the top of the stack will form a matching pair. There are some wrong approaches for matching the brackets, and they were worth 40\% of the total number of points.

The next step is to generate all the possible expressions. There are two ways to do this, using bitmasks or using recursion. Recursion can decide which pairs of brackets to use, and some other function can remove those pairs and store the obtained expression. Here is the pseudocode:

choose(pair_index, total_pairs, removed_pairs):
    if pair_index = total_pairs:
        call gen_expression(removed_pairs)
        return
    add pair_index to removed_pairs
    choose(pair_index+1, total_pairs, removed_pairs)
    remove pair_index from removed_pairs
    choose(pair_index+1, total_pairs, removed_pairs)

Here we can substitute recursion with bitmasks. Idea is that any integer can tell us which brackets to remove if we see how that integer is written in binary form. If there is a digit 1 at some index in binary representation, then we will remove the corresponding pair of brackets, and otherwise we won't. Now we can count from 0 to 2^N-1, and generate all the possible expressions without the use of recursion.

Here is a good tutorial on this approach: https://www.topcoder.com/thrive/articles/A%20bit%20of%20fun:%20fun%20with%20bits

Finally, we must sort the obtained expressions and remove duplicates. A solution that doesn't take care of duplicates gets 70\% of the total number of points.


Comments

There are no comments at the moment.