您的位置:首页 > 理论基础 > 数据结构算法

【Codevs】1082 线段树练习 3 && 线段树模板

2016-05-08 10:05 267 查看

没用的题面 –>

题目描述 Description

给你N个数,有两种操作:

1:给区间[a,b]的所有数增加X
2:询问区间[a,b]的数的和。


输入描述 Input Description

第一行一个正整数n,接下来n行n个整数,
再接下来一个正整数Q,每行表示操作的个数,
如果第一个数是1,后接3个正整数,
表示在区间[a,b]内每个数增加X,如果是2,
表示操作2询问区间[a,b]的和是多少。


pascal选手请不要使用readln读入

输出描述 Output Description

对于每个询问输出一行一个答案

样例输入 Sample Input

3

1

2

3

2

1 2 3 2

2 2 3


样例输出 Sample Output

9


数据范围及提示 Data Size & Hint

数据范围
1<=n<=200000
1<=q<=200000


代码– >

#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#define L(x) (x << 1)
#define R(x) (x << 1 | 1)
#define SZ(x) (tree[x].r - tree[x].l + 1)
using namespace std;
typedef long long LL;
const int MAXN = 1999997;

LL num[MAXN];
struct doc{
LL l, r, sum, add;
}tree[MAXN << 2];

void update(LL p)
{
tree[p].sum = tree[L(p)].sum + tree[R(p)].sum;
return ;
}

void build(LL p, LL l, LL r)
{
tree[p].l = l;
tree[p].r = r;
if(l == r)
{
tree[p].sum = num[l];
return ;
}
LL mid = (tree[p].l + tree[p].r) / 2;
build(L(p),l,mid);
build(R(p),mid + 1, r);
update(p);
return ;
}

void spread(LL p)
{
if(tree[p].add)
{
tree[L(p)].add += tree[p].add;
tree[R(p)].add += tree[p].add;
tree[L(p)].sum += (tree[p].add * SZ(L(p)));
tree[R(p)].sum += (tree[p].add * SZ(R(p)));
tree[p].add = 0;
update(p);
return ;
}
else return;
}

void change(LL l, LL r, LL p, LL x)
{
if(l <= tree[p].l && r >= tree[p].r)
{
tree[p].add += x;
tree[p].sum += (SZ(p) * x);
return ;
}
spread(p);
LL mid = (tree[p].l + tree[p].r) / 2;
if(l <= mid)
change(l,r,L(p),x);
if(r > mid)
change(l,r,R(p),x);
update(p);
return;
}

LL ask(LL l, LL r, LL p)
{
if(l <= tree[p].l && r >= tree[p].r)
return tree[p].sum;
spread(p);
LL mid = (tree[p].l + tree[p].r ) / 2;
LL ans = 0;
if(l <= mid)
ans += ask(l,r,L(p));
if(r > mid)
ans += ask(l,r,R(p));
update(p);
return ans;
}

int main()
{
LL n, Q;
scanf("%lld",&n);
for(LL i = 1; i <= n; i ++)
scanf("%lld",&num[i]);
build(1,1,n);
scanf("%lld",&Q);
for(LL i = 1; i <= Q; i ++)
{
LL t;
LL a,b,x;
scanf("%lld",&t);
if(t == 1)
{
scanf("%lld%lld%lld",&a,&b,&x);
change(a,b,1,x);
}
else if(t == 2)
{
scanf("%lld%lld",&a,&b);
printf("%lld\n",ask(a,b,1));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息