[ARC059F] バイナリハック题解

· · 题解

Sol

一道非常水的 dp 题。

先看数据 N\le 5000,考虑 O(n^2) dp。

对于题目的三个操作中,我们唯一需要仔细思考的就是对于退格的操作,因为退格操作是不需要去保证退掉的字符 0/1 的,但需要保证退掉之后剩下的字符是我们想要的。那么我们就需要将 dp 的一维状态设计为可以去处理退格的。

记 f_{i,j} 表示当前进行了 i 次操作,当前已经匹配了 j 个字符。(这里使用刷表法转移)

那么我们对于输入 0/1 的操作转移就非常轻松:f_{i+1,j+1}\gets f_{i,j}。

那如何很好的处理退格呢,前面说了不需要去知道被退的字符,那么我们退掉的字符就会有两种可能,而我们 dp 的第二位有保证了前 j 个字符匹配的,我们就可以直接进行转移了:

\begin{cases}f_{i+1,j-1}\gets f_{i,j}\times 2 & (j>0)\\f_{i+1,j-1}\gets f_{i,j} & (j=0)\end{cases}

然后这道紫题就通过了。

Code

#include<bits/stdc++.h>
#define db doub
#define inf LONG_LONG_MAX
#define fir first
#define sec second
#define ls (x<<1)
#define rs (x<<1|1)
#define mid ((l+r)>>1)
#define Pr(i,j) pair<i,j>
#define PB(i) push_back(i)
#define MP(i,j) make_pair(i,j)
#define Fo(i,j) for(auto i:j)
#define mem(i,j) memset(i,j,sizeof(i))
#define FO(i,j,k) for(int i=j;i;i=k)
#define FFF(i,j,k) for(auto i=j;i!=k;++i)
#define For(i,j,k) for(int i=j;i<=k;++i)
#define FoR(i,j,k) for(int i=j;i^k;++i)
#define FOR(i,j,k) for(int i=j;i>=k;--i)
using namespace std;
template <typename _Tp>void read(_Tp& first) {
    _Tp x = 0, f = 1; char c = getchar();
    while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c ^ '0'), c = getchar();
    first = x * f;
}
#define N 5005
#define Mod 1000000007
#define int long long
int n,m;
int f[N][N];
string s;
signed main(){
    read(n);
    cin>>s;
    s=' '+s;
    m=s.size()-1;
    f[0][0]=1;
    For(i,0,n)
    For(j,0,n){
        f[i+1][j+1]+=f[i][j];
        f[i+1][max(j-1,0ll)]+=f[i][j]*(1+(j>0));
        f[i+1][j+1]%=Mod;
        f[i+1][max(j-1,0ll)]%=Mod;
    }
    cout<<f[n][m];
}