Append
Time limit1sMemory limit128 MB
Given an LZ-style encoding as a list of (back-reference, length) pairs, count how many prefix positions split it into two valid non-empty encodings whose concatenation reproduces the original string.
- Level
Hard8 of 10
- Topics
- String, Implementation, Brute force, Dynamic programming
- Solved
- No attempts yet
Problem
Consider the encoding scheme used by a well-known compression algorithm. We encode only sequences of lowercase letters. Such a sequence is encoded as a list of pairs , where is an integer and is either a single character (when ) or an integer with (when ).
Decoding processes the pairs in order and builds the output sequence:
- If , then is a character; append it to the end of the decoded sequence.
- If , then is an integer with ; append characters copied from the decoded sequence, starting positions before its current end.
For example, the pairs decode step by step: gives a; gives aa; gives aab; appends aab to give aabaab; the next appends aab to give aabaabaab; appends aa to give aabaabaabaa; and gives aabaabaabaac. Note that one string may have several different encodings.
For sequences and , write for their concatenation. Let denote an encoding of a lowercase-letter sequence . Given an encoding , count how many ways it can be split into two consecutive parts such that:
- is the prefix consisting of the first few pairs and is the remaining suffix of pairs;
- is itself a valid encoding of some sequence , and is itself a valid encoding of some sequence ;
- , and neither nor is empty.
Write a program that outputs this number.
Input
The input consists of several blocks of lines. Each block describes one encoding . A line of a block contains either two integers and (with ) separated by a single space, or the integer followed by a single space and a single lowercase letter. Each block is terminated by one empty line. The input may contain several such blocks, one after another.
Output
For each block, print a single line containing the number of ways the encoding can be written as with , where both and are non-empty and each part is a valid encoding on its own.