The Number Of Good Substrings
You are given a binary string s (recall that a string is binary if each character is either 0 or 1).
Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011)=3,f(00101)=5,f(00001)=1,f(10)=2,f(000)=0 and f(000100)=4.
The substring sl,sl+1,…,sr is good if r−l+1=f(sl…sr).
For example string s=1011 has 5 good substrings: s1…s1=1, s3…s3=1, s4…s4=1, s1…s2=10 and s2…s4=011.
Your task is to calculate the number of good substrings of string s.
You have to answer t independent queries.
Input
The first line contains one integer t (1≤t≤1000) — the number of queries.
The only line of each query contains string s (1≤|s|≤2⋅105), consisting of only digits 0 and 1.
It is guaranteed that ∑i=1t|si|≤2⋅105.
Output
For each query print one integer — the number of good substrings of string s.
二进制的一些理解和运用;
首先,要知道除了10(2)和1(1)可以不用前缀0以外,其他的数都需要前缀0,只是多少问题;
先记录每个1的位置和1前面的0的个数,然后枚举1后面20位(2^20已经比|s|大很多),算出每个位置与 1 组成的数所需要的前缀0,然后跟这个位置1的前缀0比较大小就行;
代码:
#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
//ios::sync_with_stdio(false);
using namespace std;
const int N=200100;
const int M=200100;
const ll mod=1e9+7;
struct Node{
int post,date;
}a[N];
int solve(string p){
int b=0;
int ans=0;
for(int i=p.length()-1;i>=0;i--){
ans+=(p[i]-'0')*(1<<b);
b++;
}
return ans;
}
int main(){
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
ll ans=0;
string s;
cin>>s;
int len=0,k=0;
for(int i=0;i<s.length();i++){
if(s[i]=='0') len++;
else if(s[i]=='1'&&len){
a[++k].date=len;
a[k].post=i;
len=0;
}
}
for(int i=0;i<s.length();i++){
if(s[i]=='1') ans++;
if(i!=s.length()-1&&s[i]=='1'&&s[i+1]=='0') ans++;
}
// cout<<ans<<endl;
for(int i=1;i<=k;i++){
int l=a[i].post;
string b="";
for(int j=0;j<20;j++){
if(l+j>=s.length()) break;
b+=s[l+j];
int c=solve(b)-j-1;
// cout<<b<<" "<<c<<endl;
if(c<=a[i].date&&c) ans++;
}
}
cout<<ans<<endl;
}
return 0;
}