P9883题解

· · 题解

解决方法

  1. update 函数其实是树状数组的修改功能
  2. pos & (-pos) 其实就是 lowbit

维护一个 cnt 数组,此时可以分类讨论一下:

当 c[i] 是 0 时,对于 cnt[i]:

\begin{cases} cnt[i] = 0 & \text{不改变}\\ cnt[i] = 1 & \text{执行操作} \\ cnt[i] \ge 2 & \text{不改变} \end{cases}

因为当 cnt[i]=1 时,需要把前面的影响抵消掉,如果 cnt[i] \ge 2,也可以抵消,他说是实数,所以 0.5 + 0.5 = 1 是可行的。

当 c[i] 是 1 时,对于 cnt[i]:

\begin{cases} cnt[i] = 0 & \text{执行操作}\\ cnt[i] = 1 & \text{不改变} \\ cnt[i] \ge 2 & \text{不改变} \end{cases}

虽然执行 update 是要将所有 lowbit \le n 都更新,但其实只要更新下一个,因为下一个也会给下一个的下一个更新 \dots,这样子,只需要 O(1) 的时间复杂度就可以更新。

记录一下 ans 就好了。

代码:


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
const int MAXN = 1e5 + 7;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;

int t, n;
int cnt[MAXN], ans;

int lowbit(int x) {
    return x & -x;
}

string s;

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> t;
    while (t--) {
        ans = 0;
        memset(cnt, 0, sizeof(cnt));
        cin >> n;
        cin >> s;
        for (int i = 1; i <= n; i++) {
            if (s[i - 1] == '0') {
                if (cnt[i] == 1)
                    ans++, cnt[i]++;
            } else {
                if (cnt[i] == 0)
                    ans++, cnt[i]++;
                int next = i + lowbit(i);
                if (next <= n)
                    cnt[next]++;
            }
        }
        cout << ans << endl;
    }
    return 0;
}