POJ - 3468——A Simple Problem with Integers (线段树区间查询/修改)

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


线段树模板题:

#include<algorithm>
#include<string.h>
#include<stdio.h>
#define LL long long
#define M 100010
using namespace std;
struct node
{
    int l,r;
    LL n,f;
}a[4*M];
LL ans;
void down(int k)//懒标记
{
    a[2*k].n+=a[k].f*(a[2*k].r-a[2*k].l+1);
    a[2*k+1].n+=a[k].f*(a[2*k+1].r-a[2*k+1].l+1);
    a[2*k].f+=a[k].f;
    a[2*k+1].f+=a[k].f;
    a[k].f=0;
}
void init(int l,int r,int k)//建树
{
    a[k].r=r;
    a[k].l=l;
    if(l==r)
    {
        a[k].n=0;
        a[k].f=0;
        return ;
    }
    int mid=(l+r)>>1;
    init(l,mid,2*k);
    init(mid+1,r,2*k+1);
}
void insert_trie(int l,int r,int k,int x)//区间修改
{
    int mid;
    if(a[k].r<=r&&a[k].l>=l)
    {
        a[k].n+=x*(a[k].r-a[k].l+1);
        a[k].f+=x;
        return ;
    }
    mid=(a[k].l+a[k].r)>>1;
    if(a[k].f)down(k);
    if(mid>=r)insert_trie(l,r,2*k,x);
    else if(mid<l)insert_trie(l,r,2*k+1,x);
    else
    {
        insert_trie(l,mid,2*k,x);
        insert_trie(mid+1,r,2*k+1,x);
    }
    a[k].n=a[2*k].n+a[2*k+1].n;
}
void search_trie(int l,int r,int k)//区间查询
{
    int mid;
    if(a[k].r<=r&&a[k].l>=l)
    {
        ans+=a[k].n;
        return ;
    }
    mid=(a[k].l+a[k].r)>>1;
    if(a[k].f)down(k);
    if(mid>=r)search_trie(l,r,2*k);
    else if(mid<l)search_trie(l,r,2*k+1);
    else
    {
        search_trie(l,mid,2*k);
        search_trie(mid+1,r,2*k+1);
    }
}
int main()
{
    char s[10];
    int n,m,x,y,z;
    while(~scanf("%d%d",&n,&m))
    {
        init(1,n,1);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&x);
            insert_trie(i,i,1,x);
        }
        while(m--)
        {
            scanf("%s",s);
            if(!strcmp(s,"Q"))
            {
                ans=0;
                scanf("%d%d",&x,&y);
                search_trie(x,y,1);
                printf("%I64d\n",ans);
            }
            else
            {
                scanf("%d%d%d",&x,&y,&z);
                insert_trie(x,y,1,z);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41380961/article/details/80464286