poj3468(树状数组)

博客介绍了一道关于区间更新和查询的经典题目,并提到原先使用线段树解决,但后来学习了树状数组的方法,认为其非常巧妙。提供了一个解法链接以供参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:一道经典题,区间更新,区间查询。

解法:原来用的是线段树。后来学了树状数组的做法,感觉很神奇,贴上解法网址:http://www.docin.com/p-97026988.html?qq-pf-to=pcqq.c2c

代码:

/****************************************************
* author:xiefubao
*******************************************************/
#pragma comment(linker, "/STACK:102400000,102400000")
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <string.h>

using namespace std;
typedef long long LL;
LL C[100100];
LL B[100100];
LL tool=0;
int lowbit(int x){return x&(-x);}
int N,Q;
void updateC(int x,LL t)
{
    tool+=t;
    while(x<=N){
        C[x]+=t;
        x+=lowbit(x);
    }
}
void updateB(int x,LL t)
{
    while(x<=N){
        B[x]+=t;
        x+=lowbit(x);
    }
}
LL queryC(int x)
{
    LL ans=0;
    while(x){
        ans+=C[x];x-=lowbit(x);
    }
    return ans;
}
LL queryB(int x)
{
    LL ans=0;
    while(x){
        ans+=B[x];x-=lowbit(x);
    }
    return ans;
}
void make(int a,int b,LL c)
{
    if(a>1)updateC(a-1,-c),updateB(a-1,-c*(a-1));
    updateC(b,c);
    updateB(b,c*b);
}
LL query(int x)
{
  LL ans=(tool-queryC(x))*x+queryB(x);
  return ans;
}
int main()
{
 cin>>N>>Q;
 for(int i=1;i<=N;i++)
 {
     int a;scanf("%d",&a);make(i,i,a);
 }
 for(int i=0;i<Q;i++)
 {
     char c;getchar();scanf("%c",&c);
     if(c=='Q')
     {
         int a,b;scanf("%d%d",&a,&b);//cout<<a<<" "<<b<<endl;
         printf("%I64d\n",query(b)-query(a-1));
     }
     else
     {
         int a,b,c;scanf("%d%d%d",&a,&b,&c);
         make(a,b,c);
     }
 }
   return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值