算法1
线段树标记永久化
时间复杂度
参考文献
C++ 代码
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N = 100010;
struct Node{
int l, r;
LL sum, add;
}tr[N * 4];
LL a[N];
int n, m;
LL intersaction(int al, int ar, int bl, int br)
{
return min(ar, br) - max(al, bl) + 1;
}
void pushup(int u)
{
tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
}
void build(int u, int l, int r)
{
tr[u].l = l, tr[u].r = r, tr[u].sum = 0, tr[u].add = 0;
if(l == r)
{
tr[u].sum = a[l];
return;
}
int mid = (l + r) / 2;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
pushup(u);
}
LL query(int u, int l, int r, LL add)
{
if(l <= tr[u].l && r >= tr[u].r) return tr[u].sum + add * intersaction(l, r, tr[u].l, tr[u].r);
add += tr[u].add;
int mid = (tr[u].l + tr[u].r) / 2;
LL res = 0;
if(l <= mid) res += query(u << 1, l, r, add);
if(r > mid) res += query(u << 1 | 1, l, r, add);
return res;
}
void modify(int u, int l, int r, LL d)
{
tr[u].sum += intersaction(l, r, tr[u].l, tr[u].r) * d;
if(tr[u].l >= l && tr[u].r <= r)
{
tr[u].add += d;
return;
}
int mid = (tr[u].l + tr[u].r) / 2;
if(l <= mid) modify(u << 1, l, r, d);
if(r > mid) modify(u << 1 | 1, l, r, d);
}
int main()
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; ++ i) scanf("%lld", &a[i]);
build(1, 1, n);
while(m --)
{
char op[2];
scanf("%s", op);
if(*op == 'Q')
{
int l, r;
scanf("%d%d", &l, &r);
printf("%lld\n", query(1, l, r, 0ll));
}
else
{
int l, r;
LL d;
scanf("%d%d%lld", &l, &r, &d);
modify(1, l, r, d);
}
}
return 0;
}