牛牛的Link Power II
链接:https://ac.nowcoder.com/acm/contest/3004/G
题解:https://ac.nowcoder.com/discuss/365306
@四糸智乃
前缀和与差分:https://blog.nowcoder.net/n/5aeb050bfc90486098a099e9336b1661
树状数组维护前缀和的前缀和:https://blog.nowcoder.net/n/bb352f0f59ea4509b0a7fc15b11fa5a8
示例1
输入
5
00001
7
1 1
2 5
2 1
1 2
1 4
1 3
1 1
输出
0
4
0
0
0
2
4
10
思路:
树状数组维护前缀和,
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn),注意取模时。
Code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
const int N = 1e5 + 5;
int n, m, q, pos;
ll c[2][N]; // 0-cnt, 1-sumpos
int lowbit(int x) {
return x & (-x);
}
void add(int k, int x, int val) {
while (x <= n) {
c[k][x] = ((c[k][x] + val) % mod + mod) % mod;
x += lowbit(x);
}
}
ll sum(int k, int x) {
ll res = 0;
while (x > 0) {
res = ((res + c[k][x]) % mod + mod) % mod;
x -= lowbit(x);
}
return res % mod;
}
int main () {
ios::sync_with_stdio(false), cin.tie(0);
string s;
cin >> n >> s;
ll ans = 0;
for (int i = 1; i <= n; i++) {
if (s[i - 1] == '1') {
ans = ((ans + sum(0, i) * i - sum(1, i)) % mod + mod) % mod;
add(0, i, 1);
add(1, i, i);
}
}
cout << ans << endl;
cin >> m;
while (m--) {
cin >> q >> pos;
if (q == 1) {
ll cnt1 = sum(0, pos), cnt2 = sum(0, n) - cnt1;
ll sum1 = sum(1, pos), sum2 = sum(1, n);
ans = ((ans + cnt1 * pos - sum1 + sum2 - sum1 - cnt2 * pos) % mod + mod) % mod;
add(0, pos, 1);
add(1, pos, pos);
} else {
add(0, pos, -1);
add(1, pos, -pos);
ll cnt1 = sum(0, pos), cnt2 = sum(0, n) - cnt1;
ll sum1 = sum(1, pos), sum2 = sum(1, n);
ans = ((ans - (cnt1 * pos - sum1 + sum2 - sum1 - cnt2 * pos)) % mod + mod) % mod;
}
cout << ans << endl;
}
return 0;
}