poj 3468 A Simple Problem with Integers

A Simple Problem with Integers
Time Limit: 5000MS   Memory Limit: 131072K
Total Submissions: 110087   Accepted: 34277
Case Time Limit: 2000MS

Description

You have N integers, A1A2, ... , 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 A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+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.

Source

大意:给定序列
两种操作
区间求和与区间修改
#include<cstdio>

#define LL long long

const int N=100005;
char a[10];
LL p,q,d; 
LL sum[N*3],lazy[N*3];
LL read(){
    LL x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c<='9'&&c>='0'){x=x*10+c-'0';c=getchar();}return x*f;}
void update(int rt)
{
    sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}

void build(int l,int r,int rt)
{
    if(l==r){
        sum[rt]=read(); return ;
    }
    int mid=(l+r)>>1;
    build(l,mid,rt<<1);
    build(mid+1,r,rt<<1|1);
    update(rt);
}

void push_down(int rt,int len)
{
    
    lazy[rt<<1]+=lazy[rt];
    lazy[rt<<1|1]+=lazy[rt];
    sum[rt<<1]+=(len-(len>>1))*lazy[rt];
    sum[rt<<1|1]+=(len>>1)*lazy[rt];
    lazy[rt]=0;
}
void modify(int l,int r,int rt)
{
    if(p<=l&&q>=r)
    {
        lazy[rt]+=d;
        sum[rt]+=(LL)d*(r-l+1);
        return;
    }
    push_down(rt,r-l+1);
    int mid=(l+r)>>1;
    if(mid>=p) modify(l,mid,rt<<1);
    if(q>mid) modify(mid+1,r,rt<<1|1);
    update(rt);
}

LL query(int l,int r,int rt,int nowl,int nowr)
{
    if(nowl<=l&&nowr>=r)
    {
        return sum[rt];
    }
    if(lazy[rt])push_down(rt,r-l+1);
    int m=(r+l)>>1;
    LL ans=0;
    if(nowl<=m) ans+=query(l,m,rt<<1,nowl,nowr);
    if(nowr>m) ans+=query(m+1,r,rt<<1|1,nowl,nowr);
    return ans;
}
int n,m;
int main()
{
    n=read();m=read();
    build(1,n,1);
    while(m--)
    {
        scanf("%s",a);p=read(),q=read();
        if(a[0]=='Q')
        {
            printf("%lld\n",query(1,n,1,p,q));
        }
        if(a[0]=='C')
        {    d=read();
            modify(1,n,1);
        }
    }
    
    return 0;
}

 

posted @ 2017-06-21 17:21  zzzzx  阅读(127)  评论(0编辑  收藏  举报