设序列 ,,表示第 次向那个方向走。
重新定义题目中的序列 , 表示走完第 步到达的节点点权。
则 。
题目要求 ,即 。
的系数是 的若干次方,这个式子看着就很数位 DP,把 的贡献按照系数分类。
原式为:
发现此时 没有用处,只用限制 即可。
记 ,则原式 。
那么对 进行三进制数位 DP,由于 ,故从高位开始, 表示高 位已确定、、这一位需要向上进位 的前提下,剩余未确定位置的方案数。
答案和初值是显然的。
转移为 。
其中, 表示 这一位的数字,当 这一位为 ? 时,枚举 即可。
我们得到了 做法,但是题目要求 。
我们充分发扬人类智慧,使用递推实现转移,然后猜测 只有 个接近的非 位置,维护 表示非 区间的左右端点,只转移非 位置即可。
本地测试极限数据(全为 ?)大概 0.6 秒,复杂度 。
#include<bits/stdc++.h>
using namespace std;
int f[2][4005][4005];
//int f[50][100][50];
int l[2005][4005],r[2005][4005];
const int mod=1e9+7;
int d;
string s;
/*
//O(n^3)部分
const int MAXN=300;
int solve(int pos,int lst,int up){
if(up<0||up>MAXN) return 0;
if(pos==d){
return up==0;
}
if(f[pos][lst][up]!=-1){
return f[pos][lst][up];
}
int res=0;
for(int x=0;x<=2;x++){
if(lst+x<0) continue;
if(s[pos]!='?') res+=solve(pos+1,lst+x,up*3+(s[pos]-'0')-(lst+x));
else{
res+=solve(pos+1,lst+x,up*3+0-(lst+x));
res+=solve(pos+1,lst+x,up*3+1-(lst+x));
res+=solve(pos+1,lst+x,up*3+2-(lst+x));
}
res%=mod;
}
return f[pos][lst][up]=res;
}
*/
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>d>>s;
// d=2000;
// for(int i=1;i<=d;i++) s+='?';
vector<pair<int,int>> X[2];
for(int i=0;i<=2*d;i++) f[d&1][i][0]=1,X[d&1].push_back({i,0});
for(int pos=d-1;pos>=0;pos--){
int nxt=!(pos&1);
for(auto x:X[pos&1]) f[pos&1][x.first][x.second]=0;
// memset(f[pos&1],0,sizeof(f[pos&1]));
X[pos&1].clear();
for(int lst=0;lst<=2*d;lst++){
int nowl=s[pos]-'0',nowr=s[pos]-'0';
if(s[pos]=='?') nowl=0,nowr=2;
l[pos][lst]=2*d+1;
r[pos][lst]=-1;
for(int now=nowl;now<=nowr;now++){
for(int x=0;x<=2;x++){
for(int up1=l[pos+1][lst+x];up1<=r[pos+1][lst+x];up1++){
if((up1-now+lst+x)%3) continue;
int up=(up1-now+lst+x)/3;
f[pos&1][lst][up]=(f[pos&1][lst][up]+f[nxt][lst+x][up1])%mod;
if(f[pos&1][lst][up]){
X[pos&1].push_back({lst,up});
l[pos][lst]=min(l[pos][lst],up);
r[pos][lst]=max(r[pos][lst],up);
}
}
}
//up1=up*3+now-lst-x
//up=(up1-now+lst+x)/3
}
}
}
cout<<f[0][0][0]<<"\n";
return 0;
}