codeforces 1217C 二进制思维

题意

t组输入,对于每组,我们有个二进制串,求这个串的子串所表示的二进制值等于子串长度的子串个数

分析

我们知道,对于一个字符串,长度为 n n ,他的子串个数为: n ( n + 1 ) 2 \frac{n(n+1)}{2}
但这题我们枚举所有子串那肯定tle
我们发现串最长为: 2 1 0 5 < 2 18 2*10^{5}<2^{18}
于是18位二进制就可以表示所有的数据范围,然后长度不够用前导零补
思路为:
对于每个出现的1,记录这个位置离上个1的位置差值(也就是计算前导零的个数),然后这个1的位置往后跑18位,这样复杂度大概 O ( 18 n ) O(18*n)

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
template <typename T>
void out(T x) { cout << x << endl; }
ll fast_pow(ll a, ll b, ll p) {ll c = 1; while(b) { if(b & 1) c = c * a % p; a = a * a % p; b >>= 1;} return c;}
ll exgcd(ll a, ll b, ll &x, ll &y) { if(!b) {x = 1; y = 0; return a; } ll gcd = exgcd(b, a % b, y, x); y-= a / b * x; return gcd; }
int main()
{
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while(t --)
    {
        string s;
        cin >> s;
        int size = s.size();
        ll num = 0, pre = 0;
        for(int i = 0; i < size; i ++)
        {
            if(s[i] == '0')
                pre ++;
            else 
            {
                ll cnt = 0;
                for(int j = i; j < i + 20 && j < size; j ++)
                {
                    cnt = cnt * 2 + s[j] - '0';
                    int len = j - i + 1;
                    if(pre + len >= cnt)
                        num ++;
                }
                pre = 0;
            }
        }
        cout << num << endl;
    }
}

原创文章 83 获赞 6 访问量 2762

猜你喜欢

转载自blog.csdn.net/qq_43101466/article/details/102557590