题目:http://www.lightoj.com/volume_showproblem.php?problem=1164
题意:给定一个数组初始全为0,有两种操作,一种是把区间[l, r]内的元素全都加上某个值,一种求区间[l, r]元素和
思路:经典线段树题目
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
#include <string>
#include <queue>
#include <set>
#include <list>
using namespace std;
typedef long long ll;
const int N = 100010;
struct node
{
int l, r;
ll val, mark;
}s[N*4];
int cas;
void push_up(int k)
{
s[k].val = s[k<<1].val + s[k<<1|1].val;
}
void push_down(int k)
{
if(s[k].mark)
{
s[k<<1].mark += s[k].mark, s[k<<1|1].mark += s[k].mark;
s[k<<1].val += (s[k<<1].r - s[k<<1].l + 1) * s[k].mark;
s[k<<1|1].val += (s[k<<1|1].r - s[k<<1|1].l + 1) * s[k].mark;
s[k].mark = 0;
}
}
void build(int l, int r, int k)
{
s[k].l = l, s[k].r = r, s[k].mark = 0;
if(l == r)
{
s[k].val = 0; return;
}
int mid = (l + r) >> 1;
build(l, mid, k << 1);
build(mid + 1, r, k << 1|1);
push_up(k);
}
void update(int l, int r, int val, int k)
{
if(l <= s[k].l && s[k].r <= r)
{
s[k].mark += val;
s[k].val += (ll)(s[k].r - s[k].l + 1) * val;
return;
}
push_down(k);
int mid = (s[k].l + s[k].r) >> 1;
if(l <= mid) update(l, r, val, k << 1);
if(r > mid) update(l, r, val, k << 1|1);
push_up(k);
}
ll query(int l, int r, int k)
{
if(l <= s[k].l && s[k].r <= r) return s[k].val;
push_down(k);
int mid = (s[k].l + s[k].r) >> 1;
ll res = 0;
if(l <= mid) res += query(l, r, k << 1);
if(r > mid) res += query(l, r, k << 1|1);
return res;
}
int main()
{
int t, n, m, a, b, c, d;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &m);
build(1, n, 1);
printf("Case %d:\n", ++cas);
for(int i = 0; i < m; i++)
{
scanf("%d", &a);
if(a == 0)
{
scanf("%d%d%d", &b, &c, &d);
update(b+1, c+1, d, 1);
}
else
{
scanf("%d%d", &b, &c);
printf("%lld\n", query(b+1, c+1, 1));
}
}
}
return 0;
}