[AcWing 242] 一个简单的整数问题


树状数组
区间修改,单点查询
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2e5 + 10;
int n, m;
LL a[N];
LL tr[N];
int lowbit(int x)
{
return x & -x;
}
void add(int x, int c)
{
for (int i = x; i <= n; i += lowbit(i))
tr[i] += c;
}
LL ask(int x)
{
LL res = 0;
for (int i = x; i; i -= lowbit(i))
res += tr[i];
return res;
}
void solve()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++) {
cin >> a[i];
add(i, a[i] - a[i - 1]);
}
while (m --) {
char op;
int x, l, r, d;
cin >> op;
if (op == 'Q') {
cin >> x;
cout << ask(x) << endl;
}
else {
cin >> l >> r >> d;
add(l, d);
add(r + 1, -d);
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
solve();
return 0;
}
- 使用树状数组维护差分数组的前缀和

浙公网安备 33010602011771号