A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K | |
---|---|---|
Total Submissions: 137519 | Accepted: 42602 | |
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
代码语言:javascript复制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
代码语言:javascript复制4
55
9
15
Hint
The sums may exceed the range of 32-bit integers.
题解:又是一道裸地线段树操作。区间查询和区间修改。注意long long。
代码语言:javascript复制#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
#include<map>
#include<cmath>
#include<string>
using namespace std;
typedef long long ll;
ll ans;
struct node
{
ll l, r, w;
ll f;
};
struct node tree[100000 * 4 1];
void BuildSegmentTree(int k, int l, int r)
{
tree[k].l = l;
tree[k].r = r;
if(l == r )
{
scanf("%lld", &tree[k].w);
return ;
}
int m = (tree[k].l tree[k].r) >> 1;
BuildSegmentTree(k << 1, l, m);
BuildSegmentTree(k << 1 | 1, m 1, r);
tree[k].w = tree[2 * k].w tree[2 * k 1].w;
}
void down(int k)
{
tree[k << 1].f = tree[k].f;
tree[k << 1 | 1].f = tree[k].f;
tree[k << 1]. w = tree[k].f * (tree[k * 2].r - tree[k * 2].l 1);
tree[k << 1 |1].w = tree[k].f * (tree[k << 1| 1].r - tree[k << 1| 1].l 1);
tree[k].f = 0;
}
void Lazysum(int k, int x, int y)
{
if(tree[k].l >= x && tree[k].r <= y)
{
ans = tree[k].w;
return ;
}
if(tree[k].f) down(k);
int m = (tree[k].l tree[k].r) / 2;
if(x <= m) Lazysum(k << 1, x, y);
if(y > m) Lazysum(k << 1 | 1, x, y);
}
void LazyAdd(int k, int x, int y, int z)
{
if(tree[k].l >= x && tree[k].r <= y)
{
tree[k].w = z * (tree[k].r - tree[k].l 1);
tree[k].f = z;
return ;
}
if(tree[k].f) down(k);
int m = (tree[k].l tree[k].r) / 2;
if(x <= m) LazyAdd(2 *k, x, y, z);
if(y > m) LazyAdd(2 * k 1, x, y, z);
tree[k].w = tree[k << 1].w tree[k << 1 |1].w;
}
char op;
int main()
{
int N, Q;
while(~scanf("%d %d",&N, &Q))
{
BuildSegmentTree(1,1,N);
while(Q--)
{
int x, y,z;
getchar();
scanf("%c %d %d", &op, &x, &y);
if(op == 'Q')
{
ans = 0;
Lazysum(1,x,y);
printf("%lldn",ans);
}
else if(op == 'C')
{
scanf("%d", &z);
LazyAdd(1,x,y,z);
}
}
}
return 0;
}