1019(树状数组的区间更新,区间求和)

Problem 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
<p>The first line contains two numbers <i>N</i> and <i>Q</i>. 1 ≤ <i>N</i>,<i>Q</i> ≤ 100000.<br>The second line contains <i>N</i> numbers, the initial values of <i>A</i><sub>1</sub>, <i>A</i><sub>2</sub>, ... , <i>A<sub>N</sub></i>. -1000000000 ≤ <i>A<sub>i</sub></i> ≤ 1000000000.<br>Each of the next <i>Q</i> lines represents an operation.<br>"C <i>a</i> <i>b</i> <i>c</i>" means adding <i>c</i> to each of <i>A<sub>a</sub></i>, <i>A<sub>a</sub></i><sub>+1</sub>, ... , <i>A<sub>b</sub></i>. -10000 ≤ <i>c</i> ≤ 10000.<br>"Q <i>a</i> <i>b</i>" means querying the sum of <i>A<sub>a</sub></i>, <i>A<sub>a</sub></i><sub>+1</sub>, ... , <i>A<sub>b</sub></i>.</p>

Output
<p>You need to answer all <i>Q</i> commands in order. One answer in a line.</p>

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 <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;


long long c[2][100001];
long long b[100002],sum1[100002];
long long lowbit(long long x)
{
    return x&(-x);
}

void add(long long x,long long v,int k)
{
    while(x<=100001)
    {
        c[k][x]+=v;
        x+=lowbit(x);
    }

}

long long sum(long long x,int k)
{
    long long sum=0;
    while(x>0)
    {
        sum+=c[k][x];
        x-=lowbit(x);
    }
    return sum;
}


int main()
{
    int n,m;
    scanf("%d%d",&n,&m);


    memset(c,0,sizeof(c));
    memset(sum1,0,sizeof(sum1));

    for(int i=1;i<=n;i++)
    {
        scanf("%I64d",&b[i]);
       sum1[i]=sum1[i-1]+b[i];


    }

   while(m--)
   {char q[2];
       scanf("%s",q);
       if(q[0]=='Q')
       {
           long long w1,w2;
           scanf("%I64d%I64d",&w1,&w2);
           long long sun=0;
           sun+=sum1[w2]-sum1[w1-1];
           sun+=(w2+1)*sum(w2,0)-sum(w2,1);
           sun-=w1*sum(w1-1,0)-sum(w1-1,1);
           printf("%I64d\n",sun);

       }
       else if(q[0]=='C')
       {
           long long e1,e2,e3;
            scanf("%I64d%I64d%I64d",&e1,&e2,&e3);
            add(e1,e3,0);
            add(e2+1,-e3,0);
            add(e1,e3*e1,1);
            add(e2+1,-e3*(e2+1),1);

       }




    }

    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值