超级树状数组
超级树状数组,就是用树状数组来进行区间修改+区间查询操作的东西,好处是和线段树相比快了不少。
首先先来复习一下普通的树状数组
int tree[MAXN];
int lowbit(int x) {
return x & -x;
}
void update(int x, int d) {
while (x <= n) {
tree[x] += d;
x += lowbit(x);
}
}
int sum(int x) {
int ans = 0;
while (x) {
ans += tree[x];
x -= lowbit(x);
}
return ans;
}
注意: update
是 sum
是求
求区间
当求第一个数时,我们只需将
#include <cstring>
#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#define endl '\n'
#define x first
#define y second
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef double db;
typedef pair<ll, ll> pll;
inline ll read() {
char ch = getchar(); ll fu = 0, s = 0;
while(!isdigit(ch)) fu |= (ch == '-'), ch = getchar();
while(isdigit(ch)) s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar();
return fu ? -s : s;
}
const int MAXN = 1e5 + 10;
int n, m, a[MAXN];
struct Node {
ll tree[MAXN];
int lowbit(int x) {
return x & -x;
}
void update(int x, ll d) {
while (x <= n) {
tree[x] += d;
x += lowbit(x);
}
}
ll sum(int x) {
ll ans = 0;
while (x) {
ans += tree[x];
x -= lowbit(x);
}
return ans;
}
} tr1, tr2;
void solve() {
n = read(), m = read();
for (int i = 1; i <= n; i++) {
a[i] = read();
ll t = a[i] - a[i - 1];
tr1.update(i, t);
tr2.update(i, (i - 1) * t);
}
while (m--) {
int op = read(), x = read(), y = read(), k;
if (op == 1) {
k = read();
tr1.update(x, k);
tr1.update(y + 1, -k);
tr2.update(x, (x - 1) * k);
tr2.update(y + 1, -y * k);
} else {
printf("%lld\n", (tr1.sum(y) * y - tr2.sum(y)) - (tr1.sum(x - 1) * (x - 1) - tr2.sum(x - 1)));
}
}
}
signed main() {
int T = 1;
// T = read();
while(T--) solve();
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现