L - Fenwick Tree Gym - 103861L(打表,树状数组)

题意:

一开始数组的每个数都是零
对于每次操作:

  1. 可以对一个数加上一个实数

  2. 在加上实数的同时,对应的i+lowbit(i)一直到<=n都会加上这个实数

  3. 不同操作可以加上不同的实数

给一个01字符串,如果当前位上为1,表明当前位上非0,否则是0
问从全零数组 到 给定字符串表示的状态 需要的操作次数

题解

:类似于树状数组,我们可以简单的打个lowbit的表
我们打16个数的表
1 2 4 8 16
2 4 8 16
3 4 8 16
4 8 16
5 6 8 16
6 8 16
7 8 16
8 16
9 10 12 16
10 12 16
11 12 16
12 16
13 14 16
14 16
15 16
我们可以发现,对于某一段数内,可以直接更新到某一个数的数量其实是有限的。
比如:
对于16这个数,直接更新到他的数有:8,12,14,15
所以,对于16当前的状态,我们只需要管8,12,14这三个状态即可。
因为不管前面什么状态,这三个状态最终的变化是这样的如果状态位是1,有点像dp,就说明就相当于操作了一次.这样问题就变得很简单了.

范围内有2个num,这样当前状态位可以是0或1
假设有1个num,当前位是0,需要ans++
有0个num,当前位是1,需要ans++;
还有一个问题就是怎么求,直接到他的数,我们仍然可以找规律
16 : 15(1111),14(1110),12(1100),8(1000)这样看起来就很清楚了,每次都减去一位1,所以我们求出2^n将其放到一个数组里每次减去就行了,减的下限就是lowbit(i),如lowbit(16)=0,所以我们减到大于0的那个数即可…

AC代码

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
#define int long long
using namespace std;
const int N = 100100;
int n;
string s;
int ans;
vector<int> cnt;
void get()
{
    int x=1;
    while(1){
        cnt.push_back(x);
        x*=2;
        if(x>N)break;
    }
}
int lowbit(int x){
      return x&(-x);
}
void solve()
{
    scanf("%lld", &n);
    cin >> s;
    s="x"+s;
    ans = 0;
    for (int i = 1; i <= n; i++)
    {
        int num=0;
        if(i%2==1){
            if(s[i]=='1') ans++;
            continue;
        }
        for(int k:cnt){
            if(k>=lowbit(i))break;
            if(i<=k) break;
            if(s[i-k]=='1') num++;
        }
        if(num==1 && s[i]=='0'){
            ans++;
        }
        if(num==0 && s[i]=='1'){
            ans++;
        }
    }
    printf("%lld\n", ans);
}
signed main()
{
    int t;
    scanf("%lld", &t);
    get();
    while (t--)
    {
        solve();
    }
    return 0;
}

原文链接:https://blog.csdn.net/qq_54783066/article/details/127484793

posted @ 2022-11-04 20:13  kingwzun  阅读(48)  评论(0编辑  收藏  举报