poj 3468:A Simple Problem with Integers

A Simple Problem with Integers

TimeLimit: 5 sec

Description

You have N integers, A1, A2, ... , AN.You need to deal with two kinds of operations. One type of operation is to addsome given number to each number in a given interval. The other is to ask forthe sum of numbers in a given interval.

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

Attention:
Case Time Limit: 2000MS
 

TheInput

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" meansadding c to each of Aa, Aa+1, ... , Ab. -10000≤ c ≤ 10000. "Q a b" means querying the sum of Aa, Aa+1,... , Ab.
 

TheOutput

You need to answer all Q commands in order. One answer in aline.
 

SampleInput

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


 

SampleOutput

4

55

9

15


 


 

 

 

 

#include<iostream>

#include<cstdio>

using namespace std;

typedef long longintt;

struct node

{

    int l,r;

    intt sum,inc;

};

#define L(x)(x<<1)

#define R(x)((x<<1)+1)

#define M(x,y)((x+y)>>1)

const int N=1000005;

node tree[2*N];

int num[N];

void build(int t,intl,int r)

{

    tree[t].l=l;

    tree[t].r=r;

    tree[t].inc=0;

    if(l==r){tree[t].sum=num[l];return;}

    int mid=M(l,r);

    build(L(t),l,mid);

    build(R(t),mid+1,r);

    tree[t].sum=tree[L(t)].sum+tree[R(t)].sum;

}

intt query(int t,intl,int r)

{

    intt sum=0;

    if(tree[t].l>=l &&tree[t].r<=r)

    {

        sum+=(r-l+1)*tree[t].inc+tree[t].sum;

        return sum;

    }

    if(tree[t].inc)

    {

        tree[L(t)].inc+=tree[t].inc;

        tree[R(t)].inc+=tree[t].inc;

       tree[t].sum+=(tree[t].r-tree[t].l+1)*tree[t].inc;

        tree[t].inc=0;

    }

    int mid=M(tree[t].l,tree[t].r);

    if(r<=mid)sum+=query(L(t),l,r);

    else if(l>mid)sum+=query(R(t),l,r);

    else

    {

        sum+=query(L(t),l,mid);

        sum+=query(R(t),mid+1,r);

    }

    return sum;

}

void updata(int t,intl, int r,intt inc)

{

    if(tree[t].l>=l &&tree[t].r<=r){tree[t].inc+=inc;return;}

    else

    {

        tree[t].sum+=(r-l+1)*inc;

    }

    int mid=M(tree[t].l,tree[t].r);

    if(r<=mid)updata(L(t),l,r,inc);

    else if(l>mid)updata(R(t),l,r,inc);

    else {updata(L(t),l,mid,inc);  updata(R(t),mid+1,r,inc);}

}

int main()

{

    int i,n,q,a,b;

    intt inc;

    char cmd[10];

    scanf("%d%d",&n,&q);

   for(i=1;i<=n;i++)scanf("%d",num+i);

    build(1,1,n);

    while(q--)

    {

        getchar();

       scanf("%s%d%d",cmd,&a,&b);

      if(cmd[0]=='Q')printf("%I64d\n",query(1,a,b));

        else

        {

            scanf("%I64d",&inc);

            updata(1,a,b,inc);

        }

    }

    return 0;

}

 

你可能感兴趣的:(poj 3468:A Simple Problem with Integers)