POJ3648 A Simple Problem with Integers(树状数组实现)
来源:互联网 发布:mx anywhere2 软件 编辑:程序博客网 时间:2024/06/07 02:03
题目描述:
题目链接: poj3648 http://poj.org/problem?id=3468
题目大意: 对于一个序列,进行区间修改,区间询问。读入数据在int范围内,但是计算的和等会超int,要用 long long。
题目分析:
如果用线段树做就是模板题,打标记+标记下传(标记永久化)。但是利用树状数组就不同了,因为普通的树状数组只支持单点修改。对于区间修改,我们假设序列为a[i],一个数组b[i]=a[i]-a[i-1],那么就有a[i]=b[1]+b[2]+······+b[i]。考虑一段区间和:
=
于是考虑维护一个数组
注:虽然树状数组与线段树的时间复杂度都为log(n),但是树状数组的常数小于线段树,所以跑起来更快。并且代码量也小一些。当然树状数组的局限性大于线段树。下附我的代码在POJ上的测试结果,时间上只有其他人的二分之一到三分之一,所用空间也只有别人的二分之一。
附代码:
#include<iostream>#include<cstring>#include<string>#include<cstdlib>#include<cstdio>#include<ctime>#include<queue>#include<iomanip>#include<cmath>#include<map>#include<set>#include<cctype>#include<algorithm>using namespace std;const int maxn=1e5+10;int n,q,x,y,z,a[maxn];char s;struct node{ long long a;//对应分析中的b数组 long long b;//对应分析中的c数组}tree[maxn]; int readint(){ char ch;int i=0,f=1; for(ch=getchar();(ch<'0'||ch>'9')&&ch!='-';ch=getchar()); if(ch=='-') { ch=getchar(); f=-1; } for(;ch>='0'&&ch<='9';ch=getchar()) i=(i<<3)+(i<<1)+ch-'0'; return i*f;}int lowbit(int x){ return x&(-x);}void update(int x,int y){ long long z=(long long)y*(x-1);//很据分析中的定义维护 for(int i=x;i<=n;i+=lowbit(i)) { tree[i].a+=y; tree[i].b+=z; } }long long query(int x){ long long sum1=0,sum2=0; for(int i=x;i>0;i-=lowbit(i)) { sum1+=tree[i].a; sum2+=tree[i].b; } return x*sum1-sum2;//根据分析中的结果计算答案}int main(){ //freopen("lx.in","r",stdin); n=readint();q=readint(); for(int i=1;i<=n;i++) { a[i]=readint(); update(i,a[i]-a[i-1]); } while(q--) { scanf("%c",&s); if(s=='Q') { x=readint();y=readint(); long long ans=query(y)-query(x-1); printf("%lld\n",ans); } else { x=readint();y=readint();z=readint(); update(x,z); update(y+1,-z); } } return 0;}
- POJ3648 A Simple Problem with Integers(树状数组实现)
- HDU 4267 A Simple Problem with Integers 树状数组
- POJ 3468 A Simple Problem with Integers (树状数组写法)
- hdu(4267)A Simple Problem with Integers(三维树状数组)
- HDU4267 A Simple Problem with Integers(树状数组)
- POJ 3468 A Simple Problem with Integers 【树状数组】
- [POJ 3468] A Simple Problem with Integers [树状数组]
- poj3468--A Simple Problem with Integers(树状数组解法)
- 【树状数组】 HDOJ 4276 A Simple Problem with Integers
- HDU 4267 A Simple Problem with Integers --树状数组
- A Simple Problem with Integers+hdu+树状数组
- HDU 4267 A Simple Problem with Integers(树状数组)
- [树状数组] poj3468 A Simple Problem with Integers
- hdu4267--A Simple Problem with Integers(树状数组)
- HDU 4267 A Simple Problem with Integers(树状数组)
- A Simple Problem with Integers(树状数组HDU4267)
- HDOJ 4267 A Simple Problem with Integers 树状数组
- HDU - 4267 A Simple Problem with Integers(树状数组)
- Android打印工具类
- EventBus详解---参考官网
- input 上传图片显示预览、调用摄像头,ios和Android的兼容性解决
- 时域、频域、空间域
- cf 832D Misha, Grisha and Underground 【lca+倍增】
- POJ3648 A Simple Problem with Integers(树状数组实现)
- Android 系统发送“系统当前时间”的广播
- Selenium Grid 的使用
- 小白笔记-----------------------Metasploit (from tools)整理
- 【bzoj3522】 [Poi2014]Hotel
- Netty echo server 简例
- 奇偶位交换
- Mr.Smile填坑记——debug、release包MD5签名的获取方式
- redis写入文件