We refer “a possible substring of a string obtained by replacing each occurrence of ?
in S by 0
or 1
independently” to simply “a string obtained from S.” For simplicity, here we assume that an empty string can also be obtained from S too.
For the string S=s1s2…sN, for each i=0,1,…,N, let
- dp[i][0]:= (the number of strings obtained from the first i character of S, s1s2…si, ending with
0
);
- dp[i][1]:= (the number of strings obtained from the first i character of S, s1s2…si, ending with
1
).
Then, the value that should be printed for each query is dp[N][0]+dp[N][1] for S at each moment.
We will consider how to compute this.
First, obviously, dp[0][0]=dp[0][1]=0. We will now consider, for i=1,2,…,N, “how to find dp[i][0] and dp[i][1] when we know dp[i−1][0] and dp[i−1][1].”
We first consider si= 0
.
Any string obtained from s1s2…si−1 can be obviously obtained from s1s2…si too.
Any string that cannot be obtained from s1s2…si−1 that can be obtained from s1s2…si−1si by appending si= 0
is
a concatenation of a string obtained from s1s2…si−1 and 0
, that cannot be obtained from s1s2…si−1.
The number of “strings that are concatenations of a string obtained from s1s2…si−1 and 0
” is equal to the number of strings that can be obtained from s1s2…si−1, which is expressed as dp[i−1][0]+dp[i−1][1]+1 (where the last term 1 correspond to an empty string)
The number of strings that “can be obtained from s1s2…si−1” is dp[i−1][0]
(any string t1t2…tl ending with 0
that can be obtained from s1s2…si−1 can be constructed as a concatenation of t1t2…tl−1, which can be obtained from s1s2…si−1, and 0
).
Therefore, by appending si= 0
to the tail of s1s2…si−1, there are dp[i−1][1]+1 new strings ending with 0
obtained not from s1s2…si−1 but from s1s2…si−1si.
Therefore, when si= 0
,
- dp[i][0]=dp[i−1][0]+(dp[i−1][1]+1),
- dp[i][1]=dp[i−1][1].
Similarly, when si= 1
,
- dp[i][0]=dp[i−1][0],
- dp[i][1]=dp[i−1][1]+(dp[i−1][0]+1),
and when si= ?
,
- dp[i][0]=dp[i−1][0]+(dp[i−1][1]+1)
- dp[i][1]=dp[i−1][1]+(dp[i−1][0]+1)
Therefore, let
A0:=⎣⎢⎡100110101⎦⎥⎤,A1:=⎣⎢⎡110010011⎦⎥⎤,A?:=⎣⎢⎡110110111⎦⎥⎤,
then for each i=1,2,…,N we have
⎣⎢⎡dp[i][0]dp[i][1]1⎦⎥⎤=Asi⎣⎢⎡dp[i−1][0]dp[i−1][1]1⎦⎥⎤.
Especially,
⎣⎢⎡dp[N][0]dp[N][1]1⎦⎥⎤=AsNAsN−1⋯As1⎣⎢⎡dp[0][0]dp[0][1]1⎦⎥⎤=AsNAsN−1⋯As1⎣⎢⎡001⎦⎥⎤.
Therefore, each query can be processed by
computing the product of N matrices AsNAsN−1⋯As1,
and updating one of AsN,AsN−1,…,As1 to another matrix.
This can be achieved with a segment tree in an O(logN) time for each query.
Therefore, the problem has been solved in a total of O(N+QlogN) time.