树状数组(binary indexed tree),是一种设计新颖的数组结构,它能够高效地获取数组中连续n个数的和。概括说,树状数组通常用于解决以下问题:数组{a}中的元素可能不断地被修改,怎样才能快速地获取连续几个数的和?
2、树状数组基本操作
传统数组(共n个元素)的元素修改和连续元素求和的复杂度分别为O(1)和O(n)。树状数组通过将线性结构转换成伪树状结构(线性结构只能逐个扫描元素,而树状结构可以实现跳跃式扫描),使得修改和求和复杂度均为O(lgn),大大提高了整体效率。
给定序列(数列)A,我们设一个数组C满足
C[i] = A[i–2^k+ 1] + … + A[i]
其中,k为i在二进制下末尾0的个数,i从1开始算!
则我们称C为树状数组。
下面的问题是,给定i,如何求2^k?
答案很简单:2^k=i&(i^(i-1)) ,也就是i&(-i)
下面进行解释:
以i=6为例(注意:a_x表示数字a是x进制表示形式):
(i)_10 = (0110)_2
(i-1)_10=(0101)_2
i xor (i-1) =(0011)_2
i and (i xor (i-1)) =(0010)_2
2^k = 2
C[6] = C[6-2+1]+…+A[6]=A[5]+A[6]
数组C的具体含义如下图所示:
当我们修改A[i]的值时,可以从C[i]往根节点一路上溯,调整这条路上的所有C[]即可,这个操作的复杂度在最坏情况下就是树的高度即O(logn)。另外,对于求数列的前n项和,只需找到n以前的所有最大子树,把其根节点的C加起来即可。不难发现,这些子树的数目是n在二进制时1的个数,或者说是把n展开成2的幂方和时的项数,因此,求和操作的复杂度也是O(logn)。
树状数组能快速求任意区间的和:A[i] + A[i+1] + … + A[j],设sum(k) = A[1]+A[2]+…+A[k],则A[i] + A[i+1] + … + A[j] = sum(j)-sum(i-1)。
已知一个数列,你需要进行下面两种操作:
1.将某一个数加上x
2.求出某区间每一个数的和
/*************************************************************************
> Author: wzw-cnyali
> Created Time: 2017/6/13 10:33:11
************************************************************************/
#prag\
ma GCC optimize("O3")
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
#define REP(i, a, b) for(register int i = (a), i##_end_ = (b); i <= i##_end_; ++ i)
#define DREP(i, a, b) for(register int i = (a), i##_end_ = (b); i >= i##_end_; -- i)
#define EREP(i, a) for(register int i = (be[a]); i != -1; i = nxt[i])
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define mem(a, b) memset((a), b, sizeof(a))
template inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; }
template inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; }
char buff[1 << 25], *buf = buff;
template
T read(T sum = 0, T fg = 0)
{
while(*buf < '0' || *buf > '9') { fg |= *buf == '-'; buf++; }
while(*buf >= '0' && *buf <= '9') { sum = sum * 10 + *buf - '0'; buf++; }
return fg ? -sum : sum;
}
const int inf = 1e9;
const LL INF = 1e17;
const int Size = 500010;
const int maxn = 100000;
const int maxm = 100000;
int n, m;
int a[Size];
struct index_tree
{
#define lowbit(x) ((x) & (-x))
void add(int x, int val)
{
for(; x <= n; x += lowbit(x)) a[x] += val;
}
int query(int x)
{
int ans = 0;
for(; x; x -= lowbit(x)) ans += a[x];
return ans;
}
}tree;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
freopen("output.out", "w", stdout);
#endif
fread(buff, 1, 1 << 25, stdin);
n = read(), m = read();
REP(i, 1, n) tree.add(i, read());
while(m--)
{
int tp = read();
if(tp == 1)
{
int x = read(), val = read();
tree.add(x, val);
}
else
{
int x = read(), y = read();
printf("%d\n", tree.query(y) - tree.query(x - 1));
}
}
return 0;
}
题目链接: https://www.luogu.org/problem/show?pid=3374
已知一个数列,你需要进行下面两种操作:
1.将某区间每一个数数加上x
2.求出某一个数的值
思路:
这里要引入差分数组这种东西,我们记d[i] = a[i] - a[i-1](a为原数组),这样我们记sigma(d[i]) = a[i] ,为什么呢,观察式子sigma(d[i]) = a[1] + a[2] - a[1] +a[3]...这样一直下去就得到了我们的原数组。
有什么用呢?如果我们往一段区间上加k,在差分数组上如何体现呢?我们举个例子:
a:1,2,3,4,5
d:1,1,1,1,1
2~4加1
如果我们盲目的在2到4上加1,就会发现会影响后面的数(因为是前缀和),所以我们在2这个位置加一,用树状数组更新,在5的位置减一用树状数组更新就ok了
a:1,3,4,5,5
d:1,2,1,1,0
/*************************************************************************
> Author: wzw-cnyali
> Created Time: 2017/6/13 11:11:16
************************************************************************/
#include
#include
#include
#include
#include
#include
#prag\
ma GCC optimize("O3")
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
#define REP(i, a, b) for(register int i = (a), i##_end_ = (b); i <= i##_end_; ++ i)
#define DREP(i, a, b) for(register int i = (a), i##_end_ = (b); i >= i##_end_; -- i)
#define EREP(i, a) for(register int i = (be[a]); i != -1; i = nxt[i])
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define mem(a, b) memset((a), b, sizeof(a))
template inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; }
template inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; }
char buff[1 << 25], *buf = buff;
template
T Fread(T sum = 0, T fg = 0)
{
while(*buf < '0' || *buf > '9') { fg |= *buf == '-'; buf++; }
while(*buf >= '0' && *buf <= '9') { sum = sum * 10 + *buf - '0'; buf++; }
return fg ? -sum : sum;
}
template
T read(T sum = 0, T fg = 0)
{
char c = getchar();
while(c < '0' || c > '9') { fg |= c == '-'; c = getchar(); }
while(c >= '0' && c <= '9') { sum = sum * 10 + c - '0'; c = getchar(); }
return fg ? -sum : sum;
}
const int inf = 1e9;
const LL INF = 1e17;
const int Size = 500010;
const int maxn = 100000;
const int maxm = 100000;
int n, m;
int a[Size];
struct index_tree
{
#define lowbit(x) ((x) & (-x))
int tree[Size];
void add(int x, int val)
{
for(; x <= n; x += lowbit(x)) tree[x] += val;
}
int query(int x)
{
int ans = 0;
for(; x; x -= lowbit(x)) ans += tree[x];
return ans;
}
}tree;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
freopen("output.out", "w", stdout);
#endif
fread(buff, 1, 1 << 25, stdin);
n = Fread(), m = Fread();
REP(i, 1, n)
{
a[i] = Fread();
tree.add(i, a[i] - a[i - 1]);
}
while(m--)
{
if(Fread() == 1)
{
int x = Fread(), y = Fread(), val = Fread();
tree.add(x, val);
tree.add(y + 1, -val);
}
else printf("%d\n", tree.query(Fread()));
}
return 0;
}
已知一个数列,你需要进行下面两种操作:
1.将某区间每一个数加上x
2.求出某区间每一个数的和
首先观察式子:
a[1]+a[2]+...+a[n]
= (c[1]) + (c[1]+c[2]) + ... + (c[1]+c[2]+...+c[n])
= n*c[1] + (n-1)*c[2] +... +c[n]
= n * (c[1]+c[2]+...+c[n]) - (0*c[1]+1*c[2]+...+(n-1)*c[n]) (式子①)
那么我们就维护一个数组c2[n],其中c2[i] = (i-1)*c[i]
每当修改c的时候,就同步修改一下c2,这样复杂度就不会改变
那么式子①=n*sigma(c,n) - sigma(c2,n)
于是我们做到了在O(logN)的时间内完成一次区间和查询
一件很好的事情就是树状数组的常数比其他NlogN的数据结构小得多,实际上它的计算次数比NlogN要小很多,再加上它代码短,是OI中的利器
/*************************************************************************
> Author: wzw-cnyali
> Created Time: 2017/6/13 15:18:18
************************************************************************/
#include
#include
#include
#include
#include
#include
#prag\
ma GCC optimize("O3")
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
#define REP(i, a, b) for(register int i = (a), i##_end_ = (b); i <= i##_end_; ++ i)
#define DREP(i, a, b) for(register int i = (a), i##_end_ = (b); i >= i##_end_; -- i)
#define EREP(i, a) for(register int i = (be[a]); i != -1; i = nxt[i])
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define mem(a, b) memset((a), b, sizeof(a))
template inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; }
template inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; }
char buff[1 << 21], *buf = buff;
template
T Fread(T sum = 0, T fg = 0)
{
while(*buf < '0' || *buf > '9') { fg |= *buf == '-'; buf++; }
while(*buf >= '0' && *buf <= '9') { sum = sum * 10 + *buf - '0'; buf++; }
return fg ? -sum : sum;
}
template
T read(T sum = 0, T fg = 0)
{
char c = getchar();
while(c < '0' || c > '9') { fg |= c == '-'; c = getchar(); }
while(c >= '0' && c <= '9') { sum = sum * 10 + c - '0'; c = getchar(); }
return fg ? -sum : sum;
}
const int inf = 1e9;
const LL INF = 1e17;
const int Size = 100010;
const int maxn = 100000;
const int maxm = 100000;
int n, m;
struct index_tree
{
#define lowbit(x) ((x) & (-x))
void add(LL *array, int x, LL val)
{
for(; x <= n; x += lowbit(x)) array[x] += val;
}
LL query(LL *array, int x)
{
LL ans = 0;
for(; x; x -= lowbit(x)) ans += array[x];
return ans;
}
}tree;
LL c1[Size], c2[Size];
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
freopen("output.out", "w", stdout);
#endif
fread(buff, 1, 1 << 21, stdin);
n = Fread(), m = Fread();
LL last_x = 0;
REP(i, 1, n)
{
LL x = Fread();
tree.add(c1, i, x - last_x);
tree.add(c2, i, (x - last_x) * (i - 1));
last_x = x;
}
while(m--)
{
if(Fread() == 1)
{
int x = Fread(), y = Fread();
LL val = Fread();
tree.add(c1, x, val); tree.add(c1, y + 1, -val);
tree.add(c2, x, val * (x - 1)); tree.add(c2, y + 1, -val * y);
}
else
{
int x = Fread(), y = Fread();
LL sum1 = (x - 1) * tree.query(c1, x - 1) - tree.query(c2, x - 1);
LL sum2 = y * tree.query(c1, y) - tree.query(c2, y);
printf("%lld\n", sum2 - sum1);
}
}
return 0;
}
对于一个包含n个非负整数的数组a,如果有i
即逆序数就是前面比后面大的一对数。
/*************************************************************************
> Author: wzw-cnyali
> Created Time: 2017/6/13 16:59:03
************************************************************************/
#include
#include
#include
#include
#include
#include
#prag\
ma GCC optimize("O3")
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
#define REP(i, a, b) for(register int i = (a), i##_end_ = (b); i <= i##_end_; ++ i)
#define DREP(i, a, b) for(register int i = (a), i##_end_ = (b); i >= i##_end_; -- i)
#define EREP(i, a) for(register int i = (be[a]); i != -1; i = nxt[i])
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define mem(a, b) memset((a), b, sizeof(a))
template inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; }
template inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; }
char buff[1 << 25], *buf = buff;
template
T Fread(T sum = 0, T fg = 0)
{
while(*buf < '0' || *buf > '9') { fg |= *buf == '-'; buf++; }
while(*buf >= '0' && *buf <= '9') { sum = sum * 10 + *buf - '0'; buf++; }
return fg ? -sum : sum;
}
template
T read(T sum = 0, T fg = 0)
{
char c = getchar();
while(c < '0' || c > '9') { fg |= c == '-'; c = getchar(); }
while(c >= '0' && c <= '9') { sum = sum * 10 + c - '0'; c = getchar(); }
return fg ? -sum : sum;
}
const int inf = 1e9;
const LL INF = 1e17;
const int Size = 100000;
const int maxn = 100000;
const int maxm = 100000;
int n;
struct node
{
int val, id;
}a[Size];
bool cmp(node a, node b)
{
return a.val < b.val;
}
struct index_tree
{
#define lowbit(x) ((x) & (-x))
int tree[Size];
void add(int x)
{
for(; x <= n; x += lowbit(x)) tree[x]++;
}
int query(int x)
{
int ans = 0;
for(; x; x -= lowbit(x)) ans += tree[x];
return ans;
}
}tree;
int c[Size];
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
freopen("output.out", "w", stdout);
#endif
fread(buff, 1, 1 << 25, stdin);
n = Fread();
REP(i, 1, n) a[i] = (node){Fread(), i};
sort(a + 1, a + n + 1, cmp);
REP(i, 1, n) c[a[i].id] = i;
int ans = 0;
DREP(i, n, 1)
{
ans += tree.query(c[i]);
tree.add(c[i]);
}
printf("%d\n", ans);
return 0;
}
参考文章:http://dongxicheng.org/structure/binary_indexed_tree/
http://blog.csdn.net/BroDrinkWater/article/details/73188005