参考这里
这是个经典问题,我们考虑记忆化搜索的过程,那么每次一个状态x,会产生新状态 ~x+1什么的,而这个状态数总数是
O(logn)
的
举个链接中的例子
1010110 –> 10110 –> 110 -> 10
0101010 –> 1010
所产生的所有串的数目刚好是x的位数减去末尾的0的数目
那么我们就可以直接写一个记忆化搜索,然而这不优美
可以直接从低向上DP,u d分别表示 后缀 x 和 ~x+1的答案
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1000005;
int n;
char s[N];
int main(){
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
scanf("%s",s+1); n=strlen(s+1);
int r=n,l=1;
while (l<=n && s[l]=='0') l++;
while (r && s[r]=='0') r--;
if (!r) return printf("0"),0;
int u=1,d=1;
for (int i=r-1;i>=l;i--)
if (s[i]=='1')
u=min(u,d)+1;
else
d=min(u,d)+1;
printf("%d\n",2*u-1);
return 0;
}
BZOJ这题是个4进制 不过还是一样的
就是需要点细节
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
using namespace std;
typedef pair<int,int> abcd;
const int N=10005;
const int P=1e9;
char s[N]; int n;
int b[N],a[N];
int m;
abcd Min(abcd A,abcd B){
if (A.first==B.first) return abcd(A.first,(A.second+B.second)%P);
return min(A,B);
}
abcd operator + (abcd &A,int B){
return abcd(A.first+B,A.second);
}
int main(){
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
scanf("%s",s+1); n=strlen(s+1);
for (int i=1;i<=n;i++) b[i]=s[n-i+1]-'0';
while (n){
int rest=0,t;
for (int i=n;i;i--)
t=rest,rest=(rest*10+b[i])%4,b[i]=(t*10+b[i])/4;
while (n>0 && b[n]==0) n--;
a[++m]=rest;
}
int l=1;
while (a[l]==0) l++;
abcd u=Min(abcd(a[l],1),abcd(4-a[l]+1,1)),d=Min(abcd(3-a[l]+1,1),abcd(4-(3-a[l]+1)+1,1));
for (int i=l+1;i<=m;i++){
abcd nu,nd;
nu=Min(u+a[i],d+(3-a[i]+1));
nd=Min(d+(3-a[i]),u+(3-(3-a[i])+1));
u=nu; d=nd;
}
printf("%d\n",u.second);
return 0;
}