3468-A Simple Problem with Integers 线段树(区间增减,区间求和)
2024-08-23 08:09:23
A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 110077 | Accepted: 34272 | |
Case Time Limit: 2000MS |
Description
You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.
Input
The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.
Output
You need to answer all Q commands in order. One answer in a line.
Sample Input
10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4
Sample Output
4
55
9
15
题意:n个数字,q次操作,每次可以区间增减,或者查询区间的和
#include<cstdio>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define MAXN 100100
#define LL long long
LL sum[MAXN<<];
LL add[MAXN<<];
int n,q;
char s[];
void putup(int rt)
{
sum[rt] = sum[rt<<]+sum[rt<<|];
}
void putdown(int rt,int m)
{
if (add[rt])
{
add[rt<<] += add[rt];
add[rt<<|] += add[rt];
sum[rt<<] += (m-(m>>))*add[rt];
sum[rt<<|] += (m>>)*add[rt];
add[rt] = ;
}
}
void build(int l,int r,int rt)
{
add[rt] = ;
if (l==r)
{
scanf("%lld",&sum[rt]);
return ;
}
int m = (l+r)>>;
build(lson);
build(rson);
putup(rt);
}
void update(int l,int r,int rt,int L,int R,int c)
{
if (L<=l && r<=R)
{
add[rt] += c;
sum[rt] += (LL)c*(r-l+);
return ;
}
putdown(rt,r-l+);
int m = (l+r)>>;
if (L<=m) update(lson,L,R,c);
if (R>m) update(rson,L,R,c);
putup(rt);
}
LL query(int l,int r,int rt,int L,int R)
{
if (L<=l && r<=R)
{
return sum[rt];
}
putdown(rt,r-l+);
LL ret = ;
int m = (l+r)>>;
if (L<=m) ret += query(lson,L,R);
if (R>m) ret += query(rson,L,R);
return ret;
}
int main()
{
scanf("%d%d",&n,&q);
build(,n,);
while (q--)
{
int x,y,z;
scanf("%s",s);
if (s[]=='C')
{
scanf("%d%d%d",&x,&y,&z);
update(,n,,x,y,z);
}
else
{
scanf("%d%d",&x,&y);
printf("%lld\n",query(,n,,x,y));
}
}
return ;
}
最新文章
- es6中的promise对象
- NSString相关操作
- 5ucms后台调用标签
- 解决英文或数字在HTMl网页中不自动换行。
- 1.JS设计模式-this,call&;apply
- Mongodb数据库加密存储(python)
- ios开发理解nil,Nil, NULL
- 安装php-posix
- [转]Ubuntu alternate和desktop区别
- (转)《深入理解java虚拟机》学习笔记3——垃圾回收算法
- Qt 设置对话框背景(使用调色板,设置它的画刷,画刷可以是图片)
- Android核心基础
- linux下 文件IO 相关
- 【spring源码分析】IOC容器初始化(一)
- Centos 7部署docker
- vue组件,通过props父组件给子组件传值,WTF, 子组件报错undefined???
- Bresenham算法
- promise封装的ajax
- 一文看懂 Dubbo 的集成与使用
- Linux基础(六) Vim之vundle插件