A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 107094 | Accepted: 33429 | |
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
线段树模板题(虽然我还是不会写
首先数据量比较大 要用LL
直接套模板 修改单个点会T不动脑子
看了看dalao的博客 改了改代码
解析在代码内2333
#include <cstdio>
#include <algorithm>
using namespace std;
#define LL long long
const int N = 1000000*4+10;
int arr[N];
struct node {
int left, right;
LL sum, num;
}tree[N];
void build(int l,int r,int step)
{
tree[step].left = l;
tree[step].right = r;
tree[step].num = 0;
if(l == r) {
tree[step].sum = arr[l];
return ;
}
int mid = (l+r) >> 1;
build(l,mid,step<<1);
build(mid+1,r,step<<1|1);
tree[step].sum = tree[step<<1].sum + tree[step<<1|1].sum;
}
void update(int l,int r,LL value,int step)
{
if(tree[step].left==l&&r==tree[step].right) {
tree[step].num += value;
return;
}
tree[step].sum += value*(r-l+1);
int mid = (tree[step].left+tree[step].right) >> 1;
if(r <= mid) update(l,r,value,step<<1);
else if(l > mid) update(l,r,value,step<<1|1);
else {
update(l,mid,value,step<<1);
update(mid+1,r,value,step<<1|1);
}
}
LL query(int l,int r,int step)
{
if(l==tree[step].left && r==tree[step].right) {
return tree[step].sum+(r-l+1)*tree[step].num;
}
int mid = (tree[step].left+tree[step].right) >> 1;
tree[step].sum += (tree[step].right-tree[step].left+1)*tree[step].num;
update(tree[step].left,mid,tree[step].num,step<<1);
update(mid+1,tree[step].right,tree[step].num,step<<1|1);
tree[step].num = 0;
if(r <= mid) return query(l,r,step<<1);
else if(l > mid) return query(l,r,step<<1|1);
else return query(l,mid,step<<1)+query(mid+1,r,step<<1|1);
}
int main()
{
int n, q, x;
scanf("%d%d",&n,&q);
for(int i = 1;i <= n; i++) {
scanf("%d",&arr[i]);
}
build(1,n,1);
while(q--) {
getchar();
char ch;
int u, v, z;
scanf("%c",&ch);
if(ch == 'C') {
scanf("%d%d%d",&u,&v,&z);
update(u,v,z,1);
}
if(ch == 'Q') {
scanf("%d%d",&u,&v);
printf("%lld\n",query(u,v,1));
}
}
return 0;
}