线段树 && 树状数组
啊哈!第一篇文章~
树状数组 ↓
#include<iostream>
#include<cstdio>
using namespace std;
const int MAXN = 100010;
int n, num[MAXN], c[MAXN];
void add(int loc, int value)
{
for(int i = loc; i <= n; i += i & (-i))
c[i] += value;
}
int ask(int a, int b)
{
int ans = 0;
for(int i = b; i > 0; i -= i & (-i))
ans += c[i];
for(int i = a - 1; i > 0; i -= i & (-i))
ans -= c[i];
return ans;
}
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
scanf("%d", &num[i]);
add(i, num[i]);
}
int m, op, a, b;
scanf("%d", &m);
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d", &op, &a, &b);
if(op == 1)
add(a, b);
if(op == 2)
printf("%d\n", ask(a, b));
}
return 0;
}
线段树 ↓
#include<iostream>
#include<cstdio>
using namespace std;
const int MAXN = 200010;
typedef long long LL;
int n, num[MAXN];
struct dot
{
int l, r;
LL sum, add;
}tree[MAXN << 2];
void pushdown(int now)
{
if(tree[now].add)
{
tree[now << 1].sum += tree[now].add * (tree[now << 1].r - tree[now << 1].l + 1);
tree[now << 1].add += tree[now].add;
tree[now << 1 | 1].sum += tree[now].add * (tree[now << 1 | 1].r - tree[now << 1 | 1].l + 1);
tree[now << 1 | 1].add += tree[now].add;
tree[now].add = 0;
}
}
void update(int now)
{
tree[now].sum = tree[now << 1].sum + tree[(now << 1) + 1].sum;
}
void build(int now, int l, int r)
{
tree[now].l = l;
tree[now].r = r;
if(l == r)
{
tree[now].sum = num[l];
return ;
}
int mid = (l + r) >> 1;
build(now << 1, l, mid);
build(now << 1 | 1, mid + 1, r);
update(now);
}
void point_change(int now, int l, int r, int pos, LL value)
{
if(l == r)
{
tree[now].sum += value;
return ;
}
pushdown(now);
int mid = (l + r) >> 1;
if(pos <= mid)
point_change(now << 1, l, mid, pos, value);
else
point_change((now << 1) + 1, mid + 1, r, pos, value);
update(now);
}
void change(int now, int l ,int r, LL value)
{
if(l <= tree[now].l && tree[now].r <= r)
{
tree[now].sum += (tree[now].r - tree[now].l + 1) * value;
tree[now].add += value;
return ;
}
int mid = (tree[now].l + tree[now].r) >> 1;
pushdown(now);
if(l <= mid)
{
change(now << 1, l, r, value);
}
if(r > mid)
{
change(now << 1 | 1, l, r, value);
}
update(now);
}
LL ask(int now, int l, int r)
{
if(tree[now].l >= l && r >= tree[now].r)
{
return tree[now].sum;
}
pushdown(now);
int mid = (tree[now].l + tree[now].r) >> 1;
LL ans = 0;
if(l <= mid)
{
ans += ask(now << 1, l, r);
}
if(r > mid)
{
ans += ask(now << 1 | 1, l, r);
}
return ans;
}
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
scanf("%d", &num[i]);
}
build(1, 1, n);
int m, op, a, b;
scanf("%d", &m);
for(int i = 1; i <= m; i++)
{
scanf("%d", &op);
if(op == 1)
{
LL value;
scanf("%d%d%lld", &a, &b, &value);
change(1, a ,b, value);
point_change(1, 1, n, a, b);
}
if(op == 2)
{
scanf("%d%d", &a, &b);
printf("%lld\n", ask(1, a, b));
}
}
return 0;
}