树状数组
2012-11-21 21:39
120 查看
树状数组主要理解三个函数Lowbit(),pluse(),sum();lowbit()是他们三个当中最难理解的,一切都靠网络,呵呵,另外有意外收获了输入开挂
先说下Lowbit()人如其名,指的就是,这个数用二进制表示,最后一个1所代表的数
Pluse()也就是从底向上跟新了,他与他的父亲节点下表差为Lowbit();
sum()也就是求和,很easy,sum(pos)=C[Lowbit(pos)]+sum(pos-Lowbit(pos));
表示的是从1到pos数组C的和
这是南阳理工的士兵杀敌二
先说下Lowbit()人如其名,指的就是,这个数用二进制表示,最后一个1所代表的数
Pluse()也就是从底向上跟新了,他与他的父亲节点下表差为Lowbit();
sum()也就是求和,很easy,sum(pos)=C[Lowbit(pos)]+sum(pos-Lowbit(pos));
表示的是从1到pos数组C的和
这是南阳理工的士兵杀敌二
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define K 1000050 long long c[K]; long long Lowbit(long long t) { return t&(t^(t-1)); } long long Sum(long long end) { long long sum=0; while(end>0) { sum+=c[end]; end-=Lowbit(end); } return sum; } void Plus(long long pos,long long num,long long n) { while(pos<=n) { c[pos]+=num; pos+=Lowbit(pos); } } /* 输入外挂 使用方法: int a; a = Scan(); */ int Scan() { long long res = 0 , ch ; while( !( ( ch = getchar() ) >= '0' && ch <= '9' ) ) { if( ch == EOF ) return 1 << 30 ; } res = ch - '0' ; while( ( ch = getchar() ) >= '0' && ch <= '9' ) res = res * 10 + ( ch - '0' ) ; return res ; } int main() { long long N,M,i,tem,s,t; char str1[]="QUERY",str2[]="ADD",str[20]; scanf("%lld%lld",&N,&M); for(i=1;i<=N;i++) { tem = Scan(); Plus(i,tem,N); } /*for(i=1;i<=N;i++) cout<<"c["<<i<<"]="<<c[i]<<endl;*/ for(i=0;i<M;i++) { scanf("%s%lld%lld",str,&s,&t); //cout<<"str[]="<<str<<endl; int ma; ma=strlen(str); if(ma==5) cout<<Sum(t)-Sum(s-1)<<endl; if(ma==3) Plus(s,t,N); } }
相关文章推荐
- Matrix 二维树状数组 区间修改+单点查询
- 树状数组应用
- ZOJ 2112 Dynamic Rankings (动态第 K 大)(树状数组套主席树)
- 树状数组(转载)
- 树状数组求解逆序数(SOJ2309)
- POJ1195 Mobile phones 【二维树状数组】
- poj-3321-Apple Tree(树状数组)
- [BZOJ4888][洛谷3760]异或和 树状数组
- 树状数组求序列的区间和
- 树状数组求逆序对
- 树状数组
- 【NOIP模拟赛】飞(fly) 数论+树状数组
- 暑假-树状数组-E - Stars
- hdu 1556 树状数组
- 树状数组模板程序
- LightOJ 1085 All Possible Increasing Subsequences (DP&离散化&树状数组)
- POJ 3110 Jenny's First Exam (二分 + 树状数组 + 贪心 + 预处理年份)
- poj2155 Matrix 【二维树状数组】
- 树状数组 BIT
- 浅谈树状数组求逆序对