我们需要构造字符串 ,其中每个位置 由所有合法字符串在位置 的字符决定。合法字符串需要满足:
- 恰好有 个 。
- 没有相邻的 。
那么,对于每个位置 :
- 如果 是确定的( 或 ),则 直接取该字符。
- 如果 是 ,需要检查:
- 强制该位置为 时,是否存在合法方案。
- 强制该位置为 时,是否存在合法方案。
那么,我们为了优化,就要用到一些特别的手段啦。
DP 预处理
使用前后缀 DP 来检查可行性:
前缀数组():
- :前 个字符以 结尾时的最小 数。
- :前 个字符以 结尾时的最大 数。
- :前 个字符以 结尾时的最小 数。
- :前 个字符以 结尾时的最大 数。
后缀数组():
- :从 到末尾以 开头时的最小 数。
- :从 到末尾以 开头时的最大 数。
- :从 到末尾以 开头时的最小 数。
- :从 到末尾以 开头时的最大 数。
对于每个 位置 ,结合前缀和后缀信息检查两种选择的可行性,确定 。
我们就做完啦!
代码实现
#include<bits/stdc++.h>
#define IXcape cout<<endl;return 0
#define Venti cout<<"\nVenti!\n"
#define int long long
using namespace std;
const int V=2e5+10,INF=1e18;
int pm0[V],px0[V],pm1[V],px1[V];
int sm0[V],sx0[V],sm1[V],sx1[V];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N,K;
string S;
cin>>N>>K>>S;
pm0[0]=0;px0[0]=0;
pm1[0]=INF;px1[0]=-INF;
for(int i=1;i<=N;i++){
if(S[i-1]=='.'){
pm0[i]=min(pm0[i-1],pm1[i-1]);
px0[i]=max(px0[i-1],px1[i-1]);
pm1[i]=INF;
px1[i]=-INF;
}
else if(S[i-1]=='o'){
pm0[i]=INF;
px0[i]=-INF;
pm1[i]=pm0[i-1]+1;
px1[i]=px0[i-1]+1;
}
else{
pm0[i]=min(pm0[i-1],pm1[i-1]);
px0[i]=max(px0[i-1],px1[i-1]);
pm1[i]=pm0[i-1]+1;
px1[i]=px0[i-1]+1;
}
}
sm0[N+1]=0;sx0[N+1]=0;
sm1[N+1]=INF;sx1[N+1]=-INF;
for(int i=N;i>=1;i--){
if(S[i-1]=='.'){
sm0[i]=min(sm0[i+1],sm1[i+1]);
sx0[i]=max(sx0[i+1],sx1[i+1]);
sm1[i]=INF;
sx1[i]=-INF;
}
else if(S[i-1]=='o'){
sm0[i]=INF;
sx0[i]=-INF;
sm1[i]=sm0[i+1]+1;
sx1[i]=sx0[i+1]+1;
}
else{
sm0[i]=min(sm0[i+1],sm1[i+1]);
sx0[i]=max(sx0[i+1],sx1[i+1]);
sm1[i]=sm0[i+1]+1;
sx1[i]=sx0[i+1]+1;
}
}
string T(N,' ');
for(int i=1;i<=N;i++){
if(S[i-1]=='.'){
T[i-1]='.';
}
else if(S[i-1]=='o'){
T[i-1]='o';
}
else{
int ll,lr,rl,rr;
if(i==1){
ll=0;lr=0;
}
else{
ll=min(pm0[i-1],pm1[i-1]);
lr=max(px0[i-1],px1[i-1]);
}
if(i==N){
rl=0;rr=0;
}
else{
rl=min(sm0[i+1],sm1[i+1]);
rr=max(sx0[i+1],sx1[i+1]);
}
bool f1=false;
if(ll<=lr&&rl<=rr){
if(ll+rl<=K&&K<=lr+rr){
f1=true;
}
}
int ll2,lr2,rl2,rr2;
if(i==1){
ll2=0;lr2=0;
}
else{
ll2=pm0[i-1];
lr2=px0[i-1];
}
if(i==N){
rl2=0;rr2=0;
}
else{
rl2=sm0[i+1];
rr2=sx0[i+1];
}
bool f2=false;
if((i==1||(pm0[i-1]!=INF&&px0[i-1]!=-INF))&&
(i==N||(sm0[i+1]!=INF&&sx0[i+1]!=-INF))){
if(ll2+rl2<=K-1&&K-1<=lr2+rr2){
f2=true;
}
}
if(f1&&f2){
T[i-1]='?';
}
else if(f1){
T[i-1]='.';
}
else if(f2){
T[i-1]='o';
}
else{
T[i-1]='?';
}
}
}
cout<<T;
IXcape;
}时间复杂度 。