文章来自 : http://blog.csdn.net/x314542916/article/details/7837276
学习算法,自己收藏着。
线段树的入门级 总结
线段树是一种二叉搜索树,与区间树相似,它将一个区间划分成一些单元区间,每个单元区间对应线段树中的一个叶结点。
对于线段树中的每一个非叶子节点[a,b],它的左儿子表示的区间为[a,(a+b)/2],右儿子表示的区间为[(a+b)/2+1,b]。因此线段树是平衡二叉树,最后的子节点数目为N,即整个线段区间的长度。
使用线段树可以快速的查找某一个节点在若干条线段中出现的次数,时间复杂度为O(logN)。而未优化的空间复杂度为2N,因此有时需要离散化让空间压缩。
----来自百度百科
【以下以 求区间最大值为例】
先看声明:
- #include <stdio.h>
- #include <math.h>
- const int MAXNODE = 2097152;
- const int MAX = 1000003;
- struct NODE{
- int value;
- int left,right;
- }node[MAXNODE];
- int father[MAX];

【创建线段树(初始化)】:
由于线段树是用二叉树结构储存的,而且是近乎完全二叉树的,所以在这里我使用了数组来代替链表上图中区间上面的红色数字表示了结构体数组中对应的下标。
在完全二叉树中假如一个结点的序号(数组下标)为 I ,那么 (二叉树基本关系)
I 的父亲为 I/2,
I 的另一个兄弟为 I/2*2 或 I/2*2+1
I 的两个孩子为 I*2 (左) I*2+1(右)
有了这样的关系之后,我们便能很方便的写出创建线段树的代码了。
- void BuildTree(int i,int left,int right){
- node[i].left = left;
- node[i].right = right;
- node[i].value = 0;
- if (left == right){
- father[left] = i;
- return;
- }
-
-
- BuildTree(i<<1, left, (int)floor( (right+left) / 2.0));
-
- BuildTree((i<<1) + 1, (int)floor( (right+left) / 2.0) + 1, right);
- }
【单点更新线段树】:
由于我事先用 father[ ] 数组保存过 每单个结点 对应的下标了,因此我只需要知道第几个点,就能知道这个点在结构体中的位置(即下标)了,这样的话,根据之前已知的基本关系,就只需要直接一路更新上去即可。
- void UpdataTree(int ri){
-
- if (ri == 1)return;
- int fi = ri / 2;
- int a = node[fi<<1].value;
- int b = node[(fi<<1)+1].value;
- node[fi].value = (a > b)?(a):(b);
- UpdataTree(ri/2);
- }
【查询区间最大值】:
将一段区间按照建立的线段树从上往下一直拆开,直到存在有完全重合的区间停止。对照图例建立的树,假如查询区间为 [2,5]
![查询区间为[2,5] bubuko.com,布布扣](http://img.my.csdn.net/uploads/201208/06/1344268495_9443.jpg)
红色的区间为完全重合的区间,因为在这个具体问题中我们只需要比较这 三个区间的值 找出 最大值 即可。
- int Max = -1<<20;
- void Query(int i,int l,int r){
- if (node[i].left == l && node[i].right == r){
- Max = (Max < node[i].value)?node[i].value:(Max);
- return ;
- }
- i = i << 1;
- if (l <= node[i].right){
- if (r <= node[i].right)
- Query(i, l, r);
- else
- Query(i, l, node[i].right);
- }
- i += 1;
- if (r >= node[i].left){
- if (l >= node[i].left)
- Query(i, l, r);
- else
- Query(i, node[i].left, r);
- }
- }
线段树入门【转】
原文:http://www.cnblogs.com/ediszhao/p/3983494.html