Gym101954F Lighting(记忆化搜索)

暴力的做法就是枚举每一位选什么,但是过于暴力,我们只需要记忆化搜索一下,表示之后的有没有算过即可

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=5e5+10;
const int mod=1e9+7;
ll f[1010][1010][2];
int n,k;
string s;
ll dfs(int u,int one,int flag){
    if(u==-1){
        if(one+flag==k)
            return 1;
        return 0;
    }
    auto &x=f[u][one][flag];
    if(x!=-1)
        return x;
    x=0;
    if(s[u]=='1'&&flag){
        x=(x+dfs(u-1,one+1,1)%mod+dfs(u-1,one,1)%mod)%mod;
    }
    if(s[u]=='0'&&flag){
        x=(x+dfs(u-1,one,flag)%mod+dfs(u-1,one+1,0)%mod)%mod;
    }
    if(s[u]=='1'&&!flag){
        x=(x+dfs(u-1,one,1)%mod+dfs(u-1,one+1,0)%mod)%mod;
    }
    if(s[u]=='0'&&!flag){
        x=(x+dfs(u-1,one+1,0)%mod+dfs(u-1,one,0)%mod)%mod;
    }
    return x;
}
int main(){
    ios::sync_with_stdio(false);
    cin>>n>>k;
    int i;
    memset(f,-1,sizeof f);
    cin>>s;
    cout<<dfs(n-1,0,0)<<endl;
}
View Code

 

posted @ 2020-10-30 10:34  朝暮不思  阅读(65)  评论(0编辑  收藏  举报