这题的要点是线段树的成段更新,和LAZY思想,用LAZY思想能减少时间,注意存放数据要用long long,不知道为什么这题输入一定要用__int64 的 %I64d.
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#define maxn 100000
#define mem(a) memset(a, 0, sizeof(a))
using namespace std;
long long sum[maxn * 4 + 5];
long long col[maxn * 4 + 5];
void build(int l, int r, int n)
{
if(l == r)
{
scanf("%I64d", &sum[n]);
return;
}
int mid = (l + r) / 2;
build(l, mid, n * 2);
build(mid + 1, r, n * 2 + 1);
sum[n] = sum[n * 2] + sum[n * 2 + 1];
}
void add(int l, int r, int n, int ll, int rr, int x)
{
if(l >= ll&&r <= rr)
{
sum[n] += ((r - l + 1) * (long long)x);
col[n] += x;
return;
}
if(col[n])
{
col[n * 2] += col[n];
col[n * 2 + 1] += col[n];
sum[n * 2] += (col[n] * (r - l + 1 - (r - l + 1) / 2));
sum[n * 2 + 1] += (col[n] * ((r - l + 1) / 2));
col[n] = 0;
}
int mid = (l + r) / 2;
if(ll <= mid)
add(l, mid, n * 2, ll, rr, x);
if(rr > mid)
add(mid + 1, r, n * 2 + 1, ll, rr, x);
sum[n] = sum[n * 2] + sum[n * 2 + 1];
}
long long ans(int l, int r, int n, int ll, int rr)
{
if(l >= ll&&r <= rr)
{
return sum[n];
}
if(col[n])
{
col[n * 2] += col[n];
col[n * 2 + 1] += col[n];
sum[n * 2] += (col[n] * (r - l + 1 - (r - l + 1) / 2));
sum[n * 2 + 1] += (col[n] * ((r - l + 1) / 2));
col[n] = 0;
}
int mid = (l + r) / 2;
long long res = 0;
if(ll <= mid)
res += ans(l, mid, n * 2, ll, rr);
if(rr > mid)
res += ans(mid + 1, r, n * 2 + 1, ll, rr);
return res;
}
int main(int argc, char *argv[])
{
int q, a, b, v, i, num;
char ch;
scanf("%d%d", &num, &q);
build(1, num, 1);
scanf("%*c");
for(i = 0;i < q;i++)
{
scanf("%c", &ch);
if(ch == 'Q')
{
scanf("%d%d%*c", &a, &b);
printf("%lld\n", ans(1, num, 1, a, b));
}
else if(ch == 'C')
{
scanf("%d%d%d%*c", &a, &b, &v);
add(1, num, 1, a, b, v);
}
}
return 0;
}