算法-ACM POJ

发布于 2017-01-08 02:26:40 字数 3764 浏览 1171 评论 1

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 abc" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q ab" 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

#include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;

const int MAX = 100000;
int num[MAX];

struct Node
{
int l, r;
long long sum;
long long inc;
}sTree[MAX*3];

void Build(int i, int l, int r)
{
sTree[i].l = l;
sTree[i].r = r;
sTree[i].inc = 0;
if( l == r )
{
sTree[i].sum = num[l];
return;
}
int mid = (l+r)/2;
Build(i<<1, l, mid);
Build(i<<1|1, mid+1, r );
sTree[i].sum = sTree[i<<1].sum+sTree[i<<1|1].sum;
}

void Add(int i, int a, int b, long long c);
long long Query(int i, int a, int b);

int main()
{
int n, q;
char op;
int a,b,c;
while(scanf("%d%d", &n, &q) != EOF)
{
for( int i = 1; i <= n; ++i )
scanf("%d", &num[i]);
Build(1,1,n);

while(q--)
{
cin>>op;
if( op == 'C' )
{
scanf("%d%d%d",&a,&b,&c);
Add(1,a,b,c);
}
else
{
scanf("%d%d",&a,&b);
long long temp = Query(1,a,b);
printf("%I64dn", temp );
}
}
}
return 0;
}

void Add(int i, int a, int b, long long c)
{
if( a <= sTree[i].l && b >= sTree[i].r )
{
sTree[i].inc += c;
sTree[i].sum += (sTree[i].r - sTree[i].l + 1)*c;
return;
}
if( sTree[i].inc > 0 )
{
Add(i<<1, sTree[i<<1].l, sTree[i<<1].r, sTree[i].inc );
Add(i<<1|1, sTree[i<<1|1].l, sTree[i<<1|1].r, sTree[i].inc);
sTree[i].inc = 0;
}
if( a <= sTree[i<<1].r )
Add(i<<1, a, b, c);
if( b >= sTree[i<<1|1].l )
Add(i<<1|1, a, b, c);
sTree[i].sum = sTree[i<<1].sum + sTree[i<<1|1].sum;
}

long long Query(int i, int a, int b)
{
if( sTree[i].l == a && sTree[i].r == b )
return sTree[i].sum;

int mid = (sTree[i].l+sTree[i].r)/2;
if( sTree[i].inc > 0 )
{
Add(i<<1, sTree[i<<1].l, sTree[i<<1].r, sTree[i].inc );
Add(i<<1|1, sTree[i<<1|1].l, sTree[i<<1|1].r, sTree[i].inc);
sTree[i].inc = 0;
}
if ( b <= mid )
return Query( i<<1, a, b);
else if( a > mid )
return Query( i<<1|1, a, b);
else
return Query( i<<1, a, mid)+Query(i<<1|1, mid+1, b);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

归属感 2017-05-20 07:33:27

同学, if( sTree[i].inc > 0 )这个地方有问题,应该是 sTree[i].inc!=0,思想(线段树+lazy更新)都是正确

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文