题目出处http://cs.scu.edu.cn/soj/problem.action?id=3099
线段树
题目中有一个操作是为某个区间的所有成员加上c;
用 d表示此时整个区间所有元素的增量
#include <iostream> using namespace std; #define ll long long const int MAXN = 100001; struct { int l, r; ll s, d; } nod[MAXN*3]; int a[MAXN]; void creat(int t, int l, int r) {//建树过程 if(l == r) { nod[t].l = nod[t].r = l, nod[t].s = a[l], nod[t].d = 0; return; } int m = (l+r) / 2; nod[t].l = l, nod[t].r = r, nod[t].d = 0; creat(t*2, l, m), creat(t*2+1, m+1, r); nod[t].s = nod[t*2].s + nod[t*2+1].s; } void inc(int t, int l, int r, int c) {//为[l-r]中元素加c if(l == nod[t].l && r == nod[t].r) {nod[t].d += c; return;}//区间增量改变 if(r <= nod[t*2].r) inc(t*2, l, r, c); else if(l >= nod[t*2+1].l) inc(t*2+1, l, r, c); else inc(t*2, l, nod[t*2].r, c), inc(t*2+1, nod[t*2+1].l, r, c); nod[t].s = nod[t*2].s + nod[t*2].d * (nod[t*2].r-nod[t*2].l+1) + nod[t*2+1].s + nod[t*2+1].d * (nod[t*2+1].r-nod[t*2+1].l+1);//区间和值又子区间得到, } ll query(int t, int l, int r) { if(nod[t].l == l && nod[t].r == r) return nod[t].s + nod[t].d * (r-l+1); ll sum; if(r <= nod[t*2].r) sum = query(t*2, l, r); else if(l >= nod[t*2+1].l) sum = query(t*2+1, l, r); else sum = query(t*2, l, nod[t*2].r) + query(t*2+1, nod[t*2+1].l, r); return sum + nod[t].d * (r-l+1);//区间的总量等于区间和值加上(增量乘以*区间元素个数) } int main() { int i, n, q, x1, x2, c; char s[2]; while(scanf("%d%d", &n, &q) != EOF) { for(i = 1; i <= n; i++) scanf("%d", &a[i]); creat(1, 1, n); while(q--) { scanf("%s%d%d", s, &x1, &x2); if(s[0] == 'C') {scanf("%d", &c); inc(1, x1, x2, c);} else printf("%lld\n", query(1, x1, x2)); } } return 0; }