Editorial for COCI '08 Contest 2 #5 Setnja
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.
Submitting an official solution before solving the problem yourself is a bannable offence.
Suppose that the root of the tree is not labeled , but with an arbitrary label .
For some , let be the value of all paths in the set described by the substring of the input starting with the character.
The following recursive relations hold:
- ; if the character is
P
(we stay in the root of the tree, with value ) - ; if the character is
L
(we move to the left child, with value ) - ; if the character is
R
(we move to the right child, with value ) - ; if the character is
*
The base case is the empty substring – .
The recursive formulas are linear, meaning that we only add constants or multiply by them. Because of this every term can be written in the form .
The above recursive formulas can then be rewritten as:
The output is .
We can use dynamic programming to calculate the sequences and . Because the terms in the sequences can get large, it is required to implement big integer arithmetic supporting long addition.
Comments