您的位置:首页 > 其它

poj 3468 A Simple Problem with Integers(线段树-区间更新(基础))

2015-08-26 12:09 477 查看
A Simple Problem with Integers

Time Limit: 5000MSMemory Limit: 131072K
Total Submissions: 78715Accepted: 24261
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

Hint

The sums may exceed the range of 32-bit integers.

初学线段树

#include <iostream>

#include <stdio.h>

using namespace
std;

#define maxn 100010

struct Tree

{

int l;

int r;

long long sum;

long long add;

};

Tree tree[maxn<<2];

void PushUp(int root)

{

tree[root].sum=tree[root<<1].sum+tree[(root<<1)+1].sum;

}

void Build(int L,int R,int root)

{

tree[root].l=L;

tree[root].r=R;

tree[root].add=0;

if(L==R)

{

scanf("%lld",&tree[root].sum);

return;

}

int m=(R+L)>>1;

Build(L, m, root<<1);

Build(m+1, R, (root<<1)+1);

PushUp(root);

}

void PushDown(int root)

{

int l=root<<1;

int r=l+1;

tree[l].add+=tree[root].add;

tree[r].add+=tree[root].add;

tree[l].sum+=tree[root].add*(tree[l].r-tree[l].l+1);

tree[r].sum+=tree[root].add*(tree[r].r-tree[r].l+1);

tree[root].add=0;

}

void Update(int L,int R,int root,int value)

{

if(L<=tree[root].l &&
tree[root].r<=R)

{

tree[root].add+=value;

tree[root].sum+=value*(tree[root].r-tree[root].l+1);

return;

}

if(tree[root].add)

{

PushDown(root);

}

int m=(tree[root].l+tree[root].r)>>1;

if(L<=m)

Update(L, R, root<<1, value);

if(R>m)

Update(L, R, (root<<1)+1,value);

PushUp(root);

}

long long Query(int L,int R,int root)

{

if(L<=tree[root].l && R>=tree[root].r)

return tree[root].sum;

if(tree[root].add)

PushDown(root);

int m=(tree[root].l+tree[root].r)>>1;

long long ans=0;

if(L<=m)

ans+=Query(L, R, root<<1);

if(R>m)

ans+=Query(L, R, (root<<1)+1);

return ans;

}

int main()

{

int n,q,l,r,val;

char op;

scanf("%d",&n);

scanf("%d",&q);

Build(1, n,
1);

getchar();

for (int i=0; i<q; i++)

{

scanf("%c",&op);

if(op=='C')

{

scanf("%d%d%d",&l,&r,&val);

getchar();

Update(l, r,
1, val);

}

else

{

scanf("%d%d",&l,&r);

getchar();

printf("%lld\n",Query(l, r,
1));

}

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: