您的位置:首页 > 理论基础 > 数据结构算法

算法导论14(数据结构的扩张)

2015-05-29 20:15 435 查看
14.1 动态顺序统计

顺序统计树(order-statistic tree)只是简单地在每个结点上存储附加信息的一颗红黑树,使得可以在O(logn)时间内确定任何的顺序统计量。

struct node
{
int key,color,size;
node *left,*right,*p;
node():color(BLACK){}
};

//查找具有给定秩的元素,时间复杂度为O(logn)。
node *OSSelect(node *x,int i)
{
int r=x->left->size+1;
if(i==r)return x;
else if(i<r)return OSSelect(x->left,i);
else return OSSelect(x->right,i-r);
}

//确定一个元素的秩,时间复杂度为O(logn)。
int OSRank(node *root,node *x)
{
int r=x->left->size+1;
node *y=x;
while(y!=root)
{
if(y==y->p->right)r+=y->p->left->size+1;
y=y->p;
}
return r;
}

//对子树规模的维护
//(1)插入:对由根至叶子的路径上遍历的每一个结点x,都增加x->size属性。新增加结点的size为1。
//(2)删除:我们只需要遍历一条由结点y(从它在树中的原始位置开始)至根的简单路径,并减少路径上每个结点的size属性的值。
//(3)在左旋和右旋中增加下面两行。
y->size=x->size;
x->size=x->left->size+x->right->size+1;


14.2 如何扩张数据结构

14.3 区间树

区间树(interval tree)是一种对动态集合进行维护的红黑树。

struct node
{
int key,color;
node *left,*right,*p;
pair<int,int> int;
node():color(BLACK){}
};

//判断i和j是否重叠。
bool overlap(pair<int,int> i,pair<int,int> j)
{
return i.first<j.second&&j.first<i.second;
}

//返回一个指向区间树中元素x的指针,使x->int与i重叠;若此元素不存在,则返回nil。时间复杂度为O(logn)。
node *intervalSearch(node *root,pair<int,int> i)
{
node *x=root;
while(x!=nil&&overlap(i,x->int))
{
if(x->left!=nil&&x->left->max>=i.first)x=x->left;
else x=x->right;
}
return x;
}

//对信息的维护
x->max=max(max(x->int.second,x->left->max),x->right->max);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: