Editorial for COCI '14 Contest 1 #3 Piramida
Submitting an official solution before solving the problem yourself is a bannable offence.
Firstly, let us notice that changing the word direction from row to row doesn't have any impact on the number of individual letters in a certain row.
A naive solution would be to simulate writing the letters into each row and count the number of appearances of individual letters in the matrix and then output the value from the matrix for each query. The memory complexity of this solution is
and time complexity
, which is enough for
of total points.
For a more effective solution, we need to examine how string looks written down in each row. There are two options:
for some
and
. In other words, string
is a substring of string
.
for some
and
. In other words, string
consists of a suffix of string
(possibly an empty one), then the whole word
repeated
times and, finally, a suffix of string
(possibly an empty one)
For example, if the word would be
, the
row of the pyramid would be:
In order to determine ,
and
for a certain row, we need to be able to determine what letter the word in that row begins with. It is easily shown that for row
that position is equal to the remainder of dividing number
with
. It is necessary to carefully implement this formula because
can be very big. When we have calculated the position, it is easy to determine parameters
,
and
.
Now we can come up with the formulas for certain cases. Let be the number of appearances of
letter of the alphabet in the substring
. The formulas are the following:
To implement this solution effectively, we need to be able to quickly calculate the value of function . We can do this by constructing a matrix
where the element at index
tells us how many times the
letter of the alphabet appears in the substring
. Then we calculate
by the formula
.
The memory complexity of this solution is , and time complexity
, which was enough for all the points in HONI.
In COCI, this solution was enough for of total points because the maximal string length was bigger, so a matrix of the dimension
couldn't fit in 32 MB. It was necessary to solve queries separately for each letter. In this case, instead of a matrix of the dimension
, a matrix of the dimension
was enough.
Comments