原题链接:https://agc022.contest.atcoder.jp/tasks/agc022_e
Median Replace
Problem Statement
Taichi thinks a binary string X of odd length N is beautiful if it is possible to apply the following operation N−12 N − 1 2 times so that the only character of the resulting string is ‘1’ :
Choose three consecutive bits of X and replace them by their median. For example, we can turn ‘00110’ into ‘010’ by applying the operation to the middle three bits.
Taichi has a string S consisting of characters ‘0’, ‘1’ and ‘?’. Taichi wants to know the number of ways to replace the question marks with ‘1’ or ‘0’ so that the resulting string is beautiful, modulo 109+7 10 9 + 7 .
Constraints
1≤|S|≤300000
|S| is odd.
All characters of S are either ‘0’, ‘1’ or ‘?’.
Input
Input is given from Standard Input in the following format:
S
Output
Print the number of ways to replace the question marks so that the resulting string is beautiful, modulo 109+7 10 9 + 7 .
Sample Input 1
1??00
Sample Output 1
2
There are 4 ways to replace the question marks with 0 or 1 :
11100 : This string is beautiful because we can first perform the operation on the last 3 bits to get 110 and then on the only 3 bits to get 1.
11000 : This string is beautiful because we can first perform the operation on the last 3 bits to get 110 and then on the only 3 bits to get 1.
10100 : This string is not beautiful because there is no sequence of operations such that the final string is 1.
10000 : This string is not beautiful because there is no sequence of operations such that the final string is 1.
Thus, there are 2 ways to form a beautiful string.
Sample Input 2
?
Sample Output 2
1
In this case, 1 is the only beautiful string.
Sample Input 3
?0101???10???00?1???????????????0????????????1????0
Sample Output 3
402589311
Remember to output your answer modulo 109+7 10 9 + 7 .
题目大意
考虑长度为 n n 的 串,保证 n n 是奇数,每次你可以选择连续的 个,并用这 3 3 个的中位数替换这 3 个数字。
显然每次操作长度减少, n−12 n − 1 2 之后变成一个长度为 1 1 的字符串,考虑这个字符串是 还是 1 1 。
出题人发现对于一些字符串,通过合适的操作,最后可以变为,对于另一些,无论怎么操作,都不能变为 1 1 。
输入一个由构成的字符串,你需要把 ? ? 替换为 或者 1 1 ,问有多少种替换方法,使得得到的字符串通过合适的操作,最后可以变为 。
题解
毕克讲的最有趣的一道题。。。
判断一个 01 01 串是否 beautiful b e a u t i f u l ,我们可以手动建一个“毕克自动机”:
其中,红色的边表示 1 1 ,蓝色的为,这样,我们就可以把 01 01 串放进自动机里跑一波,如果最后停在了 1,2 1 , 2 节点,那么这个串就是 beautiful b e a u t i f u l 的。
然后,我们就可以在自动机上做一个 dp d p , dp[i][j] d p [ i ] [ j ] 表示在字符串的第 i i 位,自动机的第个节点时,使得最后的串为 beautiful b e a u t i f u l 的方案数。
因为无法得知自己从哪儿转移,而且初始状态不可知,所以采用倒退 dp d p ,最后的答案储存在 dp[0][0] d p [ 0 ] [ 0 ] ,具体见代码。
代码
打表建自动机。
#include<bits/stdc++.h>
using namespace std;
const int M=3e5+5,mod=1e9+7;
int mmp[8][2]={3,1,5,2,2,2,4,7,3,3,6,1,5,5,3,1},dp[M][8],len,i,j;
char ch[M];
void in(){scanf("%s",ch);}
void ac()
{
len=strlen(ch);dp[len][1]=dp[len][2]=1;
for(i=len-1;i>=0;--i)for(j=0;j<8;++j)
{
if(ch[i]!='0')dp[i][j]+=dp[i+1][mmp[j][1]];
if(ch[i]!='1')dp[i][j]+=dp[i+1][mmp[j][0]];
dp[i][j]%=mod;
}
printf("%d",dp[0][0]);
}
int main(){in();ac();}