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.

Suppose that the root of the tree is not labeled 1, but with an arbitrary label x.

For some x, let fi(x) be the value of all paths in the set described by the substring of the input starting with the ith character.

The following recursive relations hold:

  1. fi(x)=fi+1(x); if the ith character is P (we stay in the root of the tree, with value x)
  2. fi(x)=fi+1(2x); if the ith character is L (we move to the left child, with value 2x)
  3. fi(x)=fi+1(2x+1); if the ith character is R (we move to the right child, with value 2x+1)
  4. fi(x)=fi+1(x)+fi+1(2x)+fi+1(2x+1); if the ith character is *

The base case is the empty substring – fN+1(x)=x.

The recursive formulas are linear, meaning that we only add constants or multiply by them. Because of this every term fi(x) can be written in the form fi(x)=Aix+Bi.

The above recursive formulas can then be rewritten as:

  1. fi(x)=Ai+1x+Bi+1
  2. fi(x)=Ai+1(2x)+Bi+1=(2Ai+1)x+Bi+1
  3. fi(x)=Ai+1(2x+1)+Bi+1=(2Ai+1)x+(Ai+1+Bi+1)
  4. fi(x)=Ai+1x+Bi+1+Ai+1(2x)+Bi+1+Ai+1(2x+1)+Bi+1=(5Ai+1)x+(Ai+1+3Bi+1)

The output is f1(1)=A11+B1.

We can use dynamic programming to calculate the sequences A and B. Because the terms in the sequences can get large, it is required to implement big integer arithmetic supporting long addition.


Comments

There are no comments at the moment.