Educational Codeforces Round 72 C.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.

Example

Input
4
0110
0101
00001000
0001000
Output
4
3
4
3

题目大意

给你一个二进制字符串s(只包含0和1),f(t)中t为一个二进制的数,f(t)为t的十进制形式。如果s的某个子串s[l-r]是好的,那么f(s[l-r])=r-l+1。问s中有多少好的子串。

题目分析

字符串的长度是2e5,但十进制的2e5转化为二进制也就不到二十位而已(220>2e5)。 因此我们可以找出s中所有可能的起点(s[i]=1的地方),往后枚举20位即可找出s中所有可能的数。
注意:还要记录这些子串的前导0,因为一个数的二进制的长度>=这个数的十进制,因此需要前导0来凑数。

代码如下7
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define LL long long
#define PII pair
using namespace std;
const int N=2e5+5;
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		string s;
		cin>>s;
		int ans=0;		//记录答案
		int pre=0;		//记录前导0
		for(int i=0;i<s.size();i++)
		{
			if(s[i]=='0') {pre++; continue;}	//如果这一位是0,那么记为下一个数的前导0
			int sum=1;			//找到的这个二进制数的十进制形式
			int r=i;			//i为起点,r为终点(一开始只有一位数,所有r=i)
			for(int j=0;j<=20;j++)		//往后枚举20位
			{
				if(sum<=pre+r-i+1) ans++;
				if(r+1>=s.size()) break;
				sum=sum*2+(s[++r]-'0');
			}
			pre=0;
		}
		cout<<ans<<endl;
	}
	return 0;
}

你可能感兴趣的:(Codeforces)